import cv2
import numpy as np
from matplotlib import pyplot as plt # Used for a colormap
img = cv2.imread('shapes.png') # Read input image.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale.
out = np.zeros_like(img) # Prepare output image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)[1] # Convert to binary image - use automatic thresholding
# Find contours with hierarchy, use cv2.RETR_TREE
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Get viridis colormap, and convert it to look up table:
cmap = plt.get_cmap('hsv')
# Iterate over the contours and their hierarchies
# Draw contours with different colors for marking that it's not one large contour
for i, contour in enumerate(contours):
if hierarchy[0][i][2] < 0:
color = np.round(np.array(cmap(i*57 % 255)[:-1])*255).astype(np.uint8) # Get the color from a colormap
# If contour has no child, draw the contour
cv2.drawContours(out, contours, i, tuple(color.tolist()), 3)
cv2.imwrite('out.png', out) # Save the result.
1条答案
按热度按时间mm5n2pyu1#
我们可以使用
RETR_TREE
找到具有层次结构的轮廓,并找到没有子轮廓的“内部轮廓”。当使用
RETR_TREE
时,空轮廓具有外轮廓和内轮廓。内部轮廓是分离的,因此只查找内部轮廓就解决了问题。
以下代码示例使用以下阶段:
if hierarchy[0][i][2] < 0
...代码示例:
输出: