10.噪声和PSNR:这部分的实验介绍了用于图像质量评估的误差度量。两个常见的指标是均方误差(MSE)和峰值信噪比(PSNR)。MSE是处理后的图像与原始图像之间的累积平方误差。PSNR利用了MSE。MSE越小,误差越小。PSNR越大,误差越小。您将向测试图像添加不同数量的随机噪声,并测量它们的MSE和PSNR。 创建一个函数,可以将(i)椒盐噪声和(ii)高斯噪声添加到PGM图像中,并计算PSNR和MSE。显示结果,并写出原始与损坏的MSE和PSNR的值。
时间: 2024-03-03 08:47:35 浏览: 16
好的,以下是一个MATLAB函数,可以用于添加椒盐噪声或高斯噪声到PGM格式的图像中,并计算PSNR和MSE。
```matlab
function [noisyImg, mseVal, psnrVal] = addNoiseAndCalcPSNR_MSE(originalImg, noiseType, noiseParam)
% 读取原始图像
img = imread(originalImg);
% 转换为灰度图像
if size(img,3) == 3
img = rgb2gray(img);
end
% 添加噪声
if strcmp(noiseType, 'salt & pepper')
noisyImg = imnoise(img, 'salt & pepper', noiseParam);
elseif strcmp(noiseType, 'gaussian')
noisyImg = imnoise(img, 'gaussian', 0, noiseParam^2);
else
error('Unsupported noise type!');
end
% 计算MSE
mseVal = mean((img(:) - noisyImg(:)).^2);
% 计算PSNR
maxPixelVal = double(max(noisyImg(:)));
psnrVal = 10*log10((maxPixelVal^2)/mseVal);
% 显示结果
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(noisyImg);
title(sprintf('Noisy Image (%s, %d)', noiseType, noiseParam));
sgtitle(sprintf('MSE=%.2f, PSNR=%.2f', mseVal, psnrVal));
```
使用方法如下:
1. 准备原始PGM格式图像,例如`lena.pgm`。
2. 调用函数进行添加噪声和计算MSE、PSNR:
```matlab
% 添加椒盐噪声,噪声密度为0.1
[noisyImg, mseVal, psnrVal] = addNoiseAndCalcPSNR_MSE('lena.pgm', 'salt & pepper', 0.1);
% 添加高斯噪声,标准差为10
[noisyImg, mseVal, psnrVal] = addNoiseAndCalcPSNR_MSE('lena.pgm', 'gaussian', 10);
```
函数会显示原始图像和添加噪声后的图像,并在标题中显示MSE和PSNR的值。
注意:该函数只支持PGM格式的图像,如果要处理其他格式的图像需要进行相应的修改。