如何找到轮廓的不同特征,例如面积,周长,质心,边界框等?
轮廓面积
area = cv.contourArea(cnt)
轮廓周长
perimeter = cv.arcLength(cnt,True)
轮廓近似
epsilon = 0.1*cv.arcLength(cnt,True)
approx = cv.approxPolyDP(cnt,epsilon,True)
外接矩形
直角矩形,不考虑物体的旋转。所以边界矩形的面积不是最小的。它是由函数cv.boundingRect()找到的。
(x,y)为矩形的左上角坐标,而(w,h)为矩形的宽度和高度。
x, y, w, h = cv2.boundingRect(cnt) # 外接矩形
cv2.rectangle(img_color1, (x, y), (x + w, y + h), (0, 255, 0), 2)
旋转矩形是用最小面积绘制的,所以它也考虑了旋转。使用的函数是cv.minAreaRect()。
rect = cv2.minAreaRect(cnt) # 最小外接矩形
box = np.int0(cv2.boxPoints(rect)) # 矩形的四个角点取整
cv2.drawContours(img_color1, [box], 0, (255, 0, 0), 2)
最小外接圆
外接圆跟外接矩形一样,找到一个能包围物体的最小圆:
(x, y), radius = cv2.minEnclosingCircle(cnt)
(x, y, radius) = np.int0((x, y, radius)) # 圆心和半径取整
cv2.circle(img_color2, (x, y), radius, (0, 0, 255), 2)
拟合椭圆
把一个椭圆拟合到一个物体上。
ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img_color2, ellipse, (255, 255, 0), 2)