import cv2 import numpy as np from matplotlib import pyplot as plt Reading image I =…
- User
import cv2 import numpy as np from matplotlib import pyplot as plt
Reading image
I = cv2.imread('image.tif', cv2.IMREAD_GRAYSCALE) / 255.0
Motion Blur the image and adding Gaussian noise
kernel_motion = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]], dtype=np.float32) / 5 # Kernel for motion blur blurred = cv2.filter2D(I, -1, kernel_motion, borderType=cv2.BORDER_CONSTANT) blurred_with_noise = blurred + 0.01 * np.random.randn(*blurred.shape) # Add Gaussian noise
Taking Fourier transform of the Blurred Image
G = np.fft.fftshift(np.fft.fft2(blurred_with_noise))
Estimate and display the Gaussian lowpass filter h
h = cv2.getGaussianKernel(5, 2) @ cv2.getGaussianKernel(5, 2).T H = np.fft.fftshift(np.fft.fft2(h, G.shape))
Deconvolution in frequency domain with limited radius R
R = 20 F = np.zeros_like(G, dtype=complex) rows, cols = G.shape for u in range(cols): for v in range(rows): if (u - cols // 2)**2 + (v - rows // 2)2 <= R2: F[v, u] = G[v, u] / H[v, u] if H[v, u] != 0 else 0
Convert back to spatial domain
fRestored = np.real(np.fft.ifft2(np.fft.ifftshift(F)))
Displaying all figures including original image in a grid
fig, axs = plt.subplots(2, 4, figsize=(18, 8))
axs[0, 0].imshow(I, cmap='gray') axs[0, 0].set_title('Original Image')
axs[0, 1].imshow(blurred_with_noise, cmap='gray') axs[0, 1].set_title('Motion Blurred Image with Gaussian Noise')
axs[0, 2].imshow(np.log(np.abs(G)), cmap='gray') axs[0, 2].set_title('Fourier Transform of Blurred Image')
axs[0, 3].imshow(h, cmap='gray') axs[0, 3].set_title('Estimated h = Lowpass Gaussian filter')
axs[1, 0].imshow(np.log(np.abs(H)), cmap='gray') axs[1, 0].set_title('Fourier Transform of Estimated h')
axs[1, 1].imshow(np.log(np.abs(F)), cmap='gray') axs[1, 1].set_title('Intermediate Result in Frequency Domain')
axs[1, 2].imshow(fRestored, cmap='gray') axs[1, 2].set_title('Restored Image')
for ax in axs.flat: ax.axis('off')
plt.tight_layout() plt.show() Explain this code
- Assistant
This code performs image restoration using motion blur and Gaussian noise. Here is a step-by-step explanation of the code:
-
The code reads an image named "image.tif" in grayscale format and normalizes it to values between 0 and 1.
-
It then applies motion blur to the image using a 5x5 kernel with equal weights.
-
Gaussian noise is added to the motion blurred image.
-
The Fourier transform of the blurred image with noise is computed and the result is shifted to center the low frequencies.
-
An estimate of the Gaussian lowpass filter 'h' is created using two 5x5 Gaussian kernels. The Fourier transform of 'h' is also shifted.
-