Opencv - Contours 属性及操作 Python API
Contours, 轮廓
- 定义 - Contours,explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity.
用处 - shape analysis,object detection and recognition
- 采用二值图(binary images), 故,在寻找轮廓前,采用阈值或 canny 边缘检测.
- cv2.findContours 函数在原图进行修改
- Opencv中, cv2.findContours 类似于从黑色背景中寻找白色物体,因此,二值图中待寻找的物体应为白色,背景应为黑色
示例 - 寻找二值图的轮廓
import numpy as np
import cv2
im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.findContours函数输入有三个参数:
- thresh: source image
- cv2.RETR_TREE: 轮廓检索模式
- cv2.CHAIN_APPROX_SIMPLE: 轮廓逼近方法
输出三个结果:
- contours: 图像中所有的轮廓,python列表的形式保存. 每个单独的contour是包括物体边界点的(x,y)坐标的Numpy 数组.
示例 - 画出轮廓
img = cv2.drawContours(img, contours, -1, (0,255,0), 3) # 画出Image中的所有轮廓
img = cv2.drawContours(img, contours, 3, (0,255,0), 3) # 画出Image中的某个轮廓,比如第四个<