填充轮廓的圆圈

Sal*_* A. 7 python opencv image image-processing python-imaging-library

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

样本图片

我尝试使用嵌套循环来实现此目的,但是这需要很多时间,并且我拥有约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
Run Code Online (Sandbox Code Playgroud)

nat*_*ncy 5

使用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()
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*ell 5

我尝试找到白色轮廓的边界框,并找到它的中心,然后从那里向外填充白色。

\n\n
#!/usr/bin/env python3\n\nimport cv2\n\ndef findfill(image):\n    thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n    cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n    cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n    cv2.fillPoly(image, cnts, [255,255,255])\n\ndef me(image):\n    x,y,w,h = cv2.boundingRect(image)\n    cv2.floodFill(image,None,(int(x+w/2),int(y+h/2)),255)\n    return image\n\nimage = cv2.imread('BLYmz.png', 0)\n\n%timeit findfill(image)\n%timeit me(image)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这似乎给出了相同的结果,并且运行速度提高了 2.5 倍:

\n\n
findfill\n810 \xc2\xb5s \xc2\xb1 2.94 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\n\nme\n343 \xc2\xb5s \xc2\xb1 1.06 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n\n

当然,如果你有 150 万个任务要做,我也会推荐一些并行处理:-)

\n