caveskelton
caveskelton

Reputation: 143

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?

Upvotes: 3

Views: 11770

Answers (3)

Cris Luengo
Cris Luengo

Reputation: 60484

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

Upvotes: 2

Leox
Leox

Reputation: 370

Similar result with morphology operations

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

Upvotes: 1

fmw42
fmw42

Reputation: 53081

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

Upvotes: 4

Related Questions