如何填充触摸图像边界的轮廓?



我有图像,我从亮度阈值上绘制轮廓,轮廓从内部填充之后。我遇到的问题是填充触及边界的轮廓。

最近的尝试是在图像周围添加边框并在轮廓填充后删除它们,但它并不适用于所有文件。

显示的问题示例[1]: https://i.stack.imgur.com/icrgR.jpg

我对解决这个问题的新方法持开放态度,提前谢谢你。

#open the image as a numpy array, in grayscale
img_input = cv2.imread(input_folder + "\" + filename, cv2.IMREAD_GRAYSCALE)
#blur for more accurate contour detection
img_blurred = cv2.GaussianBlur(img_input, (5,5), cv2.BORDER_DEFAULT)
#contour selection with otsu's threshold
image = cv2.threshold(img_blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
#border creation to fill border hitting contours
row, col = image.shape[:2]
bottom = image[row - 2:row, 0:col]
mean = cv2.mean(bottom)[0]
bordersize = 10
image = cv2.copyMakeBorder(
image,
top=bordersize,
bottom=bordersize,
left=bordersize,
right=bordersize,
borderType=cv2.BORDER_CONSTANT,
value=255
)
#border hole creation so the whole image doesnt get filled due to continous contour by the borders
image[100:101,0:10] = [0]
#filling the contours
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cv2.fillPoly(image, cnts, [255, 255, 255])
#removing the created borders
y, x = image.shape
final_img = image[10:y-10, 10:x-10]
#saving the file
cv2.imwrite(output_folder + "\" + filename[:-4] + ".png", final_img)
image = cv2.copyMakeBorder(
image,
top=bordersize,
bottom=bordersize,
left=bordersize,
right=bordersize,
borderType=cv2.BORDER_CONSTANT,
value=0
)

我认为value=0比value=255好。

最新更新