opencv物体形状相似度对比 布满荆棘的人生 2022-10-15 13:52 118阅读 0赞 import cv2 from math import * def rota(img, degree): height, width = img.shape[:2] # 旋转后的尺寸 heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree)))) widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree)))) matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1) matRotation[0, 2] += (widthNew - width) / 2 matRotation[1, 2] += (heightNew - height) / 2 imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255)) return imgRotation def getsim(img1,img2): ret, thresh1 = cv2.threshold(img1, 254, 255, 0) ret, thresh2 = cv2.threshold(img2, 254, 255, 0) h1,w1 = thresh1.shape h2,w2 = thresh2.shape r1 = h1 / w1 r2 = h2 / w2 if r1 < 1 and r2 > 1: thresh2 = rota(thresh2,90) thresh1 = ~thresh1 thresh2 = ~thresh2 h1, w1 = thresh1.shape h2, w2 = thresh2.shape if w1< w2: thresh2 = cv2.resize(thresh2,(w1,h1)) else: thresh1 = cv2.resize(thresh1,(w2,h2)) cv2.imshow('1',thresh1) cv2.imshow('2',thresh2) cv2.waitKey(0) contours, hierarchy = cv2.findContours(thresh1, 2, 1) cnt1 = contours[0] contours, hierarchy = cv2.findContours(thresh2, 2, 1) cnt2 = contours[0] return cv2.matchShapes(cnt1, cnt2, 1, 0.0) def comparesim(path1,path2): img1 = cv2.imread(path1, 0) img1 = cv2.GaussianBlur(img1,(25,25),15) img2 = cv2.imread(path2, 0) img2 = cv2.GaussianBlur(img2,(25,25),15) return getsim(img1,img2) sim = comparesim('/home/lhq/mb/0.jpg','/home/lhq/mb/7.jpg') print(sim)
还没有评论,来说两句吧...