我有 2 个文件夹,一个包含数据集中未经预处理的图像,另一个包含未经预处理的生成图像,我想计算它们之间的 FID,但我无法弄清楚我通过 torchmetrics 找到了这段代码:
>>> import torch
>>> _ = torch.manual_seed(123)
>>> from torchmetrics.image.fid import FrechetInceptionDistance
>>> fid = FrechetInceptionDistance(feature=64)
>>> # generate two slightly overlapping image intensity distributions
>>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
>>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
>>> fid.update(imgs_dist1, real=True)
>>> fid.update(imgs_dist2, real=False)
>>> fid.compute()
tensor(12.7202)
这是我到目前为止的代码,有什么想法吗?
import torch
import torchmetrics
from torchmetrics.image.fid import _TORCH_FIDELITY_AVAILABLE
from torchmetrics.image.fid import FrechetInceptionDistance
import torchvision.transforms as transforms
import os
import pathlib
# Define transforms to resize and normalize images
transform = transforms.Compose([
transforms.Resize((299, 299)),
transforms.ToTensor(), # Convert images to PyTorch tensors
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # Normalize images
])
def load_images_from_folder(folder):
image_paths = pathlib.Path(folder).glob("*.*")
images = [transform(Image.open(img_path)) for img_path in image_paths]
images = torch.stack(images)
return images
def calculate_fid_for_folders(folder1, folder2):
# Load images from folders and apply transformations
real_images = load_images_from_folder(folder1)
fake_images = load_images_from_folder(folder2)
# Initialize FID metric
fid = FrechetInceptionDistance(normalize=True)
# Update FID metric with real and fake images
fid.update(real_images, real=True)
fid.update(fake_images, real=False)
# Compute FID score
fid_score = fid.compute()
print(f"FID: {float(fid.compute())}")
# Example usage:
folder1 = "/content/output_images"
folder2 = "/content/genearated_images"
fid_score = calculate_fid_for_folders(folder1, folder2)
您是否收到任何错误消息,或者您到底遇到了什么问题?