图像评价之计算PSNR、SSIM、MSE、LPIPS和NIQE评价指标

文章目录

      • 链接
      • 说明
      • 代码
        • 峰值信噪比
        • 结构相似性
        • 均方误差
        • 学习感知图像块相似性
        • 自然图像质量评估器

链接

GitHub 仓库
如果代码对你的研究有所帮助,请为该仓库点上小星星。

说明

  1. PSNR、SSIM、MSE和LPIPS是有监督指标,计算时必须是两对图像参与;
  2. NIQE是无监督指标,计算时只需要单个图像。

代码

峰值信噪比
import numpy as np
from utils import to_y_channeldef calculate_psnr(img1, img2, test_y_channel=False):"""Calculate PSNR (Peak Signal-to-Noise Ratio).Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratioArgs:img1 (ndarray): Images with range [0, 255].img2 (ndarray): Images with range [0, 255].test_y_channel (bool): Test on Y channel of YCbCr. Default: False.Returns:float: psnr result."""assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')assert img1.shape[2] == 3img1 = img1.astype(np.float64)img2 = img2.astype(np.float64)if test_y_channel:img1 = to_y_channel(img1)img2 = to_y_channel(img2)mse = np.mean((img1 - img2) ** 2)if mse == 0:return float('inf')return 20. * np.log10(255. / np.sqrt(mse))
结构相似性
import cv2
import numpy as np
from utils import to_y_channeldef _ssim(img1, img2):"""Calculate SSIM (structural similarity) for one channel images.It is called by func:`calculate_ssim`.Args:img1 (ndarray): Images with range [0, 255] with order 'HWC'.img2 (ndarray): Images with range [0, 255] with order 'HWC'.Returns:float: ssim result."""C1 = (0.01 * 255) ** 2C2 = (0.03 * 255) ** 2img1 = img1.astype(np.float64)img2 = img2.astype(np.float64)kernel = cv2.getGaussianKernel(11, 1.5)window = np.outer(kernel, kernel.transpose())mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]mu1_sq = mu1 ** 2mu2_sq = mu2 ** 2mu1_mu2 = mu1 * mu2sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sqsigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sqsigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))return ssim_map.mean()def calculate_ssim(img1, img2, test_y_channel=False):"""Calculate SSIM (structural similarity).Ref:Image quality assessment: From error visibility to structural similarityThe results are the same as that of the official released MATLAB code inhttps://ece.uwaterloo.ca/~z70wang/research/ssim/.For three-channel images, SSIM is calculated for each channel and thenaveraged.Args:img1 (ndarray): Images with range [0, 255].img2 (ndarray): Images with range [0, 255].test_y_channel (bool): Test on Y channel of YCbCr. Default: False.Returns:float: ssim result."""assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')assert img1.shape[2] == 3img1 = img1.astype(np.float64)img2 = img2.astype(np.float64)if test_y_channel:img1 = to_y_channel(img1)img2 = to_y_channel(img2)ssims = []for i in range(img1.shape[2]):ssims.append(_ssim(img1[..., i], img2[..., i]))return np.array(ssims).mean()
均方误差
import numpy as np
from utils import to_y_channeldef calculate_mse(img1, img2, test_y_channel=False):assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')assert img1.shape[2] == 3img1 = img1.astype(np.float64)img2 = img2.astype(np.float64)if test_y_channel:img1 = to_y_channel(img1)img2 = to_y_channel(img2)return np.mean((img1 - img2) ** 2)
学习感知图像块相似性
import lpipsdevice = 'cuda' if torch.cuda.is_available() else 'cpu'
calculate_lpips = lpips.LPIPS(net='alex', verbose=False).to(device)
自然图像质量评估器
import cv2
import math
import numpy as np
from scipy.special import gamma
from utils import to_y_channel
from scipy.ndimage.filters import convolvedef reorder_image(img, input_order='HWC'):"""Reorder images to 'HWC' order.If the input_order is (h, w), return (h, w, 1);If the input_order is (c, h, w), return (h, w, c);If the input_order is (h, w, c), return as it is.Args:img (ndarray): Input image.input_order (str): Whether the input order is 'HWC' or 'CHW'.If the input image shape is (h, w), input_order will not haveeffects. Default: 'HWC'.Returns:ndarray: reordered image."""if input_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are '"'HWC' and 'CHW'")if len(img.shape) == 2:img = img[..., None]if input_order == 'CHW':img = img.transpose(1, 2, 0)return imgdef estimate_aggd_param(block):"""Estimate AGGD (Asymmetric Generalized Gaussian Distribution) paramters.Args:block (ndarray): 2D Image block.Returns:tuple: alpha (float), beta_l (float) and beta_r (float) for the AGGDdistribution (Estimating the parames in Equation 7 in the paper)."""block = block.flatten()gam = np.arange(0.2, 10.001, 0.001)  # len = 9801gam_reciprocal = np.reciprocal(gam)r_gam = np.square(gamma(gam_reciprocal * 2)) / (gamma(gam_reciprocal) * gamma(gam_reciprocal * 3))left_std = np.sqrt(np.mean(block[block < 0]**2))right_std = np.sqrt(np.mean(block[block > 0]**2))gammahat = left_std / right_stdrhat = (np.mean(np.abs(block)))**2 / np.mean(block**2)rhatnorm = (rhat * (gammahat**3 + 1) *(gammahat + 1)) / ((gammahat**2 + 1)**2)array_position = np.argmin((r_gam - rhatnorm)**2)alpha = gam[array_position]beta_l = left_std * np.sqrt(gamma(1 / alpha) / gamma(3 / alpha))beta_r = right_std * np.sqrt(gamma(1 / alpha) / gamma(3 / alpha))return (alpha, beta_l, beta_r)def compute_feature(block):"""Compute features.Args:block (ndarray): 2D Image block.Returns:list: Features with length of 18."""feat = []alpha, beta_l, beta_r = estimate_aggd_param(block)feat.extend([alpha, (beta_l + beta_r) / 2])shifts = [[0, 1], [1, 0], [1, 1], [1, -1]]for i in range(len(shifts)):shifted_block = np.roll(block, shifts[i], axis=(0, 1))alpha, beta_l, beta_r = estimate_aggd_param(block * shifted_block)# Eq. 8mean = (beta_r - beta_l) * (gamma(2 / alpha) / gamma(1 / alpha))feat.extend([alpha, mean, beta_l, beta_r])return featdef niqe(img,mu_pris_param,cov_pris_param,gaussian_window,block_size_h=96,block_size_w=96):"""Calculate NIQE (Natural Image Quality Evaluator) metric.Ref: Making a "Completely Blind" Image Quality Analyzer.This implementation could produce almost the same results as the officialMATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zipNote that we do not include block overlap height and width, since they arealways 0 in the official implementation.For good performance, it is advisable by the official implemtation todivide the distorted image in to the same size patched as used for theconstruction of multivariate Gaussian model.Args:img (ndarray): Input image whose quality needs to be computed. Theimage must be a gray or Y (of YCbCr) image with shape (h, w).Range [0, 255] with float type.mu_pris_param (ndarray): Mean of a pre-defined multivariate Gaussianmodel calculated on the pristine dataset.cov_pris_param (ndarray): Covariance of a pre-defined multivariateGaussian model calculated on the pristine dataset.gaussian_window (ndarray): A 7x7 Gaussian window used for smoothing theimage.block_size_h (int): Height of the blocks in to which image is divided.Default: 96 (the official recommended value).block_size_w (int): Width of the blocks in to which image is divided.Default: 96 (the official recommended value)."""assert img.ndim == 2, ('Input image must be a gray or Y (of YCbCr) image with shape (h, w).')h, w = img.shapenum_block_h = math.floor(h / block_size_h)num_block_w = math.floor(w / block_size_w)img = img[0:num_block_h * block_size_h, 0:num_block_w * block_size_w]distparam = []for scale in (1, 2):mu = convolve(img, gaussian_window, mode='nearest')sigma = np.sqrt(np.abs(convolve(np.square(img), gaussian_window, mode='nearest') -np.square(mu)))img_nomalized = (img - mu) / (sigma + 1)feat = []for idx_w in range(num_block_w):for idx_h in range(num_block_h):block = img_nomalized[idx_h * block_size_h //scale:(idx_h + 1) * block_size_h //scale, idx_w * block_size_w //scale:(idx_w + 1) * block_size_w //scale]feat.append(compute_feature(block))distparam.append(np.array(feat))if scale == 1:h, w = img.shapeimg = cv2.resize(img / 255., (w // 2, h // 2), interpolation=cv2.INTER_LINEAR)img = img * 255.distparam = np.concatenate(distparam, axis=1)mu_distparam = np.nanmean(distparam, axis=0)distparam_no_nan = distparam[~np.isnan(distparam).any(axis=1)]cov_distparam = np.cov(distparam_no_nan, rowvar=False)invcov_param = np.linalg.pinv((cov_pris_param + cov_distparam) / 2)quality = np.matmul(np.matmul((mu_pris_param - mu_distparam), invcov_param),np.transpose((mu_pris_param - mu_distparam)))quality = np.sqrt(quality)return qualitydef calculate_niqe(img, crop_border, input_order='HWC', convert_to='y'):"""Calculate NIQE (Natural Image Quality Evaluator) metric.Ref: Making a "Completely Blind" Image Quality Analyzer.This implementation could produce almost the same results as the officialMATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zipWe use the official params estimated from the pristine dataset.We use the recommended block size (96, 96) without overlaps.Args:img (ndarray): Input image whose quality needs to be computed.The input image must be in range [0, 255] with float/int type.The input_order of image can be 'HW' or 'HWC' or 'CHW'. (BGR order)If the input order is 'HWC' or 'CHW', it will be converted to grayor Y (of YCbCr) image according to the ``convert_to`` argument.crop_border (int): Cropped pixels in each edge of an image. Thesepixels are not involved in the metric calculation.input_order (str): Whether the input order is 'HW', 'HWC' or 'CHW'.Default: 'HWC'.convert_to (str): Whether coverted to 'y' (of MATLAB YCbCr) or 'gray'.Default: 'y'.Returns:float: NIQE result."""niqe_pris_params = np.load('./niqe_pris_params.npz')mu_pris_param = niqe_pris_params['mu_pris_param']cov_pris_param = niqe_pris_params['cov_pris_param']gaussian_window = niqe_pris_params['gaussian_window']img = img.astype(np.float32)if input_order != 'HW':img = reorder_image(img, input_order=input_order)if convert_to == 'y':img = to_y_channel(img)elif convert_to == 'gray':img = cv2.cvtColor(img / 255., cv2.COLOR_BGR2GRAY) * 255.img = np.squeeze(img)if crop_border != 0:img = img[crop_border:-crop_border, crop_border:-crop_border]niqe_result = niqe(img, mu_pris_param, cov_pris_param, gaussian_window)return niqe_result

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/165985.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

安索夫矩阵(ANSOFF)

&#x1f449;安索夫矩阵是策略管理之父安索夫博士于1957年提出的营销策略模型&#xff0c;该模型以“产品”和“市场”作为两大基本面&#xff0c;提出了4种不同组合下的营销策略&#xff0c;是营销分析中应用最广泛的工具之一。其主要逻辑是通过选择4种不同的成长性策略来实现…

C++11的线程

线程的创建 用std::thread创建线程非常简单&#xff0c;只需要提供线程函数或者线程对象即可&#xff0c;并可以同时指定线程函数的参数。下面是创建线程的示例&#xff1a; #include <thread> #include <iostream> using namespace std;void func() {cout <<…

C# 获取图像、字体等对象大小的数据结构SizeF

如果你想要获取字符串 "你好吗" 的字节数组长度或者字符数&#xff0c; 使用如下代码&#xff1a; string s "你好吗"; //字节数组长度 int byteCount System.Text.Encoding.UTF8.GetBytes(s).Length; //字符数 int charCount s.Length; 如果你想获取…

大话设计模式C++实现

大话设计模式&#xff0c;讲得非常好&#xff0c;但是作者是用C#写的&#xff0c;为了方便C程序员&#xff0c;使用C写了大话设计模式的代码 详情见Github&#xff1a;https://github.com/liubamboo/BigTalkDesignPattern

新苹果手机如何导入旧手机数据?解决方案来了,记得收藏!

为了保持其竞争优势&#xff0c;苹果公司不断推出新的产品和服务&#xff0c;因此苹果手机的更新换代速度是比较快的。正巧最近刚出了iPhone15&#xff0c;相信很多小伙伴已经换上了期待已久的新手机。 更换新手机后&#xff0c;大家都会面临一个问题&#xff1a;新苹果手机如…

java 手机商城免费搭建+电商源码+小程序+三级分销+SAAS云平台

【SAAS云平台】打造全行业全渠道全场景的SaaS产品&#xff0c;为店铺经营场景提供一体化解决方案&#xff1b;门店经营区域化、网店经营一体化&#xff0c;本地化、全方位、一站式服务&#xff0c;为多门店提供统一运营解决方案&#xff1b;提供丰富多样的营销玩法覆盖所有经营…

Windows DOS 常用命令

文章目录 1 概述1.1 官方文档1.2 常用 2 分类2.1 目录2.2 文件2.3 网络2.4 系统 1 概述 1.1 官方文档 Windows 命令官方文档&#xff1a;https://learn.microsoft.com/zh-cn/windows-server/administration/windows-commands/windows-commands 1.2 常用 win r # 打开运…

如何预防数据泄露?六步策略帮您打造企业信息安全壁垒

大家好&#xff01;我是恒小驰&#xff0c;今天我想和大家聊聊一个非常重要的话题——如何预防数据泄露。在这个数字化的时代&#xff0c;数据已经成为了我们生活中不可或缺的一部分。然而&#xff0c;随着数据的价值日益凸显&#xff0c;数据泄露的风险也随之增加。企业应该如…

MacBook使用指南

一、安装及卸载Windows系统 1、卸载Windows系统 步骤① 点击下侧任务栏中的“启动台”&#xff0c;进入程序坞&#xff0c;点击"其他",选择“启动转换助理” 步骤② 点击“继续”&#xff0c;接着点击“恢复”&#xff0c;即可卸载Windows系统 2、安装Windows系统 …

Shell编程里if的参数从-a到-z详解

Shell编程里if的参数从-a到-z详解

智能医疗越发周到!新的机器人系统评估中风后的活动能力

原创 | 文 BFT机器人 中风是在医疗界上最难的解决的病例之一&#xff0c;全球每年有超过1500万人中风&#xff0c;四分之三的中风患者的手臂和手部会出现损伤、虚弱和瘫痪。 许多中风患者日常生活是依靠他们强壮的手臂来完成的&#xff0c;从拿一些小东西到梳头&#xff0c;即…

phpstudy和IDEA 配置php debug

1.安装xdebug 扩展&#xff0c;phpinfo() 查看 2.配置php.ini zend_extensionD:/phpstudy_pro/Extensions/php/php7.4.3nts/ext/php_xdebug.dll xdebug.collect_params1 xdebug.collect_return1 xdebug.auto_traceOn xdebug.trace_output_dirD:/phpstudy_pro/Extensions/php_l…

c语言新龟兔赛跑

以下是一个使用C语言编写的新的龟兔赛跑游戏&#xff1a; #include <stdio.h>#include <stdlib.h>#include <time.h>int main() { int distance, turtle_speed, rabbit_speed, turtle_time, rabbit_time, rabbit_lead; srand(time(NULL)); // 随机数种…

Whatweb简单使用

目录 简介 安装 debian/ubtuntu redhat/centos 特性 使用 常用参数如下&#xff1a; whatweb -v whatweb --version whatweb -i 1.txt whatweb -v www.baidu.com 扫描等级 whatweb -a 4 www.baidu.com 扫描网段 whatweb --no-errors -t 255 192.168.71.0/24 导出…

http与https有什么区别,https攻击要如何防护

我们在浏览网站时&#xff0c;在网址的前面经常会看到http// 或者https//的显示。同样是http&#xff0c;加了s与不加s是有什么区别&#xff0c;加了s又有哪些用处。 http&#xff0c;中文叫做超文本传输协议。它是一种用于分布式、协作式和超媒体信息系统的应用层协议。是基于…

在vscode中添加代码提示

添加配置 run->add_configuration 添加头文件路径 在c_cpp_properties.json中添加头文件路径 效果

时间敏感网络TSN的车载设计实践: 802.1Qbv协议

▎概述 IEEE 802.1Qbv[1]是TSN系列协议中备受关注的技术之一&#xff0c;如图1所示&#xff0c;它定义了一种时间感知整形器&#xff08;Time Aware Shaper&#xff0c;TAS&#xff09;&#xff0c;支持Qbv协议的交换机可以按照配置好的门控列表来打开/关闭交换机出口队列&…

Spring Validation实践及其实现原理

Bean Validation 2.0 注解 校验空值 Null&#xff1a;验证对象是否为 null NotNull&#xff1a;验证对象是否不为 null NotEmpty&#xff1a;验证对象不为 null&#xff0c;且长度&#xff08;数组、集合、字符串等&#xff09;大于 0 NotBlank&#xff1a;验证字符串不为 nul…

2023软件应用类下载系统平台源码/手机软件应用、新闻资讯下载站/软件库网站源码

源码简介&#xff1a; 这个是最新软件应用类平台源码、手机应用下载系统源码、软件应用市场下载站源码、新闻资讯软件下载。2023软件应用类平台源码/手机软件应用、新闻资讯下载站&#xff0c;它是软件库网站源码。 最新软件应用类平台源码 手机应用下载系统源码 软件应用市场…