-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
73 lines (56 loc) · 2.25 KB
/
app.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
import cv2
import numpy as np
def calculate_mse(img1, img2):
"""
Calculates the Mean Squared Error (MSE) between two images.
Parameters:
img1 (numpy.ndarray): The first image represented as a 2D NumPy array.
img2 (numpy.ndarray): The second image represented as a 2D NumPy array.
Returns:
float: The Mean Squared Error (MSE) between the two images.
"""
return np.mean((img1 - img2) ** 2)
def calculate_psnr(img1, img2):
"""
Calculates the Peak Signal-to-Noise Ratio (PSNR) between two images.
Parameters:
img1 (numpy.ndarray): The first image represented as a 2D NumPy array.
img2 (numpy.ndarray): The second image represented as a 2D NumPy array.
Returns:
float: The PSNR value between the two images. If the Mean Squared Error (MSE) is zero,
the function returns infinity (float('inf')).
"""
mse = calculate_mse(img1, img2)
if mse == 0:
return float('inf')
max_pixel = 255.0
return 20 * np.log10(max_pixel / np.sqrt(mse))
def compress_image(image_path, quality=90):
"""
Compresses an image using JPEG compression.
This function reads an image from the specified path, compresses it using JPEG compression,
and then decodes the compressed image back to its original format.
Parameters:
image_path (str): The path to the image file to be compressed.
quality (int, optional): The quality of the compressed image. The value should be between 0 and 100.
Default is 90.
Returns:
numpy.ndarray: The decoded compressed image represented as a 2D NumPy array.
"""
# Read the image
img = cv2.imread(image_path)
# Encode the image with JPEG compression
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
_, encoded_img = cv2.imencode('.jpg', img, encode_param)
# Decode the compressed image
decoded_img = cv2.imdecode(encoded_img, cv2.IMREAD_COLOR)
return decoded_img
# Read the original image
original_img = cv2.imread('sampleimage.jpg')
# Compress the image with 50% quality
compressed_img = compress_image('sampleimage.jpg', quality=50)
# Display results
cv2.imshow('Original', original_img)
cv2.imshow('Compressed', compressed_img)
cv2.waitKey(0)
cv2.destroyAllWindows()