1import logging
2import os.path
3
4import cv2
5
6
7def crop_picture(picture, x1=0, y1=72, x2=720, y2=1208):
8    img = cv2.imread(picture)
9    img = img[y1:y2, x1:x2]
10    cv2.imwrite(picture, img)
11
12
13def compare_image_similarity(image1, image2):
14    logging.info('{} is exist? [{}]'.format(image1, os.path.exists(image1)))
15    logging.info('{} is exist? [{}]'.format(image2, os.path.exists(image2)))
16    if not os.path.exists(image1) or not os.path.exists(image2):
17        logging.info('file not found, set similarity as 0%')
18        return 0
19    image1 = cv2.imread(image1, 0)
20    image2 = cv2.imread(image2, 0)
21
22    # 初始化特征点检测器和描述符
23    orb = cv2.ORB_create(edgeThreshold=5, patchSize=30)
24    keypoints1, descriptors1 = orb.detectAndCompute(image1, None)
25    keypoints2, descriptors2 = orb.detectAndCompute(image2, None)
26
27    # 初始化匹配器
28    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
29
30    # 匹配特征点
31    matches = bf.match(descriptors1, descriptors2)
32    if not matches:
33        logging.info('no fixture point found, set similarity as 0%')
34        return 0
35    if not keypoints1:
36        if not keypoints2:
37            logging.info('similarity is 100%')
38            return 1
39        logging.info('similarity is 0%')
40        return 0
41    # 计算相似度
42    similarity = len(matches) / len(keypoints1)
43    logging.info('similarity is {}%'.format(similarity * 100))
44    return similarity
45