1、简介
把图片表示成一个向量,通过计算向量之间的余弦距离来表征两张图片的相似度。
2、代码from PIL import Image from numpy import average, dot, linalg # 对图片进行统一化处理 def get_thum(image, size=(1920, 1080), greyscale=False): # 利用image对图像大小重新设置, Image.ANTIALIAS为高质量的 image = image.resize(size, Image.Resampling.LANCZOS) if greyscale: # 将图片转换为L模式,其为灰度图,其每个像素用8个bit表示 image = image.convert('L') return image # 计算图片的余弦距离 def image_similarity_vectors_via_numpy(image_cp1, image_cp2): image_cp1 = get_thum(image_cp1) image_cp2 = get_thum(image_cp2) images = [image_cp1, image_cp2] vectors = [] norms = [] for image in images: vector = [] for pixel_tuple in image.getdata(): vector.append(average(pixel_tuple)) vectors.append(vector) # linalg = linear(线性)+algebra(代数),norm则表示范数 # 求图片的范数 norms.append(linalg.norm(vector, 2)) a, b = vectors a_norm, b_norm = norms # dot返回的是点积,对二维数组(矩阵)进行计算 res = dot(a / a_norm, b / b_norm) return res image_cp1 = Image.open('WD1.png') image_cp2 = Image.open('WD2.png') cosine_similarity = image_similarity_vectors_via_numpy(image_cp1, image_cp2) print('图片余弦相似度:', cosine_similarity)
标签:Python,image,vectors,余弦,两图,cp1,cp2,Image,norm From: https://www.cnblogs.com/TSmagic/p/17874966.html