python - 如何在opencv-python中填充canny边缘图像

标签 python opencv image-processing image-segmentation contour

我有一张图片,例如: an image of a sword with a transparent background

我应用了 Canny 边缘检测器并得到了这张图片: output of Canny edge detection

如何填充这张图片?我希望边缘包围的区域是白色的。我如何实现这一点?

最佳答案

您可以在 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

关于python - 如何在opencv-python中填充canny边缘图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67285972/

相关文章:

python - 并非所有参数在字符串格式化 python 期间都会转换

c++ - cmake 找到 opencv 库的路径,但 make 没有找到 opencv 函数 Rodrigues

opencv - 关于使用opencv观看视频的问题

c++ - cvBlob/Opencv : Why is my output variable empty?

python - BIC 使用 scikit-learn 中的 GaussianMixture 过度拟合图像分割模型中的组件数量

algorithm - 如何过滤二值图像中不需要的区域和空洞区域

python - scrapy中 'slot'是什么意思?

python - numpy 中矩阵的 One-hot 表示

image-processing - 在不使用重映射的情况下将 OpenCV 中的每个像素向右移动(1px)?

python - 规范化 Pandas 数据框中的数据