1、像素比较:
这种方法通常用于比较尺寸和颜色完全相同的图像。可以通过比较两个图像的每一个像素来计算相似度。
例如:
from PIL import Image
import numpy as np
img1 = Image.open("image1.jpg")
img2 = Image.open("image2.jpg")
arr1 = np.array(img1)
arr2 = np.array(img2)
similarity = np.mean(arr1 == arr2)
2、结构相似性指数 (SSIM):
SSIM是一种衡量两个图像的视觉相似度的方法。它考虑了图像的亮度、对比度和结构信息。
例如:
from skimage import measure
from PIL import Image
import numpy as np
img1 = Image.open("image1.jpg").convert('L') # convert image to grayscale
img2 = Image.open("image2.jpg").convert('L')
arr1 = np.array(img1)
arr2 = np.array(img2)
similarity = measure.compare_ssim(arr1, arr2)
3、特征匹配:
这种方法通常用于比较视觉上类似但可能在颜色、尺寸或方向上有所不同的图像。可以使用一些算法(如SIFT, SURF, ORB等)来提取图像的特征点,然后比较这些特征点的匹配程度。
例如使用OpenCV的ORB算法:
import cv2
img1 = cv2.imread('image1.jpg',0) # queryImage
img2 = cv2.imread('image2.jpg',0) # trainImage
# Initiate ORB detector
orb = cv2.ORB_create()
# find the keypoints and descriptors with ORB
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Match descriptors.
matches = bf.match(des1,des2)
# Sort them in the order of their distance.
matches = sorted(matches, key = lambda x:x.distance)
# The similarity can be measured by the number of matches or the quality of matches
similarity = len(matches)
4、深度学习:
如果你有大量的训练数据,你也可以使用深度学习的方法(如卷积神经网络)来学习图像的特征表示,并用这些特征来比较图像的相似性。
例如,可以使用预训练的VGG网络提取特征:
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.preprocessing import image
import numpy as np
model = VGG16(weights='imagenet', include_top=False)
img1 = image.load_img('image1.jpg', target_size=(224, 224))
img2 = image.load_img('image2.jpg', target_size=(224, 224))
img1 = image.img_to_array(img1)
img2 = image.img_to_array(img2)
img1 = np.expand_dims(img1, axis=0)
img2 = np.expand_dims(img2, axis=0)
img1 = preprocess_input(img1)
img2 = preprocess_input(img2)
features1 = model.predict(img1)
features2 = model.predict(img2)
similarity = np.dot(features1, features2) / (np.linalg.norm(features1) * np.linalg.norm(features2))
网友回复