首页 > 解决方案 > 基于空间维度去除图像噪声

问题描述

我想使用 Python 从 RGB 图像的主要特征周围去除噪音“五彩纸屑”。理想情况下,此过程将使示例图像中心的大特征(斑点)保持不变。即是否可以仅在其面积低于给定值时去除噪声?

我曾尝试fastNlMeansDenoisingColored在示例图像上使用 OpenCV 的功能(见下文),但这会从图像的其余部分移除重要信号。

这是示例图像:

例子.png

也可以在这里下载

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()

代码结果

标签: pythonimageopencvnoise

解决方案


如果您只想要中央斑点,您可以选择寻找轮廓并选择具有最大面积的轮廓。

代码:

#--- 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)

在此处输入图像描述


推荐阅读