简体   繁体   中英

Python OpenCV delete outermost edges after Canny Edge Detection

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: 在此处输入图像描述

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

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:

在此处输入图像描述

  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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM