使用Python在OpenCV中检查轮廓面积
我尝试在新的 Python API(cv2)中使用 checkContour() 函数,结果发现如果我用 findContours 创建轮廓来检查,它是可以工作的,比如:
contours, hierarchy = cv2.findContours(imgGray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cv2.contourArea(contours[0])
但是,当我自己创建轮廓时,下面的代码就不行了:
contour = numpy.array([[0,0], [10,0], [10,10], [5,4]])
area = cv2.contourArea(contour)
它返回了一个错误:“error: (-215) contour.checkVector(2) >= 0 && (contour.depth() == CV_32F || contour.depth() == CV_32S) in function contourArea”
当我改成:
contour = numpy.array([[0,0], [10,0], [10,10], [5,4]], dtype=numpy.int32)
我得到了另一个错误:“error: (-210) The matrix can not be converted to point sequence because of inappropriate element type in function cvPointSeqFromMat”
我想知道如何让下面这段 C++ 文档中的代码:
vector<Point> contour;
contour.push_back(Point2f(0, 0));
contour.push_back(Point2f(10, 0));
contour.push_back(Point2f(10, 10));
contour.push_back(Point2f(5, 4));
double area0 = contourArea(contour);
在最新的 Python API(2.3)中运行?
1 个回答
34
这个应该可以用:
contour = numpy.array([[[0,0]], [[10,0]], [[10,10]], [[5,4]]])
area = cv2.contourArea(contour)