峰值信噪比是一个工程术语,表示信号的最大可能功率与影响其表示保真度的破坏性噪声功率之间的比率。由于许多信号的动态范围非常宽,因此 PSNR 通常使用分贝标度表示为对数值。通常用于量化经过有损压缩的图像和视频的重建质量。
这里,M A X 是图像的最大可能像素值。当像素使用每个样本 8 位表示时,该值为 255 。更一般地,当样本使用每个样本 B 位的线性 PCM 表示时,M A X_l 为 2^B-1。
from math import log10, sqrt
import cv2
import numpy as np
def PSNR(original, compressed):
mse = np.mean((original - compressed) ** 2)
if(mse == 0):
return 100
max_pixel = 255.0
psnr = 20 * log10(max_pixel / sqrt(mse))
return psnr
def main():
original = cv2.imread("original_image.png")
compressed = cv2.imread("compressed_image.png", 1)
value = PSNR(original, compressed)
print(f"PSNR value is {value} dB")
if __name__ == "__main__":
main()
应用滤波器来减轻各种类型的噪声(如高斯、椒盐、斑点、泊松和指数)来去除图像噪声。我们将利用 Python 的 scipy.ndimage 和 skimage 库来演示均值和中值滤波器在噪声图像上的应用,并使用峰值信噪比 (PSNR) 比较它们的有效性。
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from skimage.io import imread
from skimage.color import rgb2gray
from skimage.util import random_noise
from skimage.metrics import peak_signal_noise_ratio as compare_psnr
from scipy.ndimage import uniform_filter, median_filter
def plt_hist(noise, title='Noise Histogram', bins=None):
plt.grid()
plt.hist(noise.ravel(), bins=bins, alpha=0.5, color='green')
plt.tick_params(labelsize=15)
plt.title(title, size=25)
def plt_images(original_img, noisy_img, denoised_mean_img, denoised_median_img, noise, noise_type):
fig, axes = plt.subplots(1, 4, figsize=(20, 5))
ax = axes.ravel()
ax[0].imshow(original_img, cmap='gray')
ax[0].set_title('Original', size=20)
ax[0].axis('off')
ax[1].imshow(noisy_img, cmap='gray')
ax[1].set_title(f'Noisy ({noise_type})', size=20)
ax[1].axis('off')
ax[2].imshow(denoised_mean_img, cmap='gray')
ax[2].set_title('Denoised (Mean)', size=20)
ax[2].axis('off')
ax[3].imshow(denoised_median_img, cmap='gray')
ax[3].set_title('Denoised (Median)', size=20)
ax[3].axis('off')
plt.figure()
plt_hist(noise, title=f'{noise_type} Noise Histogram')
plt.show()
print(f"PSNR (Original vs Noisy): {compare_psnr(original_img, noisy_img):.3f}")
print(f"PSNR (Original vs Denoised Mean): {compare_psnr(original_img, denoised_mean_img):.3f}")
print(f"PSNR (Original vs Denoised Median): {compare_psnr(original_img, denoised_median_img):.3f}")
Loading the image and converting to Gray scale
image_path = 'lena.png'
original_img = rgb2gray(imread(image_path))
denoised_mean_img = uniform_filter(noisy_img, size=5)
denoised_median_img = median_filter(noisy_img, size=5)
plt_images(original_img, noisy_img, denoised_mean_img, denoised_median_img, noisy_img-original_img, 'Gaussian')
class Autoencoder(nn.Module):
def __init__(self):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(50 * 37, 512),
nn.ReLU(True),
nn.Linear(512, 128),
nn.ReLU(True))
self.decoder = nn.Sequential(
nn.Linear(128, 512),
nn.ReLU(True),
nn.Linear(512, 50 * 37),
nn.Sigmoid())
def forward(self, x):
x = x.view(-1, 50 * 37)
x = self.encoder(x)
x = self.decoder(x)
return x.view(-1, 1, 50, 37)
model = Autoencoder()