import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import osdef is_similar(image1, image2, threshold=0.95):'''对图像的颜色信息敏感,能快速计算。对图像的旋转、缩放等几何变换不敏感。缺点:对图像的结构、纹理等信息不敏感。不能很好地处理图像的局部变化或噪声。'''# 将图像转换为灰度图像image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)image2_gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)# 计算直方图hist1 = cv2.calcHist([image1_gray], [0], None, [256], [0, 256])hist2 = cv2.calcHist([image2_gray], [0], None, [256], [0, 256])# 归一化直方图cv2.normalize(hist1, hist1, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)cv2.normalize(hist2, hist2, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)# 计算相似度similarity = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)print("similarity",similarity)# return similarity > threshold
def calculate_ssim(image1, image2):'''结构相似性指数(Structural Similarity Index, SSIM):优点:综合考虑了亮度、对比度和结构信息,能够更好地反映人类视觉感知。对局部变化和噪声有较好的鲁棒性。缺点:计算复杂度较高,速度较慢。对大范围的几何变换不敏感。适用场景:适用于需要精确比较图像结构信息的场景,如图像压缩质量评估、图像增强效果评估等医学图像分析。'''# Convert images to grayscalegray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)# Calculate SSIMssim_score, _ = ssim(gray1, gray2, full=True)# print("calculate_ssim",ssim_score)return ssim_score
def calculate_mae(image1, image2):'''均值绝对误差(Mean Absolute Error, MAE):优点:简单直接,计算像素值的绝对差异。对图像的整体亮度变化敏感。缺点:对图像的几何变换(如平移、旋转、缩放)敏感。不能很好地处理局部变化和噪声。适用场景:适用于对整体亮度或颜色变化敏感的场景,如医学图像分析、监控图像等。'''# Convert images to grayscalegray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)# Calculate Mean Absolute Error (MAE)mae = np.mean(np.abs(gray1 - gray2))# print("mae",mae) #0到255 越小越来约相似return mae