if n > 5 : while n > 5 : if med == 0 : break n = n - int(Histogram[med]) med = med - 1 elif n < 5 : while n < 5 : med = med + 1 n = n + int(Histogram[med])
# b = medianBlurChannel(b) # g = medianBlurChannel(g) # r = medianBlurChannel(r) b = fastMedianBlurChannel(b) g = fastMedianBlurChannel(g) r = fastMedianBlurChannel(r)
import cv2 import numpy import copy import datetime # 对于单一通道进行中值滤波 defmedianBlurChannel(channel): channel2 = copy.copy(channel) for x inrange(1,len(channel)-1): for y inrange(1,len(channel[0])-1): channel2[x][y]=numpy.median(channel[x-1:x+2,y-1:y+2]) return channel2
# 快速中值滤波 deffastMedianBlurChannel(channel): channel2 = copy.copy(channel) for x inrange(1,len(channel)-1): # 初始化直方图 Histogram = numpy.zeros(256,dtype=int) # 对每一列的第一个像素初始化 # 它的颜色取channel[x][1]它及周围的八个像素的颜色的中位数 med = int(numpy.median(channel[x-1:x+2,0:3])) # 用n确定中值的偏移量 n = 0 for i inrange(-1,2): for j inrange(0,3): Histogram[channel[x+i][j]] = Histogram[channel[x+i][j]] +1 if channel[x+i][j] <= med : n = n + 1 for y inrange(1,len(channel[0])-1): if y == 1: pass else : # 更新直方图,并更新n的值 for i inrange(-1,2) : # 在直方图中删除下方不用的像素 Histogram[channel[x+i][y-2]] = Histogram[channel[x+i][y-2]] - 1 if channel[x+i][y-2] <= med : n = n - 1 # 在直方图中添加上方要用的像素 Histogram[channel[x+i][y+1]] = Histogram[channel[x+i][y+1]] + 1 if channel[x+i][y+1] <= med : n = n + 1 # 更新 med 的值 if n > 5 : while n > 5 : if med == 0 : break n = n - int(Histogram[med]) med = med - 1 elif n < 5 : while n < 5 : med = med + 1 n = n + int(Histogram[med]) # 存入结果 channel2[x][y] = med return channel2
# 对图像进行中值滤波 defmedianBlur(image): shape = list(image.shape) iflen(shape) != 3: print("请输入三通道的图像!") return else: b,g,r=cv2.split(image) # b = medianBlurChannel(b) # g = medianBlurChannel(g) # r = medianBlurChannel(r) b = fastMedianBlurChannel(b) g = fastMedianBlurChannel(g) r = fastMedianBlurChannel(r) return cv2.merge([b,g,r])