Search code examples
pythonopencvmatplotlibcontourarea

Calculate contour area with opencv for contours created by matplotlib


I need to calculate the area limited by a contour line. I use matplotlib to get the vertices of the contour line, but I am not able to convert them into a valid input for contourArea method in openCV:

Z = z_func(X, Y, Ql, k[i,j], B)
cs = plt.contour(X, Y, Z,[IncT])
v = cs.collections[0].get_paths()[0].vertices
xy = []
for vv in v:
    xy.append(vv[0])
cnt = np.array(xy)
area = cv2.contourArea(cnt)

I get this error: ......\opencv-2.4.9.1\modules\imgproc\src\contours.cpp:1904: error: (-215) contour.checkVector(2) >= 0 && (contour.depth() == CV_32F || contour.depth() == CV_32S) in function cv::contourArea

: EOF when reading a line

Could anyone help me? Thanks in advance!!!


Solution

  • Finally, I didn't use cv2.contourArea method. Only get the Y component of vertices, sum their absolute values and multiply by the grid size:

    x = arange(-1.0,10.0,0.05)
    y = arange(-1.0,1.0,0.05)
    
    X,Y = meshgrid(x, y) # grid of point
    
    cs = plt.contour(X, Y, Z,[IncT])
    p = cs.collections[0].get_paths()[0]
    v = p.vertices
    y = v[:,1]
    s[i,j]=sum(abs(y))*0.05