python - 在OpenCV中删除图像中的噪声而不会丢失数据

标签 python image opencv image-preprocessing

我用这个代码:

    horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontalsize, 1))
    horizontal = cv2.erode(horizontal, horizontalStructure, (-1, -1))
    horizontal = cv2.dilate(horizontal, horizontalStructure, (-1, -1))

删除线。

以及一些过滤器,用于删除噪点并加粗字体:
 blur = cv2.GaussianBlur(img, (11, 11), 0)
 thresh = cv2.threshold(blur, 80, 255, cv2.THRESH_BINARY)[1]
 kernel = np.ones((2,1), np.uint8)
 dilation = cv2.erode(thresh, kernel, iterations=1)
 dilation = cv2.bitwise_not(dilation)

尽管有阈值和其他方法,您仍然可以看到很多噪音

,这是我想要达到的结果:

您知道一个OpenCV过滤器可以帮助我实现这一结果吗?

最佳答案

以下解决方案不是完美的解决方案,也不是通用的解决方案,但我希望它足以满足您的需求。

为了删除该行,我建议使用cv2.connectedComponentsWithStats查找簇,并屏蔽宽或长簇。

该解决方案使用以下阶段:

  • 将图像转换为灰度。
  • 应用阈值并反转极性。
    通过应用标志cv2.THRESH_OTSU使用自动阈值。
  • 使用“关闭”形态操作来缩小小差距。
  • 查找具有统计信息的连接的组件(集群)。
  • 遍历集群,并删除具有较大宽度和较大高度的集群。
    去除非常小的簇-被认为是噪音。
  • “手动”清洁顶部和左侧。

  • 这是代码:
    import numpy as np
    import cv2
    
    img = cv2.imread('Heshbonit.jpg')  # Read input image
    
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # Convert to Grayscale.
    
    ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)  # Convert to binary and invert polarity
    
    # Use "close" morphological operation to close small gaps
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, np.array([1, 1]));
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, np.array([1, 1]).T);
    
    nlabel,labels,stats,centroids = cv2.connectedComponentsWithStats(thresh, connectivity=8)
    
    thresh_size = 100
    
    # Delete all lines by filling wide and long lines with zeros.
    # Delete very small clusters (assumes to be noise).
    for i in range(1, nlabel):
        #
        if (stats[i, cv2.CC_STAT_WIDTH] > thresh_size) or (stats[i, cv2.CC_STAT_HEIGHT] > thresh_size):
            thresh[labels == i] = 0
        if stats[i, cv2.CC_STAT_AREA] < 4:
            thresh[labels == i] = 0
    
    # Clean left and top margins "manually":
    thresh[:, 0:30] = 0
    thresh[0:10, :] = 0
    
    # Inverse polarity
    thresh = 255 - thresh
    
    # Write result to file
    cv2.imwrite('thresh.png', thresh)
    

    关于python - 在OpenCV中删除图像中的噪声而不会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740506/

    相关文章:

    python - 当使用 eventlet 运行 celery 时,Fabric 失败并显示 Name lookup failed

    python - Jenkins:将我的 Python 模块放在 PYTHONPATH 上

    ios - 将图像转换为 CGBitmapContext

    mysql - 在使用 mysql 的 spring/java 应用程序中处理大量图像,有些小 - 有些大

    python - 如何计算移动物体的速度

    c++ - 使用 OpenCV C++ 创建遵循高斯分布的图像

    python - Bokeh:编辑图中的所有选项

    python - 安装 gunicorn 的语法错误

    c# - Xamarin.Forms UWP 图像永远不会关闭打开的文件

    c - cvWriteFrame 返回值是什么意思?