# Time    : 2024/8/13 09:13
# Author  : wangchao
# File    : demo4.py
# Description :
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from Config import Config
from PIL import Image, ImageChops

class ImageComparisonTool:
    def __init__(self):
        #从配置文件获取阈值
        self.similarity_threshold = Config.similarity_threshold

    def compare_images(self, actual_image_path, expected_image_path):
        """
        比较两个图片是否相似
        :param actual_image_path: 实际图
        :param expected_image_path: 预期图
        :param compare_result_img_path: 比对结果图
        :param highlight_differences:
        :return:
        """
        # 读取图片
        img1 = Image.open(actual_image_path)
        img2 = Image.open(expected_image_path)

        # 确保两个图片具有相同的模式和大小
        if img1.mode != img2.mode or img1.size != img2.size:
            return False

        # 计算差异
        diff = ImageChops.difference(img1, img2)
        # 将差异图片转换为灰度，并获取差异像素的总数
        diff_gray = diff.convert('L')
        squared_pixels = [i ** 2 for i in list(diff_gray.getdata())]
        rmse = (sum(squared_pixels) / len(squared_pixels)) ** 0.5

        # 根据均方根误差（RMSE）和阈值判断图片是否相似
        return rmse < self.similarity_threshold

# 在测试用例中调用
if __name__ == '__main__':
    comparator = ImageComparisonTool()
    result = comparator.compare_images('Rectangle_actual.png', 'Rectangle_expected2.png')
    if result:
        print("测试通过：两张图片相似")
    else:
        print("测试失败：两张图片不相似")