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中的某个轮廓,比如第四个
# 一般也采用下面的方法画出某个轮廓,比如第四个
cnt = contours[4]
img = cv2.drawContours(img, [cnt], 0, (0,255,0), 3)
主要有轮廓面积、周长、质心、边界框等.
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值,可以提取很多信息,比如面积、质心等.
area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt,True)
k = cv2.isContourConvex(cnt)
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)
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)
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)
ellipse = cv2.fitEllipse(cnt)
im = cv2.ellipse(im,ellipse,(0,255,0),2)
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)
物体边界框的宽高比.
x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h
area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
rect_area = w*h
extent = float(area)/rect_area
area = cv2.contourArea(cnt)
hull = cv2.convexHull(cnt)
hull_area = cv2.contourArea(hull)
solidity = float(area)/hull_area
area = cv2.contourArea(cnt)
equi_diameter = np.sqrt(4*area/np.pi)
mask = np.zeros(imgray.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
pixelpoints = np.transpose(np.nonzero(mask))
#pixelpoints = cv2.findNonZero(mask)
mask image 的最大值,最小值和其位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(imgray,mask = mask)
物体的最上、下、左、右的点.
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])