计算机视觉:Opencv图像去噪
- 添加高斯噪声
- 添加椒盐噪声
- 均值滤波
- 中值滤波
- 高斯滤波
- 双边滤波
本博客针对某一原始图片添加高斯或椒盐噪声,再使用均值、中值、高斯和双边滤波对加噪图像进行去噪,相关函数如下所示。
添加高斯噪声
def clamp(pv):
if pv > 255:
return 255
if pv < 0:
return 0
else:
return pv
def gaussian_noise(image):
image_ori = image.copy()
h, w, c = image.shape
for row in range(h):
for col in range(w):
s = np.random.normal(0, 20, 3)
b = image[row, col, 0]
g = image[row, col, 1]
r = image[row, col, 2]
image[row, col, 0] = clamp(b + s[0])
image[row, col, 1] = clamp(g + s[1])
image[row, col, 2] = clamp(r + s[2])
cv2.imwrite('gaussian_noise_picture.png', image)
return image
添加椒盐噪声
def sp_noise(image):
prob = 0.01
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
cv2.imwrite('sp_noise_picture.png',output)
return output
均值滤波
def mean_filter(noise_img):
result = cv2.blur(noise_img, (5, 5))
cv2.imwrite('mean_filter_picture.png', result)
中值滤波
def median_filter(noise_img):
result = cv2.medianBlur(noise_img, 5)
cv2.imwrite("median_filter_picture.png", result)
高斯滤波
def gaussian_filter(noise_img):
gaussian_blurred = cv2.GaussianBlur(noise_img, (5, 5), 0)
cv2.imwrite('gaussian_filter_picture.png', gaussian_blurred)
双边滤波
def bilateral_filter(noise_img):
bilateral_blurred = cv2.bilateralFilter(noise_img, d=20, sigmaColor=50, sigmaSpace=15)
cv2.imwrite('bilateral_filter_picture.png', bilateral_blurred)