如何在OpenCV-Python中填充Canny边缘图像

3
我有一张图片,例如: 一个透明背景的剑的图片 我使用Canny边缘检测器得到了这个图片: Canny边缘检测的输出 如何填充这个图片?我希望被边缘包围的区域是白色的。我该如何实现这个目标?

1
在进行一些形态学处理后,您可以使用洪水填充算法来确保图像闭合。或者您可以获取轮廓并将轮廓绘制为黑色背景上的白色填充。请参阅https://docs.opencv.org/4.1.1/d7/d1b/group__imgproc__misc.html#gaf1f55a048f8a45bc3383586e80b1f0d0和https://docs.opencv.org/4.1.1/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0。 - fmw42
1
为什么你需要整个物体却只关注边缘呢?为什么不使用已有的数百万种分割算法之一,而非Canny算法呢? - Cris Luengo
1
此外,您的PNG图像具有透明背景。您只需查看alpha通道,即可获得您所期望的输出。 - Cris Luengo
3个回答

4
你可以通过获取轮廓并在黑色背景上绘制它来在Python/OpenCV中完成这个操作。
输入:

enter image description here

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

结果:

enter image description here


2

这并没有回答问题。
这只是对问题的评论补充,评论不允许包含代码和图片。


示例图片具有透明背景。因此,alpha通道提供了您要查找的输出。即使没有任何图像处理知识,您也可以按照以下方式加载图像并提取alpha通道:

import cv2

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

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

output from code above, the sword is white and the background is black


1

形态学操作得到类似的结果

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)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接