当前位置: 代码迷 >> 综合 >> 评价图像相似度的指标 : FID(Fréchet Inception Distance)
  详细解决方案

评价图像相似度的指标 : FID(Fréchet Inception Distance)

热度:86   发布时间:2024-02-11 03:38:24.0

FID(Fréchet Inception Distance)
是用来计算真实图像与生成图像的特征向量间距离的一种度量。如果FID值越小,则相似程度越高。最好情况即是FID=0,两个图像相同。

实际计算:
参考链接:https://machinelearningmastery.com/how-to-implement-the-frechet-inception-distance-fid-from-scratch/

在这里插入图片描述

在这里插入图片描述

# example of calculating the frechet inception distance in Keras
import numpy
import os
import cv2
import argparse
import torch
import numpy as np
from scipy.linalg import sqrtm
from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_v3 import preprocess_input# os.environ["TF_CPP_MIN_LOG_LEVEL"]='2' # 只显示 warning 和 Error
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'   # 只显示 Error# calculate frechet inception distance
def calculate_fid(model, images1, images2):# calculate activationsact1 = model.predict(images1)act2 = model.predict(images2)# calculate mean and covariance statisticsmu1, sigma1 = act1.mean(axis=0), np.cov(act1, rowvar=False)mu2, sigma2 = act2.mean(axis=0), np.cov(act2, rowvar=False)# calculate sum squared difference between meansssdiff = numpy.sum((mu1 - mu2)**2.0)# calculate sqrt of product between covcovmean = sqrtm(np.dot(sigma1, sigma2))# check and correct imaginary numbers from sqrtif np.iscomplexobj(covmean):covmean = covmean.real# calculate scorefid = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean)return fiddef data_list(dirPath):generated_Dataset = []real_Dataset = []for root, dirs, files in os.walk(dirPath):for filename in sorted(files):  # sorted已排序的列表副本# 判断该文件是否是目标文件if "generated" in filename:generatedPath = root + '/' + filenamegeneratedImg = cv2.imread(generatedPath).astype('float32')generated_Dataset.append(generatedImg)# 对比图片路径realPath = root + '/' + filename.replace('generated', 'real')realImg = cv2.imread(realPath).astype('float32')real_Dataset.append(realImg)return generated_Dataset, real_Datasetif __name__ == '__main__':### 参数设定parser = argparse.ArgumentParser()# parser.add_argument('--dataset_dir', type=str, default='./results/hrnet/', help='results')parser.add_argument('--dataset_dir', type=str, default='./results/ssngan/', help='results')parser.add_argument('--name', type=str, default='sketch', help='name of dataset')opt = parser.parse_args()# 数据集dirPath = os.path.join(opt.dataset_dir, opt.name)generatedImg, realImg = data_list(dirPath)dataset_size = len(generatedImg)print("数据集:", dataset_size)images1 = torch.Tensor(generatedImg)images2 = torch.Tensor(realImg)print('shape: ', images1.shape, images2.shape)# 将全部数据集导入# prepare the inception v3 modelmodel = InceptionV3(include_top=False, pooling='avg')# pre-process images(归一化)images1 = preprocess_input(images1)images2 = preprocess_input(images2)# fid between images1 and images2fid = calculate_fid(model, images1, images2)print('FID : %.3f' % fid)print('FID_average : %.3f' % (fid / dataset_size))

在这里插入图片描述

  相关解决方案