繁体   English   中英

如何使用python在opencv中对噪声图像执行中值滤波

[英]How to perform median filter for noise image in opencv with python

我是OpenCV和Python的新手。 我想通过首先向图像添加噪声来执行高斯滤波器和中值滤波器。 我已经获得了高斯滤波器的成功输出,但是我没有得到中值滤波器,谁能解释一下如何在Python中使用Python对噪声图像执行OpenCV中值​​滤波。 以下是我的代码:

 import numpy as np

 import cv2

 img = cv2.imread('lizard.jpg').astype(np.float32)



 gaussian_blur = np.array([[1,2,1],[2,4,2],[1,2,1]],dtype=np.float32)
 gaussian_blur = gaussian_blur/np.sum(gaussian_blur)


 img_noise = img + np.random.uniform(-20,20,size=np.shape(img))

 cv2.imwrite('gt3_plus_noise.jpg',img_noise)
 median = cv2.medianBlur(img_noise.astype(np.float32),(3),0)
 cv2.imshow('Median Blur',median)
 cv2.waitKey()
 cv2.destroyAllWindows()
 img_blur_g = cv2.filter2D(img_noise.astype(np.float32), -1,gaussian_blur)

 cv2.imwrite('gt3_noise_filtered_gaussian.jpg',img_blur_g)

输出:

噪声滤波高斯

在此处输入图片说明

噪声图像

在此处输入图片说明

中值滤波图像

在此处输入图片说明

OpneCV在Python和C ++中具有函数meanBlur来执行中值过滤。 您可以从此处获取详细信息: http : //docs.opencv.org/2.4/modules/imgproc/doc/filtering.html#medianblur

要使用此功能,请遵循以下代码片段:

n=3; #where n*n is the size of filter
output_image = cv2.medianBlur(input_image, n)

当OpenCV具有float图像时,它将假定范围在0到1之间。但是,您的图像仍然具有介于0到255之间的值(可能在该值上下一些)。 可以很好地进行操作,但是要查看图像,您需要将其规格化为0和1 ,您必须将其转换回uint8图像并使其饱和。 当前,您的图片刚刚溢出1,这是浮动图片的假定最大值。 由于值很小,因此颜色仅显示在图像的较暗区域中。 具体来说,小于1。

饱和uint8图像的值意味着0以下的任何东西都固定为0,255以上的任何东西都固定为255。正常的numpy操作不会使值饱和,它们会溢出并翻转(因此np.array(-1).astype(np.uint8) ==> 255 ,表示减去了一些暗值的任何暗色值都会变亮。 有关饱和的更多信息,请参见此处

这个问题并不是很难解决,有很多解决方案。 一种明确的方法是简单地将大于255的值固定为255,并将小于0的值固定为0并转换为uint8图像:

>>> img = np.array([[150, 0], [255, 150]], dtype=np.float32)
>>> noise = np.array([[20, -20], [20, -20]], dtype=np.float32)
>>> noisy_img = img+noise
>>> noisy_img
array([[ 170.,  -20.],
       [ 275.,  130.]], dtype=float32)
>>> noisy_img[noisy_img>255] = 255
>>> noisy_img[noisy_img<0] = 0
>>> noisy_img = np.uint8(noisy_img)
>>> noisy_img
array([[170,   0],
       [255, 130]], dtype=uint8)

您还可以使用cv2.convertScaleAbs()进行饱和投射,这比较简单但不太明确:

>>> img = np.array([[150, 0], [255, 150]], dtype=np.float32)
>>> noise = np.array([[20, -20], [20, -20]], dtype=np.float32)
>>> noisy_img = img+noise
>>> cv2.convertScaleAbs(noisy_img)
array([[170,  20],
       [255, 130]], dtype=uint8)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM