簡體   English   中英

如何在opencv-python中填充canny邊緣圖像

[英]How to fill canny edge image in opencv-python

我有一張圖片,例如: 具有透明背景的劍的圖像

我應用 Canny 邊緣檢測器並獲得此圖像: Canny邊緣檢測的輸出

如何填充此圖像? 我希望邊緣包圍的區域是白色的。 我如何實現這一目標?

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

結果:

在此處輸入圖像描述

這不能回答問題。
這只是我對該問題的評論的補充,評論不允許代碼和圖像。


示例圖像具有透明背景。 因此,Alpha 通道提供了您正在尋找的 output。 在沒有任何圖像處理知識的情況下,您可以加載圖像並提取 alpha 通道,如下所示:

import cv2

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

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

上面代碼的輸出,劍是白色的,背景是黑色的

與形態學運算類似的結果

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)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM