OpenCV学习笔记-轮廓特征

查找轮廓的不同特征,例如面积,周长,重心,边界框等

矩:cv.moments()
轮廓面积:cv.contourArea()

轮廓周长:cv.arcLength()
轮廓近似:cv.approxPolyDp()

边界矩形:cv.boundingRect()
最小外接矩形: cv.minAreaRect() cv.boxPoints()

最小外接圆:cv.minEnclosingCircle()
椭圆拟合:cv.ellipse()

直线拟合:cv.fitLine()

代码被我整合到一起了:


def measure_object(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
   
     ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
    cv.imshow( 'thresh image', thresh)
    
    copyImage, contours, hireachy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
   
     for i, contour in enumerate(contours):
          #轮廓面积
          area = cv.contourArea(contour)
          print( 'contour area', area)
    
         #轮廓周长(弧长)  
         perimeter = cv.arcLength(contour, True)
          print( 'contour perimeter', perimeter)
    
         #轮廓近似
        #所得到的近似多边形周长和源轮廓周长之间的最大差值,这个差值越小,近似多边形与源轮廓就越相似  
        epsilon = 0.01 * perimeter
        approx = cv.approxPolyDP(contour, epsilon, True)
        print( 'approx', approx)
        cv.drawContours(img, [approx], i, ( 255, 0, 255), 2)
        #图像的矩 可以计算重心,面积等,返回一个字典
        M = cv.moments(contour) print(M)
        #重心坐标
        cx = M[ 'm10']/M[ 'm00']
        cy = M[ 'm01']/M[ 'm00']
        cv.circle(img, (np.int(cx), np.int(cy)), 3, ( 0, 255, 255), - 1)
        print( 'center of gravity: (%f,%f)' % (cx,cy) )
        #边界矩阵  
        x, y, w, h = cv.boundingRect(contour)
        img = cv.rectangle(img, (x, y), (x+w, y+h), ( 0, 0, 255), 2)
        cv.imshow( 'contours image', img)
        #最小外接矩形  
        rect = cv.minAreaRect(contour) #[(x,y),(w,h),angle]  
        print(rect)
        box = cv.boxPoints(rect) #获取到最小矩阵的四个顶点box:[[x1, y1],[x2, y2],[x3, y3],[x4, y4]]  
        print(box)
        box = np.int0(box) #对box进行处理 这一步一定要进行  
        print(box) cv.drawContours(img, [box], i, ( 0, 255, 0), 1)
        # [box] #最小外接圆  
        (x, y), radius = cv.minEnclosingCircle(contour)
        center = ( int(x), int(y))
        cv.circle(img, center, int(radius), ( 255, 0, 0), 2)
        #椭圆拟合,返回值其实就是旋转边界矩形的内切圆  
        ellipse = cv.fitEllipse(contour)
        cv.ellipse(img, ellipse, ( 0, 255, 255), 2)
        #直线拟合  
        rows, cols = img.shape[: 2]
        [vx, vy, x, y] = cv.fitLine(contour, cv.DIST_L2, 0, 0.01, 0.01)
        left_y = int((-x*vy/vx) + y)
        right_y = int(((cols-x)*vy/vx) + y)
        cv.line(img, (cols- 1, right_y), ( 0, left_y), ( 255, 255, 0), 2)
        
        print(i)
        cv.imshow( 'contours image', img)

 

效果图:
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页