```python
"""
形状匹配
"""
def getpatch(maskimg):
locs = np.where(maskimg == 255)
x0 = np.min(locs[1])
x1 = np.max(locs[1])
y0 = np.min(locs[0])
y1 = np.max(locs[0])
return maskimg[y0:y1,x0:x1]
from pyimagesearch.detect_shapes import getshape
def getsim(img1,img2):
img1 = getpatch(img1)
img2 = getpatch(img2)
h1,w1 = img1.shape
h2,w2 = img2.shape
r1 = h1 / w1
r2 = h2 / w2
if (r1 > 1 and r2 < 1) or (r1 < 1 and r2 > 1):
img2 = rota(img2,90)
w2,h2 = h2,w2
# cv2.imshow('1',img1)
# cv2.waitKey(0)
# cv2.imshow('2',img2)
# cv2.waitKey(0)
# exit()
_, thresh = cv2.threshold(img1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours1, hierarchy = cv2.findContours(thresh, 3, 2)
cnt1 = np.vstack(contours1)
x = cnt1[:,:,0] / w1
y = cnt1[:,:,1] / h1
x = np.squeeze(x)
y = np.squeeze(y)
cnt1 = np.stack([x,y],axis=1)
# im1 = np.zeros(shape=img1.shape)
# cv2.polylines(im1,contours1, True, (255, 255, 255))
# cv2.imshow('',im1)
# cv2.waitKey(0)
_, thresh = cv2.threshold(img2, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours2, hierarchy = cv2.findContours(thresh, 3, 2)
cnt2 = np.vstack(contours2)
x = cnt2[:, :, 0] / w2
y = cnt2[:, :, 1] / h2
x = np.squeeze(x)
y = np.squeeze(y)
cnt2 = np.stack([x, y], axis=1)
# im2 = np.zeros(shape=img2.shape)
# cv2.polylines(im2, contours2, True, (255, 255, 255))
# cv2.imshow('', im2)
# cv2.waitKey(0)
return cv2.matchShapes(cnt1,cnt2,3,0)
sanjiaodown = cv2.imread('/home/lhq/tests/standard/standard/triangle3.jpg',0)
sanjiaoup = cv2.imread('/home/lhq/tests/standard/standard/triangle4.jpg',0)
fangxing = cv2.imread('/home/lhq/tests/standard/standard/rectangle1.jpg',0)
circle = cv2.imread('/home/lhq/tests/standard/standard/circle1.jpg',0)
# # sanjiao = rota(cv2.resize(fangxing,(400,400)),45)
testimg = cv2.imread('/home/lhq/tests/test_0.jpg',0)
print(getsim(sanjiaodown,testimg),getsim(sanjiaoup,testimg),getsim(fangxing,testimg),getsim(circle,testimg))