RGB图转化为灰度图
256度灰(图片内颜色种类不超过256中,不然会失真)
RGB → L
import os
import numpy as np
from skimage.metrics import structural_similarity as ssim
from PIL import Image
def calculate_ssim(original_path, modified_path):
# 打开原始图片和修改后的图片
original = Image.open(original_path).convert("L")
modified = Image.open(modified_path).convert("L")
original.save("hahiahi.png")
# 将图像转为 NumPy 数组
original_array = np.array(original)
modified_array = np.array(modified)
# 计算 SSIM
similarity_index, _ = ssim(original_array, modified_array, full=True)
return similarity_index
def compare_images_in_directories(original_directory, modified_directory):
# 获取原始目录和修改目录下的所有文件名
original_files = os.listdir(original_directory)
modified_files = os.listdir(modified_directory)
similarities = [] # 用于存储相似度的数组
i = 0
# 遍历两个目录下的同名文件进行对比
for filename in set(original_files).intersection(modified_files):
i += 1
original_path = os.path.join(original_directory, filename)
modified_path = os.path.join(modified_directory, filename)
# 调用计算相似度函数
similarity_index = calculate_ssim(original_path, modified_path)
similarities.append((filename, similarity_index)) # 存储文件名和相似度的元组
# print(f"Similarity index for {filename}: {similarity_index}")
return similarities, i
# 输入原始目录、修改目录和输出目录
original_directory = r"D:/AutoTest/PythonProject/img/testcase_img/PecExplorer/"
modified_directory = r"D:/AutoTest/PythonProject/img/standard_img/PecExplorer/"
# 调用函数进行处理
similarities, i = compare_images_in_directories(original_directory, modified_directory)
for i,j in similarities:
print(j)