|
import streamlit as st
|
|
import numpy as np
|
|
from sklearn.decomposition import PCA
|
|
from PIL import Image
|
|
|
|
|
|
uploaded_file = st.file_uploader("Choose an image...", type=['jpg', 'jpeg', 'png'])
|
|
|
|
def process_display_image(uploaded_file):
|
|
|
|
original_img = Image.open(uploaded_file).convert('L')
|
|
img_array = np.array(original_img)
|
|
|
|
|
|
original_components = img_array.shape[1]
|
|
|
|
|
|
n_components = 20
|
|
n_components = st.sidebar.slider('Number of PCA Components', 1, original_components, n_components)
|
|
|
|
|
|
pca = PCA(n_components=n_components)
|
|
pca.fit(img_array)
|
|
img_transformed = pca.transform(img_array)
|
|
|
|
|
|
img_reconstructed = pca.inverse_transform(img_transformed)
|
|
|
|
|
|
img_reconstructed = np.clip(img_reconstructed, 0, 255)
|
|
img_reconstructed = img_reconstructed.astype(np.uint8)
|
|
|
|
|
|
processed_components = pca.n_components_
|
|
|
|
|
|
col1, col2 = st.columns(2)
|
|
|
|
with col1:
|
|
st.image(img_array, caption=f'Original Image\n{original_components} components', use_column_width=True)
|
|
|
|
with col2:
|
|
st.image(img_reconstructed, caption=f'Reconstructed Image\n{processed_components} components', use_column_width=True)
|
|
|
|
|
|
if uploaded_file is not None:
|
|
process_display_image(uploaded_file)
|
|
else:
|
|
st.write("Please upload an image to process.")
|
|
|