Lee Lee - 4 months ago 16
Python Question

python edge detector - mask the area were it's completly black

I have used canny edge detector on an image.
It detected some areas in the image and other areas it displays nothing.
Now, I want that on the original image it would mask the areas that were completely black.
How can I do it?

I am using python and skimage or opencv (doesn't matter which one)

from skimage.feature import canny
from skimage.morphology import closing
import skimage.io
import numpy as np
import os
import matplotlib.pyplot as plt
import cv2

img = skimage.io.imread("test.jpg",as_grey=True)
fig, ax = plt.subplots(1, 1, figsize=(20,20))
ax.imshow(img,'gray')
ax.set_axis_off()
plt.show()

edges = canny(img)

close = closing(edges)

fig, ax = plt.subplots(1, 1, figsize=(20,20))
ax.imshow(close,'gray')
ax.set_axis_off()
plt.show()


Original Image
After canny and closing

Now what I want is that the white part(in the second image) would be the only part that would be displayed in the original image ( Masking )

Answer

You can simply apply a binary mask on a RGB image using:

close_BGR = cv2.cvtColor(close, cv2.COLOR_GRAY2BGR)
# Assuming that the img is of RGB format
masked_image = cv2.min(close_BGR, img)