用opencv python填充轮廓

时间:2013-10-07 10:23:56

标签: c++ python image opencv

我有二进制图像,其折线由:

创建
cv2.polylines(binaryImage,contours,1, (255,255,255))

我现在需要的是填充所有折线的有效方法。我还没有在opencv中找到这样的方法,但也许它存在。或者,也许我可以实现算法来完成这项工作(但快速 - 我有高清就绪图片)。请分享您的想法..

5 个答案:

答案 0 :(得分:21)

我认为你所寻找的是cv2.fillPoly,它填充了由一个或多个多边形限定的区域。这是一个简单的片段,我生成一个表示正方形顶点的四个点的轮廓,然后我用白色填充多边形。

import numpy as np
import cv2

contours = np.array( [ [50,50], [50,150], [150, 150], [150,50] ] )
img = np.zeros( (200,200) ) # create a single channel 200x200 pixel black image 
cv2.fillPoly(img, pts =[contours], color=(255,255,255))
cv2.imshow(" ", img)
cv2.waitKey()

enter image description here

答案 1 :(得分:16)

使用cv2.drawContours功能时,设置thickness=cv2.FILLED即可完成。

答案 2 :(得分:3)

您可以使用drawContours并将标记设置为FILLED

(代码是Java)

Imgproc.drawContours(mat, contours, contourID, COLOR, Core.FILLED);

您可以提供所需轮廓的ID以及要填充的颜色。

答案 3 :(得分:2)

如果轮廓是封闭的,则可以使用fillPolydrawContours。将@jabaldonedo和@ ash-ketchum组合在一起:

import cv2
import matplotlib.pyplot as plt
import numpy as np

# Lets first create a contour to use in example
cir = np.zeros((255,255))
cv2.circle(cir,(128,128),10,1)
_, contours, _ = cv2.findContours(cir.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# An open circle; the points are in contours[0]
plt.figure()
plt.imshow(cir)

# Option 1: Using fillPoly
img_pl = np.zeros((255,255))
cv2.fillPoly(img_pl,pts=contours,color=(255,255,255))
plt.figure()
plt.imshow(img_pl)

# Option 2: Using drawContours
img_c = np.zeros((255,255))
cv2.drawContours(img_c, contours, contourIdx=-1, color=(255,255,255),thickness=-1)
plt.figure()
plt.imshow(img_c)

plt.show()

img_pl和img_c都包含从轮廓[0]中的点开始的实心圆

答案 4 :(得分:0)

我知道 OP 专门询问了使用 OpenCV 的问题,但我最终在这里只是试图填充我所拥有的分割多边形(而且,OpenCV 对我的情况来说有点问题)库,我相信许多其他用户也这样做了也是,所以这是我使用 scikit imagepolygon function 的解决方案。

来自文档:

import matplotlib.pyplot as plt

from skimage.draw import line, polygon, circle, ellipse
import numpy as np


img = np.zeros((500, 500, 3), 'uint8')

# draw line
rr, cc = line(120, 123, 20, 400)
img[rr,cc,0] = 255

# fill polygon
poly = np.array((
    (300, 300),
    (480, 320),
    (380, 430),
    (220, 590),
    (300, 300),
))
rr, cc = polygon(poly[:,0], poly[:,1], img.shape)
img[rr,cc,1] = 255

# fill circle
rr, cc = circle(200, 200, 100, img.shape)
img[rr,cc,:] = (255, 255, 0)

# fill ellipse
rr, cc = ellipse(300, 300, 100, 200, img.shape)
img[rr,cc,2] = 255

plt.imshow(img)
plt.show()

结果: Filled polygons

相关问题