-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquantization.py
More file actions
40 lines (31 loc) · 933 Bytes
/
quantization.py
File metadata and controls
40 lines (31 loc) · 933 Bytes
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
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# Check if image is loaded
if img is None:
print("Error: Image not found. Make sure 'image.jpg' is in the same folder.")
exit()
# ----- Sampling -----
# Reduce image size (sampling)
sampled_img = cv2.resize(img, (128, 128), interpolation=cv2.INTER_NEAREST)
# ----- Quantization -----
levels = 16 # You can try: 2, 4, 8, 16, 32
quant_step = 256 // levels
quantized_img = (img // quant_step) * quant_step
# Display output
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
plt.title("Original Image")
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.title("Sampled Image (128x128)")
plt.imshow(sampled_img, cmap='gray')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.title(f"Quantized Image ({levels} levels)")
plt.imshow(quantized_img, cmap='gray')
plt.axis('off')
plt.show()