PSNR和SSIM的c++实现
时间: 2024-03-04 11:19:49 浏览: 88
您好!下面是PSNR(峰值信噪比)和SSIM(结构相似性指数)的C++实现示例:
PSNR的C++实现示例:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
double calculatePSNR(const cv::Mat& original, const cv::Mat& compressed) {
cv::Mat diff;
cv::absdiff(original, compressed, diff);
diff.convertTo(diff, CV_32F);
diff = diff.mul(diff);
double mse = cv::mean(diff)[0];
double psnr = 10.0 * log10((255 * 255) / mse);
return psnr;
}
int main() {
cv::Mat original = cv::imread("original.png", cv::IMREAD_GRAYSCALE);
cv::Mat compressed = cv::imread("compressed.png", cv::IMREAD_GRAYSCALE);
if (original.empty() || compressed.empty()) {
std::cout << "Failed to load images!" << std::endl;
return -1;
}
double psnr = calculatePSNR(original, compressed);
std::cout << "PSNR: " << psnr << " dB" << std::endl;
return 0;
}
```
请注意,上述示例使用了OpenCV库来处理图像。
SSIM的C++实现示例:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
cv::Scalar calculateSSIM(const cv::Mat& original, const cv::Mat& compressed) {
const double C1 = 6.5025, C2 = 58.5225;
cv::Mat originalFloat, compressedFloat;
original.convertTo(originalFloat, CV_32F);
compressed.convertTo(compressedFloat, CV_32F);
cv::Mat originalSquared = originalFloat.mul(originalFloat);
cv::Mat compressedSquared = compressedFloat.mul(compressedFloat);
cv::Mat originalCompressed = originalFloat.mul(compressedFloat);
cv::Mat muOriginal, muCompressed;
cv::GaussianBlur(originalFloat, muOriginal, cv::Size(11, 11), 1.5);
cv::GaussianBlur(compressedFloat, muCompressed, cv::Size(11, 11), 1.5);
cv::Mat muOriginalSquared = muOriginal.mul(muOriginal);
cv::Mat muCompressedSquared = muCompressed.mul(muCompressed);
cv::Mat muOriginalCompressed = muOriginal.mul(muCompressed);
cv::Mat sigmaOriginalSquared, sigmaCompressedSquared, sigmaOriginalCompressed;
cv::GaussianBlur(originalSquared, sigmaOriginalSquared, cv::Size(11, 11), 1.5);
sigmaOriginalSquared -= muOriginalSquared;
cv::GaussianBlur(compressedSquared, sigmaCompressedSquared, cv::Size(11, 11), 1.5);
sigmaCompressedSquared -= muCompressedSquared;
cv::GaussianBlur(originalCompressed, sigmaOriginalCompressed, cv::Size(11, 11), 1.5);
sigmaOriginalCompressed -= muOriginalCompressed;
cv::Mat ssimMap;
cv::divide((2 * muOriginalCompressed + C1) * (2 * sigmaOriginalCompressed + C2), (muOriginalSquared + muCompressedSquared + C1) * (sigmaOriginalSquared + sigmaCompressedSquared + C2), ssimMap);
cv::Scalar ssim = cv::mean(ssimMap);
return ssim;
}
int main() {
cv::Mat original = cv::imread("original.png", cv::IMREAD_GRAYSCALE);
cv::Mat compressed = cv::imread("compressed.png", cv::IMREAD_GRAYSCALE);
if (original.empty() || compressed.empty()) {
std::cout << "Failed to load images!" << std::endl;
return -1;
}
cv::Scalar ssim = calculateSSIM(original, compressed);
std::cout << "SSIM: " << ssim[0] << std::endl;
return 0;
}
```
上述示例同样使用了OpenCV库来处理图像。请确保将原始图像和压缩图像的文件路径正确地指定在`imread`函数中。
希望对您有所帮助!如有任何疑问,请随时追问。
阅读全文