【问题标题】:How to fill canny edge image in opencv-python如何在opencv-python中填充canny边缘图像
【发布时间】:2021-07-20 23:14:25
【问题描述】:

我有一张图片,例如:

我应用 Canny 边缘检测器并获得此图像:

如何填充此图像?我希望边缘包围的区域是白色的。我如何做到这一点?

【问题讨论】:

  • 你可以在做一些形态后做floodfill,以确保它是关闭的。或者您可以获取轮廓并将轮廓绘制为黑色背景上填充的白色。见docs.opencv.org/4.1.1/d7/d1b/…docs.opencv.org/4.1.1/d3/dc0/…
  • 如果您需要整个对象,为什么要获得边缘?为什么不使用一百万种现有的分割算法来代替 Canny?
  • 另外,您的 PNG 图像具有透明背景。您需要做的就是查看 Alpha 通道,然后您就会得到您正在寻找的输出。

标签: python opencv image-processing image-segmentation contour


【解决方案1】:

这不能回答问题。
这只是我对这个问题的评论的补充,cmets 不允许代码和图像。


示例图像具有透明背景。因此,Alpha 通道提供了您正在寻找的输出。在没有任何图像处理知识的情况下,您可以加载图像并提取 alpha 通道,如下所示:

import cv2

img = cv2.imread('base.png', cv2.IMREAD_UNCHANGED)
alpha = img[:,:,3]

cv2.imshow('', alpha); cv2.waitKey(0); cv2.destroyAllWindows()

【讨论】:

    【解决方案2】:

    与形态学操作相似的结果

    img=cv2.imread('base.png',0)
    _,thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
    rect=cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilation = cv2.dilate(thresh,rect,iterations = 5)
    erosion = cv2.erode(dilation, rect, iterations=4)
    

    【讨论】:

      【解决方案3】:

      您可以在 Python/OpenCV 中通过获取轮廓并将其绘制成白色填充在黑色背景上来做到这一点。

      输入:

      import cv2
      import numpy as np
      
      # Read image as grayscale
      img = cv2.imread('knife_edge.png', cv2.IMREAD_GRAYSCALE)
      hh, ww = img.shape[:2]
      
      # threshold
      thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]
      
      # get the (largest) contour
      contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
      contours = contours[0] if len(contours) == 2 else contours[1]
      big_contour = max(contours, key=cv2.contourArea)
      
      # draw white filled contour on black background
      result = np.zeros_like(img)
      cv2.drawContours(result, [big_contour], 0, (255,255,255), cv2.FILLED)
      
      # save results
      cv2.imwrite('knife_edge_result.jpg', result)
      
      cv2.imshow('result', result)
      cv2.waitKey(0)
      cv2.destroyAllWindows()
      

      结果:

      【讨论】:

        猜你喜欢
        • 2021-03-27
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 2017-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多