-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_processing_module.py
61 lines (49 loc) · 1.89 KB
/
image_processing_module.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
from PIL import Image, ImageOps
import numpy as np
import os
def process_image(file_path, F, d):
try:
img = Image.open(file_path).convert('L')
except Exception as e:
print(f"Error in opening image: {e}")
return ""
gray_img = ImageOps.grayscale(img)
matrix = image_to_matrix(gray_img)
compressed_matrix = apply_dct_and_idct(matrix, F, d)
compressed_img = matrix_to_image(compressed_matrix)
compressed_file_path = "compressed_image.png"
compressed_img.save(compressed_file_path)
return compressed_file_path
def image_to_matrix(img):
return np.array(img, dtype=np.float32)
def matrix_to_image(matrix):
min_val, max_val = matrix.min(), matrix.max()
normalized_matrix = 255 * (matrix - min_val) / (max_val - min_val)
return Image.fromarray(np.uint8(normalized_matrix))
def apply_dct_and_idct(matrix, F, d):
from dct_module import dct2, idct2
height, width = matrix.shape
compressed_matrix = np.zeros_like(matrix)
for y in range(0, height, F):
for x in range(0, width, F):
if y + F <= height and x + F <= width:
block = matrix[y:y+F, x:x+F]
dct_block = dct2(block)
filtered_dct_block = filter_frequencies(dct_block, d)
idct_block = idct2(filtered_dct_block)
compressed_matrix[y:y+F, x:x+F] = idct_block
return compressed_matrix
def filter_frequencies(matrix, d):
size = matrix.shape[0]
for k in range(size):
for l in range(size):
if k + l >= d:
matrix[k, l] = 0
return matrix
def resize_image(image, max_width, max_height):
width, height = image.size
if width > max_width or height > max_height:
ratio = min(max_width / width, max_height / height)
new_size = (int(width * ratio), int(height * ratio))
image = image.resize(new_size)
return image