opencv 凸缺陷

import cv2
import numpy as np
import matplotlib.pyplot as plt
 
A = cv2.imread('E:/python/TU.png')
imgray=cv2.cvtColor(A,cv2.COLOR_BGR2GRAY)
B=imgray.copy()
ret,thresh=cv2.threshold(imgray,150,255,0)
#th2 = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
image,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt=contours[0]
#查找凸包,此处一定要False
hull=cv2.convexHull(cnt,returnPoints=False)
defects=cv2.convexityDefects(cnt,hull)

rows, cols = B.shape
img= np.zeros((rows,cols,3),np.uint8)
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])
    cv2.line(A,start,end,(0,255,0),2)
    cv2.circle(A,far,5,(0,0,255),-1)
    
cv2.imshow('img',A)
k = cv2.waitKey(0) 
if k == ord('s'):        
    cv2.destroyAllWindows()

在这里插入图片描述在这里插入图片描述

hull=cv2.convexHull(cnt,returnPoints=False)
defects=cv2.convexityDefects(cnt,hull)

凸缺陷返回一个数组,每一行包含值是起点,终点,最远的点,到最远点的近似距离,返回的前三个点都是轮廓索引

形状匹配:根据HU矩

import cv2
import numpy as np
import matplotlib.pyplot as plt
 
A = cv2.imread('E:/python/TU.png',0)
B = cv2.imread('E:/python/TUw.png',0)
C = cv2.imread('E:/python/TUwb.png',0)


ret,thresh=cv2.threshold(A,150,255,0)
ret1,thresh1=cv2.threshold(B,150,255,0)
ret2,thresh2=cv2.threshold(C,150,255,0)
#th2 = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
image,contours,hierarchy=cv2.findContours(thresh,2,1)
cnt=contours[0]

image,contours,hierarchy=cv2.findContours(thresh1,2,1)
cnt1=contours[0]

image,contours,hierarchy=cv2.findContours(thresh2,2,1)
cnt2=contours[0]
#匹配
ret3=cv2.matchShapes(cnt,cnt,1,0.0)
ret4=cv2.matchShapes(cnt,cnt1,1,0.0)
ret5=cv2.matchShapes(cnt,cnt2,1,0.0)

print('A与自己匹配',ret3)
print('A与B匹配',ret4)
print('A与C匹配',ret5)

    
plt.subplot(131),plt.imshow(A,'gray')
plt.subplot(132),plt.imshow(B,'gray')
plt.subplot(133),plt.imshow(C,'gray')

在这里插入图片描述
A与自己匹配 0.0
A与B匹配 0.05032881381760934
A与C匹配 0.3319255255164176

猜你喜欢

转载自blog.csdn.net/qq_41244435/article/details/86656725