-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdct.py
More file actions
39 lines (28 loc) · 1022 Bytes
/
dct.py
File metadata and controls
39 lines (28 loc) · 1022 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
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread("image.jpg", 0)
img = np.float32(img)
h, w = img.shape
# Function for block-wise DCT compression
def dct_compress(img, thresh=20):
img_dct = np.zeros((h, w), np.float32)
for i in range(0, h, 8):
for j in range(0, w, 8):
block = img[i:i+8, j:j+8]
# Apply DCT
dct_block = cv2.dct(block)
# Thresholding small values (compression)
dct_block[np.abs(dct_block) < thresh] = 0
# Apply inverse DCT
idct_block = cv2.idct(dct_block)
img_dct[i:i+8, j:j+8] = idct_block
return img_dct
compressed_img = dct_compress(img, thresh=40)
compressed_img = np.uint8(compressed_img)
# Display
plt.figure(figsize=(10,5))
plt.subplot(1,2,1); plt.title("Original"); plt.imshow(img, cmap="gray"); plt.axis("off")
plt.subplot(1,2,2); plt.title("DCT Compressed"); plt.imshow(compressed_img, cmap="gray"); plt.axis("off")
plt.show()