opencv-python图像处理3

一个很有趣的个人博客,不信你来撩 fangzengye.com



宽高比

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

范围

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

体积

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

直径

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

方向

(x,y),(MA,ma),angle = cv.fitEllipse(cnt)

像素点

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

最大化最小化值

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

平均颜色,平均强度

mean_val = cv.mean(im,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])

在这里插入图片描述
源地址

https://docs.opencv.org/3.4/d1/d32/tutorial_py_contour_properties.htm

凸缺陷

hull = cv.convexHull(cnt,returnPoints = False)
defects = cv.convexityDefects(cnt,hull)
import cv2 as cv
import numpy as np
img = cv.imread('star.jpg')
img_gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(img_gray, 127, 255,0)
im2,contours,hierarchy = cv.findContours(thresh,2,1)
cnt = contours[0]
hull = cv.convexHull(cnt,returnPoints = False)
defects = cv.convexityDefects(cnt,hull)
for i in range(defects.shape[0]):
    s,e,f,d = defects[i,0]
    start = tuple(cnt[s][0])
    end = tuple(cnt[e][0])
    far = tuple(cnt[f][0])
    cv.line(img,start,end,[0,255,0],2)
    cv.circle(img,far,5,[0,0,255],-1)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()

在这里插入图片描述
点多边测试

dist = cv.pointPolygonTest(cnt,(50,50),True)

匹配形状

import cv2 as cv
import numpy as np
img1 = cv.imread('star.jpg',0)
img2 = cv.imread('star2.jpg',0)
ret, thresh = cv.threshold(img1, 127, 255,0)
ret, thresh2 = cv.threshold(img2, 127, 255,0)
im2,contours,hierarchy = cv.findContours(thresh,2,1)
cnt1 = contours[0]
im2,contours,hierarchy = cv.findContours(thresh2,2,1)
cnt2 = contours[0]
ret = cv.matchShapes(cnt1,cnt2,1,0.0)
print( ret )

在这里插入图片描述
源地址

https://docs.opencv.org/3.4/d5/d45/tutorial_py_contours_more_functions.html

posted @ 2020-03-01 19:55  开源的Boy  阅读(101)  评论(0)    收藏  举报