首页 > 解决方案 > 填充一个轮廓的圆圈

问题描述

我有一组图像,其中一个圆圈绘制为白色轮廓。但是,我想用白色填充整个圆圈。什么是快速的方法?以下是图像示例:

示例图像

我曾尝试使用嵌套循环来实现这一点,但这需要很长时间,而且我有大约 150 万张图像。以下是我的代码:

roundRobinIndex = 0
new_image = np.zeros((img_w, img_h))
for row in range(540):
    for column in range(800):
        if image[row,column] == 255:
            roundRobinIndex = (roundRobinIndex + 1) % 2
        if roundRobinIndex == 1:
            new_image[row, column] = 255

标签: pythonimageopencvimage-processingpython-imaging-library

解决方案


用于cv2.fillPoly()填充圆形轮廓

在此处输入图像描述

import cv2

image = cv2.imread('1.png', 0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cv2.fillPoly(image, cnts, [255,255,255])

cv2.imshow('image', image)
cv2.waitKey()

注意:由于输入图像已经是二值图像,可以去除 Otsu 的阈值以获得稍快的性能,您可以直接在灰度图像上找到轮廓


推荐阅读