Python-OpenCV3-Hausdorff distance

A few days ago,i saw a blog that how to use the hausdorff diseance to achieve the model matching.It was very interesting.

Today I don’t want to explain the principle of Hausdorff distance much more,and you can find it in Baidu Encyclopedia . Here i just talk about how to use it in Python.

Library

First you should install some dependency libraries for you computer.

pip install opencv-python

pip install opencv-contrib-python

Python code

Firstly,import three pictures with cv2.imread() fuction.Secondly use the cv2.findContours to find their Contours.Finally,calculate their Hausdorff distance.

import cv2

def get_contours(img):

    # 灰度化, 二值化, 连通域分析
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, img_bin = cv2.threshold(img_gray, 200, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    return contours[0]
def main():
    # 1.导入图片
    img1 = cv2.imread("./4.jpg")
    img2 = cv2.imread("./5.jpg")
    img3 = cv2.imread("./6.jpg")
    # 2.获取图片连通域
    cnt1 = get_contours(img1)
    cnt2 = get_contours(img2)
    cnt3 = get_contours(img3)
    # 3.创建计算距离对象
    hausdorff_sd = cv2.createHausdorffDistanceExtractor()
    # 4.计算轮廓之间的距离
    d1 = hausdorff_sd.computeDistance(cnt1, cnt1)
    print("与自身的距离hausdorff\t d1=", d1)
    d2 = hausdorff_sd.computeDistance(cnt1, cnt2)
    print("与5图片的距离hausdorff\t d2=", d2)
    d3 = hausdorff_sd.computeDistance(cnt1, cnt3)
    print("与6图片的距离hausdorff\t d3=", d3)
if __name__ == '__main__':
    main()

Display

Python-OpenCV3-Hausdorff distance_第1张图片Through this picture,we can find that the smaller the Hausdorff distance ,the higher the similarity between the two images.

快乐分享错了人就成了显摆,难过倾诉错了人就成了矫情。
Question:how to translate these words in English?

你可能感兴趣的:(python学习)