-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdenoise.py
More file actions
52 lines (40 loc) · 1.33 KB
/
denoise.py
File metadata and controls
52 lines (40 loc) · 1.33 KB
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
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read grayscale image
img = cv2.imread('image2.jpg', 0)
img = img.astype(np.float32)
# Padding for 3x3 kernel
padded = np.pad(img, 1, mode='reflect')
# Define output images
arithmetic = np.zeros_like(img)
geometric = np.zeros_like(img)
harmonic = np.zeros_like(img)
contra = np.zeros_like(img)
Q = 1.5 # Remove pepper noise
# Apply 3x3 neighborhood filters
for i in range(1, padded.shape[0] - 1):
for j in range(1, padded.shape[1] - 1):
window = padded[i-1:i+2, j-1:j+2]
# Arithmetic Mean
arithmetic[i-1, j-1] = np.mean(window)
# Geometric Mean
geometric[i-1, j-1] = np.exp(np.mean(np.log(window + 1e-8)))
# Harmonic Mean
harmonic[i-1, j-1] = 9 / np.sum(1.0 / (window + 1e-8))
# Contra-harmonic Mean
numerator = np.sum(window ** (Q + 1))
denominator = np.sum(window ** Q + 1e-8)
contra[i-1, j-1] = numerator / denominator
# Display results
titles = ["Original", "Arithmetic Mean", "Geometric Mean",
"Harmonic Mean", "Contra-Harmonic Mean"]
images = [img, arithmetic, geometric, harmonic, contra]
plt.figure(figsize=(14, 10))
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(images[i], cmap="gray")
plt.title(titles[i])
plt.axis("off")
plt.tight_layout()
plt.show()