首页 > 解决方案 > 在 OpenCV 中填充圆圈

问题描述

我已经为此苦苦挣扎了一段时间。我一直在尝试在 Python 中的 OpenCV 中找出某种方法来填充完全黑白图像中的圆圈。

为了清楚起见,这张图片已经使用自适应阈值进行了阈值处理,但现在我有了这些我希望能够填充的环。理想情况下,用于填充圆圈的任何算法都应该能够用于我包含的两组图片。

如果有人可以在这方面提供任何指导,我将不胜感激。

算法之前: 算法之前

算法后: 算法后

算法之前: 算法之前

算法后: 算法后

标签: pythonalgorithmopencv

解决方案


在 Google 中进行简单搜索就会为您提供这篇文章,它准确地回答了您的问题。

我采用了该解决方案作为您的输入:

import cv2
import numpy as np

# Read image
im_in = cv2.imread("circles.jpg", cv2.IMREAD_GRAYSCALE)

# Threshold
th, im_th = cv2.threshold(im_in, 127, 255, cv2.THRESH_BINARY)

# Copy the thresholded image
im_floodfill = im_th.copy()

# Mask used to flood filling.
# NOTE: the size needs to be 2 pixels bigger on each side than the input image
h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)

# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0,0), 255)

# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)

# Combine the two images to get the foreground
im_out = im_th | im_floodfill_inv

# Display images.
cv2.imwrite("circles_filled.png", im_out)

输入文件 circles.png:

界

输出文件 circles_filled.png:

实心圆圈


推荐阅读