我有一段Python代码,据说可以填充图像的轮廓,但是会留下其中包含的空洞不填充。这就是我想要的:
但这就是我得到的:
我尝试使用cv2指定轮廓层次结构进行填充,但是我无法得到想要的结果。
这是我尝试过的:
import numpy as np
import cv2
# Load the PNG image
img = cv2.imread('slice.png')
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Threshold the image to create a binary image
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
# Find the contours in the binary image
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Create a blank image with the same dimensions as the original image
filled_img = np.zeros(img.shape[:2], dtype=np.uint8)
# Iterate over the contours and their hierarchies
for i, contour in enumerate(contours):
# Check if the contour has a parent
if hierarchy[0][i][3] == -1:
# If the contour doesn't have a parent, fill it with pixel value 255
cv2.drawContours(filled_img, [contour], -1, 255, cv2.FILLED)
# Display the result
cv2.imshow('Original Image', img)
cv2.imshow('Filled Regions', filled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
我尝试修改“if hierarchy [0] [i] [3] == -1:”部分的-1、0、1值,但它要么填补较小的空洞,要么像我发布的第一张图片那样填满整个更大的轮廓。
更新
我还想用白色填充较小层次结构轮廓的内部,就像这样: