Opencv - Contours 属性及操作 Python API

1. 轮廓Contours

[1] - 定义 - Contours,explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity.

[2] - 用处 - shape analysis,object detection and recognition

  • 采用二值图(binary images), 故,在寻找轮廓前,采用阈值或 canny 边缘检测.
  • cv2.findContours 函数在原图进行修改
  • Opencv中, cv2.findContours 类似于从黑色背景中寻找白色物体,因此,二值图中待寻找的物体应为白色,背景应为黑色

2. 示例 - 寻找二值图的轮廓

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 数组.

3. 示例 - 画出轮廓

img = cv2.drawContours(img, contours, -1, (0,255,0), 3) # 画出Image中的所有轮廓
img = cv2.drawContours(img, contours, 3, (0,255,0), 3) # 画出Image中的某个轮廓,比如第四个

 # 一般也采用下面的方法画出某个轮廓,比如第四个
cnt = contours[4]
img = cv2.drawContours(img, [cnt], 0, (0,255,0), 3)

4. 轮廓特征

主要有轮廓面积、周长、质心、边界框等.

4.1. Moments

Image Moments 用于计算物体质心、物体面积等.

import cv2
import numpy as np
    
img = cv2.imread('star.jpg',0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
    
cnt = contours[0]
M = cv2.moments(cnt) # 以dict形式输出所有moment值
print(M)

根据计算得到的 moments值,可以提取很多信息,比如面积、质心等.

4.2. Contour Area 轮廓面积

area = cv2.contourArea(cnt)

4.3. Contour Perimeter 轮廓周长

perimeter = cv2.arcLength(cnt,True)

4.4. Checking Convexity 轮廓凸性

k = cv2.isContourConvex(cnt)

4.5. Bounding Rectangle 边界框

4.5.1 Straight Bounding Rectangle 直矩形框

x,y,w,h = cv2.boundingRect(cnt) # (x,y)是rectangle的左上角坐标, (w,h)是width和height
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

4.5.2 Rotated Rectangle 旋转矩形框

rect = cv2.minAreaRect(cnt) # 返回 Box2D结构,包括了左上角坐标(x,y),(width, height)和旋转角度
box = cv2.boxPoints(rect) # Rectangle的四个角
box = np.int0(box)
im = cv2.drawContours(im,[box],0,(0,0,255),2)

4.6. Minimum Enclosing Circle 最小包围圆

(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)

4.7. Fitting an Ellipse 椭圆拟合

ellipse = cv2.fitEllipse(cnt)
im = cv2.ellipse(im,ellipse,(0,255,0),2)

4.8. Fitting a Line 直线拟合

rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
img = cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)

4.9. Aspect Ratio 宽高比

物体边界框的宽高比.

x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h

4.10. Extent 轮廓物体面积与边界框面积比

area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area

4.11. Solidity 轮廓物体面积和convex hull 面积比

area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area)/hull_area

4.12. Equivalent Diameter 与轮廓物体面积相等的圆的直径

area = cv2.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)

4.13. Mask and Pixel Points 物体的所有像素点

mask = np.zeros(imgray.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
pixelpoints = np.transpose(np.nonzero(mask))
#pixelpoints = cv2.findNonZero(mask)

4.14. Maximum Value, Minimum Value and their locations

mask image 的最大值,最小值和其位置

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)

4.15. Extreme Points 极值点

物体的最上、下、左、右的点.

leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

Reference

[1] - Contours in OpenCV

Last modification:March 9th, 2021 at 04:53 pm