findContours函数和drawContours函数是画轮廓很方便的函数
首先贴两张函数参数表,这是C++上的OpenCV
接下来分别看具体用法和参数格式
1. findContours
contours, hierarchy = cv2.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)
函数作用是画出0-1图thresh的轮廓。两个重要参数的shape
thresh.shape
(911, 911, 1)
contours.shape
*** AttributeError: 'list' object has no attribute 'shape'
len(contours)
5
contours[0].shape
(2, 1, 2)
contours[1].shape
(24, 1, 2)
contours[3].shape
(11, 1, 2)
contours[4].shape
(56, 1, 2)
2. drawContours
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
以上语句作用是画出点集的最小外接矩形,然后把Box2D结构变成四点的numpy数组形式,最后根据四点画出轮廓
重要参数的shape如下
cnt.shape
(95, 1, 2)
rect
((768.0, 852.5), (168.0, 49.0), -0.0) 分别表示旋转矩形的中心坐标,长宽,和旋转角度
box.shape
(4, 2)
box[0]的第一个元素表示横向方向离左上角的距离,第二个元素表示纵向方向离左上角的距离