-
Notifications
You must be signed in to change notification settings - Fork 33
/
anannya.py
76 lines (60 loc) · 2.09 KB
/
anannya.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import cv2
import numpy as np
from numpy.fft import fft2, ifft2
from scipy.signal import gaussian, convolve2d
import matplotlib.pyplot as plt
def blur(img, mode = 'box', kernel_size = 3):
# mode = 'box' or 'gaussian' or 'motion'
dummy = np.copy(img)
if mode == 'box':
h = np.ones((kernel_size, kernel_size)) / kernel_size ** 2
elif mode == 'gaussian':
h = gaussian(kernel_size, kernel_size / 3).reshape(kernel_size, 1)
h = np.dot(h, h.transpose())
h /= np.sum(h)
elif mode == 'motion':
h = np.eye(kernel_size) / kernel_size
dummy = convolve2d(dummy, h, mode = 'valid')
return dummy
def add_gaussian_noise(img, sigma):
gauss = np.random.normal(0, sigma, np.shape(img))
noisy_img = img + gauss
noisy_img[noisy_img < 0] = 0
noisy_img[noisy_img > 255] = 255
return noisy_img
def wiener_filter(img, kernel, K):
kernel /= np.sum(kernel)
dummy = np.copy(img)
dummy = fft2(dummy)
kernel = fft2(kernel, s = img.shape)
kernel = np.conj(kernel) / (np.abs(kernel) ** 2 + K)
dummy = dummy * kernel
dummy = np.abs(ifft2(dummy))
return dummy
def gaussian_kernel(kernel_size = 3):
h = gaussian(kernel_size, kernel_size / 3).reshape(kernel_size, 1)
h = np.dot(h, h.transpose())
h /= np.sum(h)
return h
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
#img = rgb2gray(plt.imread('original.jpg' ))
img = cv2.imread('original.jpg', cv2.IMREAD_GRAYSCALE)
cv2.waitKey(1)
cv2.imshow(img)
'''
blurred_img = blur(img, mode = 'motion', kernel_size = 3)
noisy_img = add_gaussian_noise(blurred_img, sigma = 20)
kernel = gaussian_kernel(3)
filtered_img = wiener_filter(noisy_img, kernel, K = 10)
cv2.imwrite("mb_filtered.jpg", filtered_img)
display = [img, blurred_img, noisy_img, filtered_img]
label = ['Original Image', 'Motion Blurred Image', 'Motion Blurring + Gaussian Noise', 'Wiener Filter applied']
fig = plt.figure(figsize=(12, 10))
for i in range(len(display)):
fig.add_subplot(2, 2, i+1)
plt.imshow(display[i], cmap = 'gray')
plt.title(label[i])
plt.show()
'''