图像质量评估——PSNR:峰值信噪比和SSIM:结构相似性(纯手撸代码)

本文主要是介绍图像质量评估——PSNR:峰值信噪比和SSIM:结构相似性(纯手撸代码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • PSNR
    • 原理
    • 代码
    • 运行测试结果
  • SSIM
    • 原理
    • 代码
    • 运行测试结果
  • 总结

PSNR

原理

PSNR 是一种衡量图像质量的指标,它是通过比较原始图像和失真图像之间的差异来计算的。具体来说,PSNR 是通过比较两幅图像的每个像素值来计算的。给定一个大小为 m×n 的干净图像 I 和噪声图像 K,均方误差 (MSE) 定义为:

在这里插入图片描述
然后 PSNR (dB) 就定义为:
在这里插入图片描述
其中 MAX_I^2
为图片可能的最大像素值。如果每个像素都由 8 位二进制来表示,那么就为 255。通常,如果像素值由 B 位二进制来表示,那么 MAX_I = 2^B-1。

PSNR 主要比较的是两幅图像的每个像素值的差异,这种差异被称为 “噪声”。如果两幅图像完全相同,那么噪声就为零,PSNR 就为无穷大。如果两幅图像有很大的差异,那么噪声就会很大,PSNR 就会相应地减小。因此,PSNR 越大,表示图像质量越好。

代码

import numpy as np
import cv2def reorder_image(img, input_order='HWC', output_order='HWC'):''' reorder_image '''if input_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'")if output_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong output_order {output_order}. Supported output_orders are ' "'HWC' and 'CHW'")if len(img.shape) == 2:img, input_order = img[..., None], 'CHW'if input_order == 'CHW' and output_order == 'HWC':img = img.transpose(1, 2, 0)elif input_order == 'HWC' and output_order == 'CHW':img = img.transpose(2, 0, 1)return imgdef _convert_input_type_range(img):''' convert input to [0, 1] '''img_type = img.dtypeimg = img.astype(np.float32)if img_type == np.float32:passelif img_type == np.uint8:img /= 255.else:raise TypeError(f'The img type should be np.float32 or np.uint8, but got {img_type}')return imgdef _convert_output_type_range(img, dst_type):''' convert output to dst_type '''if dst_type not in (np.uint8, np.float32):raise TypeError(f'The dst_type should be np.float32 or np.uint8, but got {dst_type}')if dst_type == np.uint8:img = img.round()else:img /= 255.return img.astype(dst_type)def bgr2ycbcr(img, y_only=False):''' bgr space to ycbcr space '''img_type = img.dtypeimg = _convert_input_type_range(img)if y_only:out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0else:out_img = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) + [16, 128, 128]out_img = _convert_output_type_range(out_img, img_type)return out_imgdef calculate_psnr(img, img2, crop_border, input_order='HWC', test_y_channel=False, **_kwargs):''' calculate_psnr '''assert img.shape == img2.shape, (f'Image shapes are different: {img.shape}, {img2.shape}.')if input_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')if not isinstance(crop_border, (list, tuple)):crop_border = (crop_border, crop_border)img = reorder_image(img, input_order=input_order).astype(np.float64)img2 = reorder_image(img2, input_order=input_order).astype(np.float64)if crop_border[0] != 0:img = img[crop_border[0]:-crop_border[0], ...]img2 = img2[crop_border[0]:-crop_border[0], ...]if crop_border[1] != 0:img = img[:, crop_border[1]:-crop_border[1], ...]img2 = img2[:, crop_border[1]:-crop_border[1], ...]if test_y_channel:img = bgr2ycbcr(img.astype(np.float32) / 255., y_only=True) * 255img2 = bgr2ycbcr(img2.astype(np.float32) / 255., y_only=True) * 255mse = np.mean((img - img2)**2)                 # MSE均方误差if mse == 0:return float('inf')PSNR_result = 20. * np.log10(255. / np.sqrt(mse))return PSNR_resultif __name__ == '__main__':img1 = cv2.imread("datasets/Set5/GTmod12/hh74.png")  # 读入图片1img2 = cv2.imread("visualization/Set5/hh74_ETDS_M4C32_x4.png")  # 读入图片2PSNR_result = calculate_psnr(img1, img2, 4)print("PSNR_result = ",PSNR_result)

运行测试结果

在这里插入图片描述

SSIM

原理

SSIM(结构相似性)是一种衡量两幅图像相似度的指标。相对 PSNR 而言,SSIM 在评价图像质量上更能符合人类的视觉特性。SSIM 使用的两张图像中,一张为未经压缩的无失真图像,另一张为失真后的图像。SSIM 公式基于样本 x 和 y 之间的三个比较衡量:亮度 (luminance)、对比度 (contrast) 和结构 (structure)。具体的计算公式如下所示:

在这里插入图片描述
SSIM 主要比较的是两幅图像的亮度、对比度和结构。这三个因素都是人类视觉系统在评价图像质量时的重要因素。因此,SSIM 能够更好地反映人类视觉系统对图像质量的感知。

代码


import numpy as np
import cv2def reorder_image(img, input_order='HWC', output_order='HWC'):''' reorder_image '''if input_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'")if output_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong output_order {output_order}. Supported output_orders are ' "'HWC' and 'CHW'")if len(img.shape) == 2:img, input_order = img[..., None], 'CHW'if input_order == 'CHW' and output_order == 'HWC':img = img.transpose(1, 2, 0)elif input_order == 'HWC' and output_order == 'CHW':img = img.transpose(2, 0, 1)return imgdef _convert_input_type_range(img):''' convert input to [0, 1] '''img_type = img.dtypeimg = img.astype(np.float32)if img_type == np.float32:passelif img_type == np.uint8:img /= 255.else:raise TypeError(f'The img type should be np.float32 or np.uint8, but got {img_type}')return imgdef _convert_output_type_range(img, dst_type):''' convert output to dst_type '''if dst_type not in (np.uint8, np.float32):raise TypeError(f'The dst_type should be np.float32 or np.uint8, but got {dst_type}')if dst_type == np.uint8:img = img.round()else:img /= 255.return img.astype(dst_type)def bgr2ycbcr(img, y_only=False):''' bgr space to ycbcr space '''img_type = img.dtypeimg = _convert_input_type_range(img)if y_only:out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0else:out_img = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) + [16, 128, 128]out_img = _convert_output_type_range(out_img, img_type)return out_imgdef _ssim(img, img2):''' ssim '''c1, c2 = (0.01 * 255)**2, (0.03 * 255)**2img = img.astype(np.float64)img2 = img2.astype(np.float64)kernel = cv2.getGaussianKernel(11, 1.5)window = np.outer(kernel, kernel.transpose())mu1 = cv2.filter2D(img, -1, window)[5:-5, 5:-5]mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]mu1_sq, mu2_sq = mu1**2, mu2**2mu1_mu2 = mu1 * mu2sigma1_sq = cv2.filter2D(img**2, -1, window)[5:-5, 5:-5] - mu1_sqsigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sqsigma12 = cv2.filter2D(img * 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(img, img2, crop_border, input_order='HWC', test_y_channel=False, **_kwargs):''' calculate_ssim '''assert img.shape == img2.shape, (f'Image shapes are different: {img.shape}, {img2.shape}.')if input_order not in ['HWC', 'CHW']:raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')if not isinstance(crop_border, (list, tuple)):crop_border = (crop_border, crop_border)img = reorder_image(img, input_order=input_order)img2 = reorder_image(img2, input_order=input_order)img = img.astype(np.float64)img2 = img2.astype(np.float64)if crop_border[0] != 0:img = img[crop_border[0]:-crop_border[0], ...]img2 = img2[crop_border[0]:-crop_border[0], ...]if crop_border[1] != 0:img = img[:, crop_border[1]:-crop_border[1], ...]img2 = img2[:, crop_border[1]:-crop_border[1], ...]if test_y_channel:img = bgr2ycbcr(img.astype(np.float32) / 255., y_only=True)[..., None] * 255img2 = bgr2ycbcr(img2.astype(np.float32) / 255., y_only=True)[..., None] * 255ssims = []for i in range(img.shape[2]):ssims.append(_ssim(img[..., i], img2[..., i]))ssims_result = np.array(ssims).mean()return ssims_resultif __name__ == '__main__':img1 = cv2.imread("datasets/Set5/GTmod12/hh74.png")  # 读入图片1img2 = cv2.imread("visualization/Set5/hh74_ETDS_M4C32_x4.png")  # 读入图片2ssims_result = calculate_ssim(img1, img2, 4)print("PSNR_result = ", ssims_result)

运行测试结果

在这里插入图片描述

总结

以上就是图像质量评估——PSNR:峰值信噪比和SSIM:结构相似性的原理及详细代码,希望能帮到你,总结不易,撸码不易,三连多多支持,谢谢!

这篇关于图像质量评估——PSNR:峰值信噪比和SSIM:结构相似性(纯手撸代码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

如何使用Maven创建web目录结构

《如何使用Maven创建web目录结构》:本文主要介绍如何使用Maven创建web目录结构的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录创建web工程第一步第二步第三步第四步第五步第六步第七步总结创建web工程第一步js通过Maven骨架创pytho

Python循环结构全面解析

《Python循环结构全面解析》循环中的代码会执行特定的次数,或者是执行到特定条件成立时结束循环,或者是针对某一集合中的所有项目都执行一次,这篇文章给大家介绍Python循环结构解析,感兴趣的朋友跟随... 目录for-in循环while循环循环控制语句break语句continue语句else子句嵌套的循

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,