OpenCV python 轮廓之间的距离(相似性)
处理图片:[cs1.jpg]
处理图片:[cs2.jpg]
处理图片:[hand.jpg]
import cv2
def get_contours(img):
"""获取连通域
:param img: 输入图片
:return: 最大连通域
"""
# 灰度化, 二值化, 连通域分析
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
img_contour, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
return contours[0]
def main():
# 1.导入图片
img_cs1 = cv2.imread("cs1.jpg")
img_cs2 = cv2.imread("cs2.jpg")
img_hand = cv2.imread("hand.jpg")
# 2.获取图片连通域
cnt_cs1 = get_contours(img_cs1)
cnt_cs2 = get_contours(img_cs2)
cnt_hand = get_contours(img_hand)
# 3.创建计算距离对象
hausdorff_sd = cv2.createHausdorffDistanceExtractor()
# 4.计算轮廓之间的距离
d1 = hausdorff_sd.computeDistance(cnt_cs1, cnt_cs1)
print("与自身的距离hausdorff\t d1=", d1)
d2 = hausdorff_sd.computeDistance(cnt_cs1, cnt_cs2)
print("与相似图片的距离hausdorff\t d2=", d2)
d3 = hausdorff_sd.computeDistance(cnt_cs1, cnt_hand)
print("与不同图片的距离hausdorff\t d3=", d3)
# 5.显示图片
cv2.imshow("img_cs1", img_cs1)
cv2.imshow("img_cs2", img_cs2)
cv2.imshow("img_hand", img_hand)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
处理结果: