[英]How to draw contours using opencv in Python?
I have following image preprocessed: 我已经对以下图像进行了预处理:
Now I want to use findContours
method in order to find cells from image and then use drawContours
in order draw contour for every cell from image. 现在,我想使用findContours
方法从图像中查找单元格,然后使用drawContours
为图像中的每个单元格绘制轮廓。 I do this but nothing is shown. 我这样做,但是什么也没显示。
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
I receive the following error. 我收到以下错误。
contours is not a numpy array, neither a scalar 轮廓不是numpy数组,也不是标量
Another answers didn't helped me. 另一个答案对我没有帮助。
I also use following solution. 我也使用以下解决方案。
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
ctr = numpy.array(contours).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(img, ctr, -1, (0, 255, 0), 3)
But this solution didn't draw anything on the given image. 但是此解决方案并未在给定图像上绘制任何内容。
Update , OpenCV 4.0 change the cv2.findContours
. 更新 ,OpenCV 4.0更改cv2.findContours
。 So I modify the code example. 因此,我修改了代码示例。 And a more general way: 还有更一般的方法:
cnts, hiers = cv2.findContours(...)[:-2]
cv2.findContours
returns a tuple, not just the contours. cv2.findContours
返回一个元组,而不仅仅是轮廓。 You can do like this: 您可以这样:
## Find contours
if cv2.__version__.startswith("3."):
_, contours, _ = cv2.findContours(bimg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(bimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
## Draw contours
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
Related similar questions: 相关类似问题:
(1) Python Opencv drawContour error (1) Python Opencv drawContour错误
(2) How to use `cv2.findContours` in different OpenCV versions? (2) 如何在不同的OpenCV版本中使用`cv2.findContours`?
The tuple returned by cv2.findContours
has the form (im, contours, hierarchy)
where im
is the image with contours visualized, contours
is a tuple of two numpy arrays in the form (x_values, y_values)
and heirarchy
depends on the retrieval mode. cv2.findContours
返回的元组具有以下形式(im, contours, hierarchy)
,其中im
是具有可视化contours
的图像, contours
是具有两个numpy数组的元组,形式为(x_values, y_values)
并且heirarchy
取决于检索模式。 Since you are using CV_RETR_EXTERNAL, heirarchy
doesn't have much significance. 由于您使用的是CV_RETR_EXTERNAL,所以heirarchy
没有太大的意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.