1 任务描述:
绘制图中粗线矩形的2个边界,并找到其边界的中心线
2.函数原型
findContours( InputOutputArray image, OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method, Point offset=Point());
vector> contours;
向量,向量内每个元素保存了一组由连续的Point点构成的点的集合的向量,每一组Point点集就是一个轮廓,有多少轮廓,向量contours就有多少元素- import numpy as np
- import cv2
-
-
- img = cv2.imread('test2.jpg')
-
- # 图像预处理
- #将图像转换成二值图像
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- binary = cv2.Canny(gray, 30, 120)
- #查找所有矩形的轮廓
- contours, hierarchy = cv2.findContours(binary,
- cv2.RETR_LIST,
- cv2.CHAIN_APPROX_SIMPLE)
- cv2.imshow('origin', img)
- cv2.imshow('Canny', binary)
-
- draw_img = img.copy()
- # 计算矩形框的四个顶点坐标
- rect = cv2.minAreaRect(contours[1])
- box = cv2.boxPoints(rect)
- box = np.int0(box)
- print(box)
- cv2.drawContours(draw_img, [box], 0, (0, 0, 255), 2)
-
- rect1 = cv2.minAreaRect(contours[3])
- box1 = cv2.boxPoints(rect1)
- box1 = np.int0(box1)
- print(box1)
- # 绘制轮廓
- cv2.drawContours(draw_img, [box1], 0, (0, 255, 0),2)
-
- box2 =(box+box1)/2
- box2 = np.int0(box2)
- print(box2)
- cv2.drawContours(draw_img, [box2], 0, (255,0, 0),2)
- cv2.imshow('origin with contours', draw_img)
-
- if cv2.waitKey(0) & 0xFF == ord('q'):
- cv2.destroyWindow('binary')
- cv2.destroyWindow('origin')
- cv2.destroyWindow('origin with contours')
运行结果: