python - 如何清理这张图片(opencv-python)?

标签 python image opencv image-processing

我对opencv真的很陌生。如何在不丢失信息的情况下消除背景噪音?
我是从这个开始的:Otsu 对它进行了阈值化。我试过腐 eclipse 、膨胀、双边过滤。我的目标是在边界上得到一个矩形,这样我就可以透视变换阈值图片,但它很难找到轮廓。或者也许有不同的更好的方法?

最佳答案

这是在 Python/OpenCV 中执行此操作的一种方法。

  • 阅读输入
  • 模糊它
  • 转换为HSV并提取饱和 channel
  • 阈值饱和图像
  • 用形态关闭和打开清理它并保存为掩码
  • 重新创建您的 OTSU 阈值图像
  • 将黑色写入掩码为黑色(零)的 OTSU 图像
  • 为了比较,将黑色写入掩码为黑色(零)的输入图像
  • 保存结果

  • 输入:

    enter image description here
    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('circuit_board.jpg')
    
    # blur
    blur = cv2.GaussianBlur(img, (3,3), 0)
    
    # convert to hsv and get saturation channel
    sat = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)[:,:,1]
    
    # threshold saturation channel
    thresh = cv2.threshold(sat, 50, 255, cv2.THRESH_BINARY)[1]
    
    # apply morphology close and open to make mask
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
    morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
    mask = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel, iterations=1)
    
    # do OTSU threshold to get circuit image
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
    
    # write black to otsu image where mask is black
    otsu_result = otsu.copy()
    otsu_result[mask==0] = 0
    
    # write black to input image where mask is black
    img_result = img.copy()
    img_result[mask==0] = 0
    
    # write result to disk
    cv2.imwrite("circuit_board_mask.png", mask)
    cv2.imwrite("circuit_board_otsu.png", otsu)
    cv2.imwrite("circuit_board_otsu_result.png", otsu_result)
    cv2.imwrite("circuit_board_img_result.png", img_result)
    
    
    # display it
    cv2.imshow("IMAGE", img)
    cv2.imshow("SAT", sat)
    cv2.imshow("MASK", mask)
    cv2.imshow("OTSU", otsu)
    cv2.imshow("OTSU_RESULT", otsu_result)
    cv2.imshow("IMAGE_RESULT", img_result)
    cv2.waitKey(0)
    

    蒙版图片:

    enter image description here

    OTSU 阈值图像:

    enter image description here

    大通结果:

    enter image description here

    图像结果:

    enter image description here

    关于python - 如何清理这张图片(opencv-python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130257/

    相关文章:

    c# - 在消息框中插入图像

    html 幻灯片无法正确显示图像

    python - 来自solvePnP的输出与projectPoints不匹配

    python - Python/OpenCV 中的 cvClose?

    OpenCV:cvWarpAffine 未处理的异常

    Python 正则表达式 : alternative positive lookbehind assertion

    python - 如何从字符串中修剪空格?

    c# - C# 中 MSpaint 图像的图像步幅为 +1 字节,为什么?

    python - 计算 DataFrame 中标记化项目的单词数

    python - 输入和输出 numpy 数组到 h5py