当前位置: 首页 > 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}')

相关文章:

计算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 P…...

OpenHarmony开发技术:【国际化】实例

国际化 如今越来的越多的应用都走向了海外,应用走向海外需要支持不同国家的语言,这就意味着应用资源文件需要支持不同语言环境下的显示。本节就介绍一下设备语言环境变更后,如何让应用支持多语言。 应用支持多语言 ArkUI开发框架对多语言的…...

c++子类和父类成员函数重名

子类和父类返回值参数相同,函数名相同,有virtual关键字,则由对象的类型决定调用哪个函数。子类和父类只要函数名相同,没有virtual关键字,则子类的对象没有办法调用到父类的同名函数,父类的同名函数被隐藏了&#xff0c…...

《C++程序设计》阅读笔记【7-堆和拷贝构造函数】

🌈个人主页:godspeed_lucip 🔥 系列专栏:《C程序设计》阅读笔记 本文对应的PDF源文件请关注微信公众号程序员刘同学,回复C程序设计获取下载链接。 1 堆与拷贝构造函数1.1 概述1.2 分配堆对象1.3 拷贝构造函数1.3.1 默…...

洛谷 P1048 [NOIP2005 普及组] 采药

辰辰是个天资聪颖的孩子,他的梦想是成为世界上最伟大的医师。为此,他想拜附近最有威望的医师为师。医师为了判断他的资质,给他出了一个难题。医师把他带到一个到处都是草药的山洞里对他说:“孩子,这个山洞里有一些不同…...

VMware vSphere虚拟化基础管理平台

VMware简介 VMware介绍 官网:https://www.vmware.com/cn.html VMware公司成立于1998年,2003年存储厂商EMC以6.35亿美元收购了VMware;2015年10月,戴尔宣布以670亿美元收购EMC。VMware公司在2018年全年收入79.2亿美元。 VMware主…...

leetcode刷题-代码训练营-第7章-回溯算法1

回溯法模板 void backtracking(参数) {if (终止条件) {存放结果;return;}for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {处理节点;backtracking(路径,选择列表); // 递归回溯,撤销处理结果} }理解 从…...

三种常见webshell工具的流量特征分析

又来跟师傅们分享小技巧了,这次简单介绍一下三种常见的webshell流量分析,希望能对参加HW蓝队的师傅们有所帮助。 什么是webshell webshell就是以asp、php、jsp或者cgi等网页文件形式存在的一种代码执行环境,主要用于网站管理、服务器管理、…...

pkg打包nodejs程序用动态require路由出现问题

动态路由问题 pkg打包的时候会自动生成一个虚拟路径/snapshot/…会导致你的路径出现一些问题 而项目中依据route文件夹下的文件动态use相应的router,这就需要动态require,但是这个require的路径会被虚拟路径代替导致取不到,所以可以使用写死…...

设计模式(018)行为型之策略模式

策略模式是一种行为设计模式,它定义了一系列算法,将每个算法封装成一个对象,并使它们可以互换。策略模式使得算法的变化可以独立于使用算法的客户端。在策略模式中,有三个核心角色:策略接口(Strategy&#…...

c++关键字: =delete和=default

delete 概述 delete关键字是c11新增的关键字,主要用于的场景是:当我们不希望类中的函数被类对象在外部调用的时候,我们就可以使用这个关键字。 其实,之前我们实现这种功能是将这些函数放在private修饰符下,但是这种方…...

JSON

文章目录 JSONJSON 的定义格式快速入门JSON 对象和字符串对象转换JSON 在 java 中使用JSON与java对象的转换JSON与List集合的转换JSON与Map的转换 JSON JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式…...

Python | 超前滞后分析

Nino SST Indices (Nino 12, 3, 3.4, 4; ONI and TNI) 有几个指标用于监测热带太平洋,所有这些指标都是基于海表温度(SST)异常在一个给定的区域的平均值。通常,异常是相对于30年的周期来计算的。厄尔尼诺3.4指数(Nio 3.4 index)和海洋厄尔尼诺指数(Ocea…...

Linux CPU利用率

Linux CPU利用率 在线上服务器观察线上服务运行状态的时候,绝大多数人都是喜欢先用 top 命令看看当前系统的整体 cpu 利用率。例如,随手拿来的一台机器,top 命令显示的利用率信息如下 这个输出结果说简单也简单,说复杂也不是那么…...

vue3实现导出pdf、png功能

准备做的系统中出现了 想导出当前页面的png或者pdf设计数据较多后端做可能比较麻烦 就自己研究了一下 1、安装html2canvas 、jspdf包 npm install --save html2canvas // 可以将dom元素转为一张图片 npm install --save jspdf // 导出为PDF格式 2、vue组件中引用&#x…...

what is tty?

waht is tty? 黑话:TTY 为什么使用Linux的时候CtrlC就会终止一个命令运行,ta是如何设置的? stty -a 桌面切换 CTRL ALT F1 – 锁屏 CTRL ALT F2 – 桌面环境 CTRL ALT F3 – TTY3 CTRL ALT F4 – TTY4 CTRL ALT F5 – TTY5 CTRL ALT F6 – TTY6...

在vite中限制node版本

1.修改package.json文件 {"name": "wine-store-frontend","version": "0.0.0","private": true,"type": "module","scripts": {"dev": "vite --open","build"…...

07 Php学习:运算符

PHP 算术运算符 在 PHP 中,算术运算符用于执行基本的数学运算,包括加法、减法、乘法、除法、取余数,负数运算、取反和并置运算。以下是这些运算符的详细解释和示例: 加法运算符 :用于将两个数值相加。 $a 5; $b 3;…...

做了多年前端,有没有想在python,go,nodejs,.net,java,c++中学一门后端,推荐

作为一名经验丰富的前端开发者,选择学习后端技术是一个重要的职业发展决策。Python、Go、Node.js、.NET、Java和C都是强大的后端开发语言,每门语言都有其特定的优势和应用场景。以下是对这些技术的分析,以帮助你做出选择: 目录 …...

JR-SMD201-P便携式网络解码器

详细介绍: JR-SMD201-P便携式网络解码器采用1/2U设计,支持AVS/H.265/H.264/MPEG2解码,支持IP输入,支持1080P/1080I/720P/576I/480I多种分辨率,支持DRA/AC3/EAC3/AAC/MPEG等音频。 产品特点 支持输入方式IP 接口丰富&a…...

eNSP-Cloud(实现本地电脑与eNSP内设备之间通信)

说明: 想象一下,你正在用eNSP搭建一个虚拟的网络世界,里面有虚拟的路由器、交换机、电脑(PC)等等。这些设备都在你的电脑里面“运行”,它们之间可以互相通信,就像一个封闭的小王国。 但是&#…...

云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?

大家好,欢迎来到《云原生核心技术》系列的第七篇! 在上一篇,我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在,我们就像一个拥有了一块崭新数字土地的农场主,是时…...

调用支付宝接口响应40004 SYSTEM_ERROR问题排查

在对接支付宝API的时候,遇到了一些问题,记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...

微信小程序之bind和catch

这两个呢,都是绑定事件用的,具体使用有些小区别。 官方文档: 事件冒泡处理不同 bind:绑定的事件会向上冒泡,即触发当前组件的事件后,还会继续触发父组件的相同事件。例如,有一个子视图绑定了b…...

遍历 Map 类型集合的方法汇总

1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module

1、为什么要修改 CONNECT 报文? 多租户隔离:自动为接入设备追加租户前缀,后端按 ClientID 拆分队列。零代码鉴权:将入站用户名替换为 OAuth Access-Token,后端 Broker 统一校验。灰度发布:根据 IP/地理位写…...

srs linux

下载编译运行 git clone https:///ossrs/srs.git ./configure --h265on make 编译完成后即可启动SRS # 启动 ./objs/srs -c conf/srs.conf # 查看日志 tail -n 30 -f ./objs/srs.log 开放端口 默认RTMP接收推流端口是1935,SRS管理页面端口是8080,可…...

SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现

摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序,以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务,提供稳定高效的数据处理与业务逻辑支持;利用 uniapp 实现跨平台前…...

Module Federation 和 Native Federation 的比较

前言 Module Federation 是 Webpack 5 引入的微前端架构方案,允许不同独立构建的应用在运行时动态共享模块。 Native Federation 是 Angular 官方基于 Module Federation 理念实现的专为 Angular 优化的微前端方案。 概念解析 Module Federation (模块联邦) Modul…...

三体问题详解

从物理学角度,三体问题之所以不稳定,是因为三个天体在万有引力作用下相互作用,形成一个非线性耦合系统。我们可以从牛顿经典力学出发,列出具体的运动方程,并说明为何这个系统本质上是混沌的,无法得到一般解…...