中值平滑指對鄰域中的像素點按灰度值進行排序,然后選擇該組的中值作為輸出的灰度值取募。
opencv提供的函數cv2.medianBlur(img, N)。
# -*-coding:utf-8-*-
import cv2 as cv
import numpy as np
import random
def salt(image,number):
? ? image= cv.cvtColor(image, cv.COLOR_BGR2GRAY)
????rows, cols= image.shape
????saltImage= np.copy(image)
????for i in range(number):
? ? ? ? randR= random.randint(0, rows-1)
????????randC= random.randint(0, cols-1)
????????saltImage[randR][randC]= 122
? ? return saltImage
def medianBlur(image1,winSize):
? ? # image1 = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
? ????? rows, cols= image1.shape
????????winH, winW= winSize
? ? ????halfWinH= (winH-1)//2
? ????? halfWinW= (winW-1)//2
? ????? medianBlurImage= np.zeros(image1.shape,image1.dtype)
for rin range(rows):
? ? ? ? for cin range(cols):
? ? ? ? ? ? rTop= 0 if r-halfWinH< 0 else r-halfWinH
????????????rBottom= rows- 1 if r+ halfWinH> rows-1 else r+halfWinH
????????????cLeft= 0 if c-halfWinW< 0 else c-halfWinW
????????????cRight= cols- 1 if c+halfWinW> cols- 1 else c+halfWinW
????????????region= image1[rTop:rBottom+ 1, cLeft:cRight+ 1]
????????????medianBlurImage[r][c]= np.median(region)
return medianBlurImage
if __name__== "__main__":
? ? print("---------------Hello python ------------")
????filename= ("polar.jpg")
????src= cv.imread(filename)
????cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
????cv.imshow("input image", src)
????src1= salt(src,1000)
????cv.imshow("src1", src1)
????medianBlurImage= medianBlur(src1, (3,3))
????cv.imshow("medianBlur", medianBlurImage)
????cv.waitKey(0)
????cv.destroyAllWindows()
可學習的網址:https://www.cnblogs.com/my-love-is-python/p/10391923.html