Spaces:
Sleeping
Sleeping
DexterSptizu
commited on
Commit
•
e53f98a
1
Parent(s):
d2dca54
Upload pca_image_compression.py
Browse files- pca_image_compression.py +49 -0
pca_image_compression.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import numpy as np
|
3 |
+
from sklearn.decomposition import PCA
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
# Add a file uploader to allow image uploads
|
7 |
+
uploaded_file = st.file_uploader("Choose an image...", type=['jpg', 'jpeg', 'png'])
|
8 |
+
|
9 |
+
def process_display_image(uploaded_file):
|
10 |
+
# Load the image and convert it to grayscale
|
11 |
+
original_img = Image.open(uploaded_file).convert('L')
|
12 |
+
img_array = np.array(original_img)
|
13 |
+
|
14 |
+
# Number of components in the original image
|
15 |
+
original_components = img_array.shape[1]
|
16 |
+
|
17 |
+
# Number of components to keep for PCA
|
18 |
+
n_components = 20 # Set an initial value for the slider
|
19 |
+
n_components = st.sidebar.slider('Number of PCA Components', 1, original_components, n_components)
|
20 |
+
|
21 |
+
# Initialize PCA and apply it to the image data
|
22 |
+
pca = PCA(n_components=n_components)
|
23 |
+
pca.fit(img_array)
|
24 |
+
img_transformed = pca.transform(img_array)
|
25 |
+
|
26 |
+
# Inverse transform to reconstruct the image
|
27 |
+
img_reconstructed = pca.inverse_transform(img_transformed)
|
28 |
+
|
29 |
+
# Normalize the pixel values to be in the range [0, 255]
|
30 |
+
img_reconstructed = np.clip(img_reconstructed, 0, 255) # Ensures values are within [0, 255]
|
31 |
+
img_reconstructed = img_reconstructed.astype(np.uint8) # Converts the values to uint8
|
32 |
+
|
33 |
+
# Number of components in the processed image
|
34 |
+
processed_components = pca.n_components_
|
35 |
+
|
36 |
+
# Display the original and the reconstructed images
|
37 |
+
col1, col2 = st.columns(2)
|
38 |
+
|
39 |
+
with col1:
|
40 |
+
st.image(img_array, caption=f'Original Image\n{original_components} components', use_column_width=True)
|
41 |
+
|
42 |
+
with col2:
|
43 |
+
st.image(img_reconstructed, caption=f'Reconstructed Image\n{processed_components} components', use_column_width=True)
|
44 |
+
|
45 |
+
# Check if an image was uploaded before processing it
|
46 |
+
if uploaded_file is not None:
|
47 |
+
process_display_image(uploaded_file)
|
48 |
+
else:
|
49 |
+
st.write("Please upload an image to process.")
|