SSIM算法用c++怎么实现两张图进行对比
时间: 2023-12-10 16:40:20 浏览: 562
psnr_ssim源代码
SSIM算法是一种用于测量两张图像之间结构相似性的算法,可以用来评估图像质量。下面是一个简单的C++实现:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
double getSSIM(Mat& img1, Mat& img2)
{
const double C1 = 6.5025, C2 = 58.5225;
int d = CV_32F;
Mat I1, I2;
img1.convertTo(I1, d);
img2.convertTo(I2, d);
Mat I2_2 = I2.mul(I2);
Mat I1_2 = I1.mul(I1);
Mat I1_I2 = I1.mul(I2);
Mat mu1, mu2;
GaussianBlur(I1, mu1, Size(11, 11), 1.5);
GaussianBlur(I2, mu2, Size(11, 11), 1.5);
Mat mu1_2 = mu1.mul(mu1);
Mat mu2_2 = mu2.mul(mu2);
Mat mu1_mu2 = mu1.mul(mu2);
Mat sigma1_2, sigma2_2, sigma12;
GaussianBlur(I1_2, sigma1_2, Size(11, 11), 1.5);
sigma1_2 -= mu1_2;
GaussianBlur(I2_2, sigma2_2, Size(11, 11), 1.5);
sigma2_2 -= mu2_2;
GaussianBlur(I1_I2, sigma12, Size(11, 11), 1.5);
sigma12 -= mu1_mu2;
Mat t1, t2, t3;
t1 = 2 * mu1_mu2 + C1;
t2 = 2 * sigma12 + C2;
t3 = t1.mul(t2);
t1 = mu1_2 + mu2_2 + C1;
t2 = sigma1_2 + sigma2_2 + C2;
t1 = t1.mul(t2);
Mat ssim_map;
divide(t3, t1, ssim_map);
Scalar mssim = mean(ssim_map);
return mssim[0];
}
int main()
{
Mat img1 = imread("img1.jpg", IMREAD_GRAYSCALE);
Mat img2 = imread("img2.jpg", IMREAD_GRAYSCALE);
double ssim = getSSIM(img1, img2);
cout << "SSIM: " << ssim << endl;
return 0;
}
```
其中,`getSSIM()`函数用于计算两张图像的SSIM值。具体实现是先对图像进行高斯模糊,然后计算图像均值、方差和协方差等参数,并根据这些参数计算出SSIM值。在`main()`函数中,我们读取两张图像并调用`getSSIM()`函数来计算它们的SSIM值。
需要注意的是,这里使用了OpenCV库来读取图像和进行高斯模糊等操作,因此需要安装OpenCV库并将其链接到程序中。
阅读全文