Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill canny edge image in opencv-python

I have an image, for example: an image of a sword with a transparent background

I apply the Canny edge detector and get this image: output of Canny edge detection

How do I fill this image? I want the area enclosed by the edges to be white. How do I achieve this?

like image 362
caveskelton Avatar asked Feb 19 '26 13:02

caveskelton


2 Answers

You can do that in Python/OpenCV by getting the contour and drawing it white filled on a black background.

Input:

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

Result:

enter image description here

like image 117
fmw42 Avatar answered Feb 22 '26 01:02

fmw42


This doesn't answer the question.
It is just an addition to my comment on the question, comments don't allow code and images.


The example image has a transparent background. Therefore, the alpha channel gives the output you're looking for. Without any knowledge of image processing, you can load the image and extract the alpha channel as follows:

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

like image 38
Cris Luengo Avatar answered Feb 22 '26 03:02

Cris Luengo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!