gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:13:47 26 4
gpt4 key购买 nike

我有一张图片,例如: 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com