使用Opencv python的省略号出错

时间:2018-04-03 16:58:14

标签: python python-3.x opencv computer-vision opencv-contour

我有一个输入图像,想在所有找到的轮廓上绘制椭圆。我正在使用python-opencv并收到以下错误。谁能帮我这个?我知道绘制椭圆,但不确定如何绘制图像中每个检测到的对象。我是这个地区的新手,所以请原谅我这个愚蠢的问题。

OpenCV Error: Incorrect size of input array (There should be at least 5 points to fit the ellipse) in cv::fitEllipse, file 
C:\bld\opencv_1498171314629\work\opencv-3.2.0\modules\imgproc\src\shapedescr.cpp, line 358
Traceback (most recent call last):
File "D:/project/test.py", line 41, in <module>
ellipse = cv2.fitEllipse(contours[0])
cv2.error: C:\bld\opencv_1498171314629\work\opencv- 
3.2.0\modules\imgproc\src\shapedescr.cpp:358: error: (-201) There should be 
at least 5 points to fit the ellipse in function cv::fitEllipse

2 个答案:

答案 0 :(得分:2)

使用ellipse=cv2.fitEllipse(contours[0]),你只需 第一个轮廓,它少于5个点...你应该遍历所有轮廓并只绘制超过5个点的轮廓......

尝试这样的事情:

import numpy as np
import cv2

image=cv2.imread("cell.jpg")

grey=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) 
grey_hist=cv2.calcHist([grey],[0],None,[256],[0,256])
eq=cv2.equalizeHist(grey)
blurredA1=cv2.blur(eq,(3,3))

(T,thresh)=cv2.threshold(blurredA1,190,255,cv2.THRESH_BINARY)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
  for i in range(len(contours)):
    if len(contours[i]) >= 5:
      cv2.drawContours(thresh,contours,-1,(150,10,255),3)
      ellipse=cv2.fitEllipse(contours[0])
    else:
      # optional to "delete" the small contours
      cv2.drawContours(thresh,contours,-1,(0,0,0),-1)

cv2.imshow("Perfectlyfittedellipses",thresh)
cv2.waitKey(0)

正如你所看到的,我迭代了所有的轮廓并检查它是否大于5.此外,我添加了一些东西来覆盖所有不够大的轮廓。

答案 1 :(得分:0)

我不知道你的输入图像是什么,所以这可能会或可能不会。在查找轮廓函数中使用cv2.RETR_EXTERNAL时,它仅返回外部轮廓。相反,请使用'cv2.RETR_TREE'。

这将检索所有轮廓并重建嵌套轮廓的完整层次结构。有关文档,请参阅here。您的代码应更改如下。

im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

希望这会有所帮助。如果它不起作用,那么如果您可以上传输入图像以便我们可以使用它就会很棒!

此外,至于在找到的每个轮廓上放置一个椭圆,就像上面提到的api55,你只在第一个轮廓上尝试拟合椭圆。希望他的回答可以帮助你。如果要在最大轮廓上放置椭圆,可以根据它们的面积对找到的轮廓进行排序,然后在最大轮廓上或在大于特定尺寸的轮廓上拟合椭圆。