我想使用Python从RGB图像的主要特征周围消除噪点“五彩纸屑”。理想情况下,此过程将使示例图像中心的大特征(斑点)保持不变。即,仅当噪声的面积低于给定值时,才可以去除噪声吗?
我尝试在示例图像上使用OpenCV的fastNlMeansDenoisingColored
函数(请参见下文),但这会从其余图像中去除明显的信号。
这是示例图片:
也可以是downloaded here。
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('example.png')
dst = cv2.fastNlMeansDenoisingColored(img,None,10,7,21)
# Original
plt.imshow(img)
plt.show()
print(np.nanmin(img),np.nanmax(img))
# denoised
plt.imshow(dst)
print(np.nanmin(dst),np.nanmax(dst))
plt.show()
# difference
plt.imshow(img-dst)
plt.show()
答案 0 :(得分:3)
如果只想要中央斑点,则可以选择查找轮廓并选择面积最大的轮廓。
代码:
#--- convert image to grayscale ---
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
#--- Perform Otsu threshold ---
ret2, th2 = cv2.threshold(imgray,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow('Threshold', th2)
它产生一个二进制图像:
#--- Finding contours using the binary image ---
_, contours, hierarchy = cv2.findContours(th2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#--- finding the contour with the maximum area ---
big_contour = 0
max_area = 0
for cnt in contours:
if (cv2.contourArea(cnt) > max_area):
max_area = cv2.contourArea(cnt)
big_contour = cnt
#--- creating a mask containing only the biggest contour ---
mask = np.zeros(imgray.shape)
cv2.drawContours(mask, [big_contour], 0, (255,255,255), -1)
cv2.imshow('Mask', mask)
#--- masking the image above with a copy of the original image ---
im2 = im.copy()
fin = cv2.bitwise_and(im2, im2, mask = mask.astype(np.uint8))
cv2.imshow('Final result', fin)