python - 如何从图像中去除小颗粒背景噪声?

标签 python image opencv image-processing computer-vision

我正在尝试从我拥有的图像中移除渐变背景噪声。我用 cv2 尝试了很多方法都没有成功。

sample

首先将图像转换为灰度,使其失去一些可能有助于找到轮廓的梯度。

Imgur

有人知道处理这种背景的方法吗?我什至尝试从角落取样并应用某种内核过滤器。

最佳答案

消除渐变的一种方法是使用 cv2.medianBlur() 通过取内核下所有像素的中值来平滑图像。然后要提取字母,您可以执行 cv2.adaptiveThreshold()

模糊消除了大部分渐变噪声。您可以更改内核大小以删除更多内容,但它也会删除字母的详细信息

enter image description here

自适应阈值图像提取字符。从您的原始图像来看,似乎在字母 cxz 上添加了渐变噪声,使其融入背景.

enter image description here

接下来我们可以执行cv2.Canny()来检测边缘并得到这个

enter image description here

然后我们可以使用cv2.morphologyEx()做形态学开运算,清理小噪声,增强细节

enter image description here

现在我们使用 cv2.dilate() 进行扩张以获得单个轮廓

enter image description here

从这里,我们使用 cv2.findContours() 找到轮廓。我们使用具有最小和最大面积的 cv2.contourArea() 遍历每个轮廓和过滤器以获得边界框。根据您的图像,您可能需要调整最小/最大区域过滤器。这是结果

enter image description here

import cv2
import numpy as np

image = cv2.imread('1.png')

blur = cv2.medianBlur(image, 7)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,3)

canny = cv2.Canny(thresh, 120, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)
dilate = cv2.dilate(opening, kernel, iterations=2)

cnts = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

min_area = 500
max_area = 7000
for c in cnts:
    area = cv2.contourArea(c)
    if area > min_area and area < max_area:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)

cv2.imshow('blur', blur)
cv2.imshow('thresh', thresh)
cv2.imshow('canny', canny)
cv2.imshow('opening', opening)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.waitKey(0)

关于python - 如何从图像中去除小颗粒背景噪声?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696080/

相关文章:

python - 在 pandas.to_numeric 中向下转换为 float16

python - Python 中的 Switch-case 不起作用;需要另一种模式

css - 当我向下滚动时背景变白,我哪里出错了? (我是新来的)

c++ - openCV 中的结果 compareHist

python - 运算符//= 和::做什么?

python - 在使用 Python 和 Beautiful Soup 4 抓取 Twitter 时关注特定结果?

android - webview图像放大点击android

Css 图像查看器在点击时移动页面

c - IplImage* 表 (IplImage**) 内的 cvCopy 出现段错误

Windows Server 2012 R2 x64 上带有 Python 3.6.4 的 OpenCV 导入 cv2 : DLL not found