如何从轮廓的质心到轮廓的周长绘制一条线?

时间:2016-03-30 16:11:33

标签: python opencv

我正在使用这样的时刻获得轮廓的质心:

cnt = np.vstack([cnt[0]]).squeeze()
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

我想将轮廓分成4个象限,因此需要绘制两条线,一条垂直线和一条水平线,两条线都穿过获得的质心。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

虽然这看起来像是OpenCV的任务,但您可能需要查看Shapely包:

http://toblerity.org/shapely/manual.html

Shapely允许您计算多边形之间的交点,因此解决方案变得非常简单:对于穿过轮廓质心的水平线和垂直线,您只需计算与轮廓的交点并绘制线到这些交叉点

缺少原始图,我使用椭圆来演示解决方案。既然你说你的轮廓只有一些样本点,我就用了一个“粗略”的椭圆,它只是几个点的近似值。

输出看起来像这样,希望这就是你要找的东西:

enter image description here

由于所有可视化,源代码很长,但希望能够自我解释:

import shapely.geometry as shapgeo
import numpy as np
import cv2

def make_image():
    img = np.zeros((500, 500), np.uint8)
    white = 255
    cv2.ellipse( img, (250, 300), (100,70), 30, 0, 360, white, -1 )
    return img


if __name__ == '__main__':
    img = make_image()

    #Create a "coarse" ellipse 
    _, contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]
    h, w = img.shape[:2]
    vis = np.zeros((h, w, 3), np.uint8)
    cv2.drawContours( vis, contours, -1, (128,255,255), 1)

    #Extract contour of ellipse
    cnt = np.vstack([contours[0]]).squeeze()

    #Determine centroid
    M = cv2.moments(cnt)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    print cx, cy

    #Draw full segment lines 
    cv2.line(vis,(cx,0),(cx,w),(150,0,0),1)
    cv2.line(vis,(0,cy),(h,cy),(150,0,0),1)


    # Calculate intersections using Shapely
    # http://toblerity.org/shapely/manual.html
    PolygonEllipse= shapgeo.asLineString(cnt)
    PolygonVerticalLine=shapgeo.LineString([(cx,0),(cx,w)])
    PolygonHorizontalLine=shapgeo.LineString([(0,cy),(h,cy)])

    insecv= np.array(PolygonEllipse.intersection(PolygonVerticalLine)).astype(np.int)
    insech= np.array(PolygonEllipse.intersection(PolygonHorizontalLine)).astype(np.int)
    cv2.line(vis,(insecv[0,0], insecv[0,1]),(insecv[1,0], insecv[1,1]),(0,255,0),2)
    cv2.line(vis,(insech[0,0], insech[0,1]),(insech[1,0], insech[1,1]),(0,255,0),2)

    cv2.imshow('contours', vis)

    0xFF & cv2.waitKey()
    cv2.destroyAllWindows()