# -*- coding: utf-8 -*-
import os
import math
import numpy as np
# 引入图像处理包
from PIL import Image
# 比较两张图片的相似度
def get_similarity(img1, img2):
# 读取图片
image1 = Image.open(img1)
image2 = Image.open(img2) # 生成缩略图,减少计算量,加快速度
image1 = image1.resize((8, 8), Image.ANTIALIAS)
image2 = image2.resize((8, 8), Image.ANTIALIAS) # 转换为灰度图
image1 = image1.convert("L")
image2 = image2.convert("L") # 两张图片大小都是8x8
pixels1 = np.array(image1.getdata())
pixels2 = np.array(image2.getdata()) # 求差值
diff = pixels1 - pixels2 # 求差值的平方
sqdiff = diff ** 2 # 求和
sumdiff = sum(sqdiff) # 开方
score = sumdiff ** 0.5 # 返回相似度
return score
# 调用
img1 = '1.jpg'
img2 = '2.jpg'
print(get_similarity(img1, img2)) # 输出相似度
用python写一个脚本,比较两张图片的相似度
最新推荐文章于 2024-01-22 17:12:47 发布