Python OpenCV delete outermost edges after Canny Edge Detection

Viewed 1122

I have an image and after I use Canny Edge detection, I want to delete the outermost edge. I can't use a mask as the image will change.

This is how the result works: enter image description here

I want to delete the outermost edge so that I am left with only one edge, the outline of the cloud.

This is the current code:

import numpy as np
import cv2
import matplotlib.cm as cm
import matplotlib.pyplot as plt

img = cv2.imread('cloud.png',0)
edges = cv2.Canny(img,100,200)

plt.subplot(121)
plt.imshow(img,cmap = 'gray')
plt.title("Original Image")
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.imshow(edges,cmap = 'gray')
plt.title("Edge")
plt.xticks([])
plt.yticks([])
plt.show()

1 Answers

You can do this in several ways:

  1. Using morphological thinning on the original shape. Simply threshold the image and then apply the thinning algorithm (no need to apply the Canny edge detector)

code:

img = cv2.imread(p, cv2.IMREAD_GRAYSCALE)
_, img = cv2.threshold(img, 128, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
img = cv2.ximgproc.thinning(img)

output:

enter image description here

  1. Apply Canny edge detector and then apply findContours and only keep external contours:

code:

img = cv2.imread(p, cv2.IMREAD_GRAYSCALE)
canny = cv2.Canny(img, 50, 100)
_, contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, 
cv2.CHAIN_APPROX_NONE)
drawing_img = np.zeros_like(canny)
cv2.drawContours(drawing_img, contours, 0, (255), 1)

output:

enter image description here

Related