1. 程式人生 > >opencv 輪廓特徵

opencv 輪廓特徵

1.距 cv.moments()

import numpy as np
import cv2 as cv
img = cv.imread('star.jpg',0)
ret,thresh = cv.threshold(img,127,255,0)
im2,contours,hierarchy = cv.findContours(thresh, 1, 2)
cnt = contours[0]
M = cv.moments(cnt)
print( M )

2.面積

area = cv.contourArea(cnt)

3.周長

perimeter = cv.arcLength(cnt,True)

4.輪廓近似 基於道格拉斯-peucker演算法實現 假設要找一個正方形,但是又是不規則的正方形,則可以使用輪廓近似

epsilon = 0.1*cv.arcLength(cnt,True)
approx = cv.approxPolyDP(cnt,epsilon,True)

5.凸

hull = cv.convexHull(points[, hull[, clockwise[, returnPoints]]

6.檢查凸面

k = cv.isContourConvex(cnt)

7.矩形 直矩形

x,y,w,h = cv.boundingRect(cnt)
cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

旋轉矩形

rect = cv.minAreaRect(cnt)
box = cv.boxPoints(rect)
box = np.int0(box)
cv.drawContours(img,[box],0,(0,0,255),2)



8.圓

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

9.橢圓

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