当前位置: 首页 > news >正文

计算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}')
http://www.lryc.cn/news/335813.html

相关文章:

  • OpenHarmony开发技术:【国际化】实例
  • c++子类和父类成员函数重名
  • 《C++程序设计》阅读笔记【7-堆和拷贝构造函数】
  • 洛谷 P1048 [NOIP2005 普及组] 采药
  • VMware vSphere虚拟化基础管理平台
  • leetcode刷题-代码训练营-第7章-回溯算法1
  • 三种常见webshell工具的流量特征分析
  • pkg打包nodejs程序用动态require路由出现问题
  • 设计模式(018)行为型之策略模式
  • c++关键字: =delete和=default
  • JSON
  • Python | 超前滞后分析
  • Linux CPU利用率
  • vue3实现导出pdf、png功能
  • what is tty?
  • 在vite中限制node版本
  • 07 Php学习:运算符
  • 做了多年前端,有没有想在python,go,nodejs,.net,java,c++中学一门后端,推荐
  • JR-SMD201-P便携式网络解码器
  • 线程池阻塞队列的选择
  • linux内核驱动-在内核代码里添加设备结点
  • 【算法优选】 动态规划之简单多状态dp问题——贰
  • 【算法刷题 | 二叉树 06】4.10( 路径总和、路径总和 || )
  • 代码学习记录37----动态规划
  • Spring Boot:Web开发之三大组件的整合
  • 2024.3.15力扣每日一题——卖木头块
  • vue快速入门(七)内联语句
  • Docker实战教程 第2章 Docker基础
  • 【S32K3 MCAL配置】-3.2-CANFD配置-发送“经典CAN/CANFD标准帧“和“经典CAN/CANFD扩展帧“(基于MCAL+FreeRTOS)
  • 【airtest】自动化入门教程(四)Poco元素定位