用机器学习识别图像边缘,并进行旋转,然后再用余弦距离进行比较。
import cv2
import tensorflow as tf
import numpy as np
from scipy.linalg import norm
# 加载模型
model = tf.saved_model.load('model')
def detect_edges(image):
# 预处理图片
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (224, 224))
image = np.expand_dims(image, axis=0)
image = np.expand_dims(image, axis=-1)
# 检测边缘
edges = model.predict(image)
return edges[0]
def compare_images(image1, image2):
# 检测边缘
edges1 = detect_edges(image1)
edges2 = detect_edges(image2)
# 计算边缘线段的斜率
_, _, angle1 = cv2.fitLine(edges1, cv2.DIST_L2, 0, 0.01, 0.01)
_, _, angle2 = cv2.fitLine(edges2, cv2.DIST_L2, 0, 0.01, 0.01)
# 计算夹角
angle1 = np.rad2deg(np.arctan(angle1))
angle2 = np.rad2deg(np.arctan(angle2))
# 旋转图片
rows, cols = image1.shape[:2]
M1 = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle1, 1)
rotated_image1 = cv2.warpAffine(image1, M1, (cols, rows))
rows, cols = image2.shape[:2]
M2 = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle2, 1)
rotated_image2 = cv2.warpAffine(image2, M2, (cols, rows))
# 计算余弦相似度
similarity = np.dot(rotated_image1.flatten(), rotated_image2.flatten()) / (norm(rotated_image1.flatten()) * norm(rotated_image2.flatten()))
print(similarity)
0 条评论