用opencv python填充轮廓
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19222343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filling contours with opencv python
提问by user2233244
I have binary image with polylines created with:
我有使用以下方法创建的折线的二进制图像:
cv2.polylines(binaryImage,contours,1, (255,255,255))
What I need now is effective method to fill all polylines. I haven't found such method in opencv, but maybe it exists. Alternatively, maybe I could implement algorithm to do the job (but fast one- I have HD ready pictures). Please share your thoughts..
我现在需要的是填充所有折线的有效方法。我还没有在 opencv 中找到这样的方法,但也许它存在。或者,也许我可以实现算法来完成这项工作(但速度很快——我有高清图片)。请分享您的想法..
回答by jabaldonedo
I think what you are looking for is cv2.fillPoly
, which fills the area bounded by one or more polygons. This is a simple snippet, I generate a contour of four points representing vertices of a square, then I fill the polygon with a white color.
我认为您正在寻找的是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()
回答by Mahm00d
You can use drawContours
with the flag set as FILLED
:
您可以drawContours
将标志设置为FILLED
:
(code is in Java)
(代码是Java)
Imgproc.drawContours(mat, contours, contourID, COLOR, Core.FILLED);
You give the ID of the desired contour and the color you want it to be filled with.
您提供所需轮廓的 ID 以及要填充的颜色。
回答by Ash Ketchum
While using cv2.drawContours
function, set thickness=cv2.FILLED
and you are done.
使用cv2.drawContours
功能时,设置即可thickness=cv2.FILLED
。
回答by Brian
You can use fillPolyor drawContoursif your contour is closed. Pulling together @jabaldonedo and @ash-ketchum answers:
如果您的轮廓是闭合的,您可以使用fillPoly或drawContours。将@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()
both img_pl and img_c contain a filled in circle from the points in contour[0]
img_pl 和 img_c 都包含一个来自轮廓 [0] 中点的填充圆圈