import os import torch import lpips from PIL import Image from torchvision.transforms import ToTensor # 初始化LPIPS模型 loss_fn = lpips.LPIPS(net='vgg') def calculate_lpips(img_path1, img_path2): # 读取图像 img1 = Image.open(img_path1) img2 = Image.open(img_path2) # 将图像转换为张量 img1_tensor = ToTensor()(img1).unsqueeze(0) img2_tensor = ToTensor()(img2).unsqueeze(0) # 计算LPIPS lpips_value = loss_fn(img1_tensor, img2_tensor) return lpips_value.item() # 文件夹路径 folder_path1 = 'your_folder_path1' folder_path2 = 'your_folder_path2' # 获取文件夹中的所有图像路径 image_paths1 = [os.path.join(folder_path1, img) for img in os.listdir(folder_path1) if img.endswith('.jpg')] image_paths2 = [os.path.join(folder_path2, img) for img in os.listdir(folder_path2) if img.endswith('.jpg')] # 确保两个文件夹中有相同名称的图像 assert set(os.path.basename(p) for p in image_paths1) == set(os.path.basename(p) for p in image_paths2), "The two folders must contain images with the same names." # 计算并打印所有同名图像对的LPIPS lpips_values = [] for img_name in os.listdir(folder_path1): if img_name.endswith('.jpg'): img_path1 = os.path.join(folder_path1, img_name) img_path2 = os.path.join(folder_path2, img_name) lpips_value = calculate_lpips(img_path1, img_path2) lpips_values.append(lpips_value) print(f'LPIPS between {img_path1} and {img_path2}: {lpips_value}') # 计算并打印LPIPS的平均值 average_lpips = sum(lpips_values) / len(lpips_values) print(f'Average LPIPS: {average_lpips}')
标签:path2,path1,img,计算,folder,lpips,os From: https://www.cnblogs.com/yyhappy/p/18072525