计算psnr ssim niqe fid mae lpips等指标的代码

2024-04-10 21:28

本文主要是介绍计算psnr ssim niqe fid mae lpips等指标的代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 以下代码仅供参考,路径处理最好自己改一下
# Author: Wu
# Created: 2023/8/15
# module containing metrics functions
# using package in https://github.com/chaofengc/IQA-PyTorch
import torch
from PIL import Image
import numpy as np
from piqa import PSNR, SSIM
import pyiqa
import argparse
import os
from collections import defaultdict
first = True
first2 = True
lpips_metric = None
niqe_metric = None
config = None
def read_img(img_path, ref_image=None):img = Image.open(img_path).convert('RGB')# resize gt to size of inputif ref_image is not None: w,h = img.size_,_, h_ref, w_ref = ref_image.shapeif w_ref!=w or h_ref!=h:img = img.resize((w_ref, h_ref), Image.ANTIALIAS)img = (np.asarray(img)/255.0)img = torch.from_numpy(img).float()img = img.permute(2,0,1)img = img.to(torch.device(f'cuda:{config.device}')).unsqueeze(0)return img.contiguous()def get_NIQE(enhanced_image, gt_path=None):niqe_metric = pyiqa.create_metric('niqe', device=enhanced_image.device).to(torch.device(f'cuda:{config.device}'))return  niqe_metric(enhanced_image)
def get_FID(enhanced_image_path, gt_path):fid_metric = pyiqa.create_metric('fid').to(torch.device(f'cuda:{config.device}'))score = fid_metric(enhanced_image_path, gt_path)return score
def get_psnr(enhanced_image, gt_path):gtimg = Image.open(gt_path).convert('RGB')gtimg = gtimg.resize((1200, 900), Image.ANTIALIAS)gtimg = (np.asarray(gtimg)/255.0)gtimg = torch.from_numpy(gtimg).float()gtimg = gtimg.permute(2,0,1)gtimg = gtimg.to(torch.device(f'cuda:{config.device}')).unsqueeze(0).contiguous()criterion = PSNR().to(torch.device(f'cuda:{config.device}'))return criterion(enhanced_image, gtimg).cpu().item()
def get_ssim(enhanced_image, gt_path):gtimg = Image.open(gt_path).convert('RGB')gtimg = gtimg.resize((1200, 900), Image.ANTIALIAS)gtimg = (np.asarray(gtimg)/255.0)gtimg = torch.from_numpy(gtimg).float()gtimg = gtimg.permute(2,0,1)gtimg = gtimg.to(torch.device(f'cuda:{config.device}')).unsqueeze(0).contiguous()criterion = SSIM().to(torch.device(f'cuda:{config.device}'))return criterion(enhanced_image, gtimg).cpu().item()
def get_lpips(enhanced_image, gt_path):gtimg = Image.open(gt_path).convert('RGB')gtimg = gtimg.resize((1200, 900), Image.ANTIALIAS)gtimg = (np.asarray(gtimg)/255.0)gtimg = torch.from_numpy(gtimg).float()gtimg = gtimg.permute(2,0,1)gtimg = gtimg.to(torch.device(f'cuda:{config.device}')).unsqueeze(0).contiguous()iqa_metric = pyiqa.create_metric('lpips', device=enhanced_image.device)return iqa_metric(enhanced_image, gtimg).cpu().item()
def get_MAE(enhanced_image, gt_path):gtimg = Image.open(gt_path).convert('RGB')gtimg = gtimg.resize((1200, 900), Image.ANTIALIAS)gtimg = (np.asarray(gtimg)/255.0)gtimg = torch.from_numpy(gtimg).float()gtimg = gtimg.permute(2,0,1)gtimg = gtimg.to(torch.device(f'cuda:{config.device}')).unsqueeze(0).contiguous()return torch.mean(torch.abs(enhanced_image-gtimg)).cpu().item()def get_metric(enhanced_image, gt_path, metrics):if gt_path is not None:gtimg = read_img(gt_path, enhanced_image)else:gtimg = Noneres = dict()if 'psnr' in metrics:psnr = PSNR().to(torch.device(f'cuda:{config.device}'))res['psnr'] = psnr(enhanced_image, gtimg).cpu().item()if 'ssim' in metrics:ssim = SSIM().to(torch.device(f'cuda:{config.device}'))res['ssim'] = ssim(enhanced_image, gtimg).cpu().item()if 'mae' in metrics:res['mae'] = torch.mean(torch.abs(enhanced_image-gtimg)).cpu().item()if 'niqe' in metrics:global first2global niqe_metricif first2:first2 = Falseniqe_metric = pyiqa.create_metric('niqe', device=enhanced_image.device)res['niqe'] = niqe_metric(enhanced_image).cpu().item()if 'lpips' in metrics:global firstglobal lpips_metricif first:first = Falselpips_metric = pyiqa.create_metric('lpips', device=enhanced_image.device)res['lpips'] = lpips_metric(enhanced_image, gtimg).cpu().item()return resdef get_metrics_dataset(pred_path, gt_path, dataset='lol'):if dataset == 'fivek':input_file_path_list = []gt_file_path_list = []file_list = os.listdir(os.path.join(gt_path))for filename in file_list:input_file_path_list.append(os.path.join(pred_path, filename))gt_file_path_list.append(os.path.join(gt_path,  filename))elif dataset == 'lol':input_file_path_list = []gt_file_path_list = []file_list = os.listdir(os.path.join(gt_path))for filename in file_list:input_file_path_list.append(os.path.join(pred_path, filename.replace('normal', 'low')))gt_file_path_list.append(os.path.join(gt_path,  filename))elif dataset == 'EE':input_file_path_list = []gt_file_path_list = []file_list = os.listdir(os.path.join(pred_path))for filename in file_list:input_file_path_list.append(os.path.join(pred_path, filename))suffix = filename.split('_')[-1]new_filename = filename[:-len(suffix)-1]+'.jpg'gt_file_path_list.append(os.path.join(gt_path,  new_filename))elif dataset == 'upair':input_file_path_list = []gt_file_path_list = []file_list = os.listdir(os.path.join(pred_path))for filename in file_list:input_file_path_list.append(os.path.join(pred_path, filename))gt_file_path_list.append(None)else:print(f'{dataset} not supported')exit()return input_file_path_list, gt_file_path_listif __name__ == '__main__':parser = argparse.ArgumentParser()parser.add_argument('--gt', type=str, default="/data1/wjh/LOL_v2/Real_captured/eval/gt")parser.add_argument('--pred', type=str, default="/data1/wjh/ECNet/baseline/gt_referenced/output")parser.add_argument('--dataset', type=str, default="lol")parser.add_argument('--device', type=str, default="0")parser.add_argument('--psnr', action='store_true')parser.add_argument('--ssim', action='store_true')parser.add_argument('--fid', action='store_true')parser.add_argument('--niqe', action='store_true')parser.add_argument('--lpips', action='store_true')parser.add_argument('--mae', action='store_true')config = parser.parse_args()print(config)gt_path = config.gtpred_path = config.pred# os.environ['CUDA_VISIBLE_DEVICES']=config.deviceassert os.path.exists(gt_path), 'gt_path not exits'assert os.path.exists(pred_path), 'pred_path not exits'metrics_names = []for metrics_name in ['psnr', 'ssim', 'niqe', 'lpips', 'mae']:if vars(config)[metrics_name]:metrics_names.append(metrics_name)# compute metricsmetrics_dict = defaultdict(list)metrics = dict()with torch.no_grad():# load img pathinput_file_paths,  gt_file_paths = get_metrics_dataset(pred_path, gt_path, config.dataset)# read img and compute metricsfor input_file_path, gt_file_path in zip(input_file_paths, gt_file_paths):# print(input_file_path)pred = read_img(input_file_path)metrics = get_metric(pred, gt_file_path, metrics_names)for metrics_name in metrics:metrics_dict[metrics_name].append(metrics[metrics_name])for metrics_name in metrics:print(f'{metrics_name}: {np.mean(metrics_dict[metrics_name])}')if config.fid:fid_score = get_FID(pred_path, gt_path)print(F'fid: {fid_score}')

这篇关于计算psnr ssim niqe fid mae lpips等指标的代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/892186

相关文章

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

poj 1113 凸包+简单几何计算

题意: 给N个平面上的点,现在要在离点外L米处建城墙,使得城墙把所有点都包含进去且城墙的长度最短。 解析: 韬哥出的某次训练赛上A出的第一道计算几何,算是大水题吧。 用convexhull算法把凸包求出来,然后加加减减就A了。 计算见下图: 好久没玩画图了啊好开心。 代码: #include <iostream>#include <cstdio>#inclu

uva 1342 欧拉定理(计算几何模板)

题意: 给几个点,把这几个点用直线连起来,求这些直线把平面分成了几个。 解析: 欧拉定理: 顶点数 + 面数 - 边数= 2。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#inc

uva 11178 计算集合模板题

题意: 求三角形行三个角三等分点射线交出的内三角形坐标。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <

XTU 1237 计算几何

题面: Magic Triangle Problem Description: Huangriq is a respectful acmer in ACM team of XTU because he brought the best place in regional contest in history of XTU. Huangriq works in a big compa

计算机毕业设计 大学志愿填报系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试

🍊作者:计算机编程-吉哥 🍊简介:专业从事JavaWeb程序开发,微信小程序开发,定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事,生活就是快乐的。 🍊心愿:点赞 👍 收藏 ⭐评论 📝 🍅 文末获取源码联系 👇🏻 精彩专栏推荐订阅 👇🏻 不然下次找不到哟~Java毕业设计项目~热门选题推荐《1000套》 目录 1.技术选型 2.开发工具 3.功能

代码随想录冲冲冲 Day39 动态规划Part7

198. 打家劫舍 dp数组的意义是在第i位的时候偷的最大钱数是多少 如果nums的size为0 总价值当然就是0 如果nums的size为1 总价值是nums[0] 遍历顺序就是从小到大遍历 之后是递推公式 对于dp[i]的最大价值来说有两种可能 1.偷第i个 那么最大价值就是dp[i-2]+nums[i] 2.不偷第i个 那么价值就是dp[i-1] 之后取这两个的最大值就是d

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

D4代码AC集

贪心问题解决的步骤: (局部贪心能导致全局贪心)    1.确定贪心策略    2.验证贪心策略是否正确 排队接水 #include<bits/stdc++.h>using namespace std;int main(){int w,n,a[32000];cin>>w>>n;for(int i=1;i<=n;i++){cin>>a[i];}sort(a+1,a+n+1);int i=1