Srikanthgoud7 commited on
Commit
abe3536
·
verified ·
1 Parent(s): 9a4f5dc

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from sklearn.cluster import KMeans
6
+ import matplotlib.ticker as ticker
7
+ from io import BytesIO
8
+ from PIL import Image
9
+
10
+ # -----------------------------
11
+ # Streamlit App
12
+ # -----------------------------
13
+ st.title("🖼️ Image Segmentation using K-Means Clustering")
14
+
15
+ # Sidebar options
16
+ st.sidebar.header("Controls")
17
+ uploaded_file = st.sidebar.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
18
+ max_k = st.sidebar.slider("Max K for Elbow Curve", 5, 15, 10)
19
+ chosen_k = st.sidebar.slider("Choose K (Clusters)", 2, 10, 4)
20
+
21
+ if uploaded_file is not None:
22
+ # -----------------------------
23
+ # Step 1: Load Image
24
+ # -----------------------------
25
+ image = Image.open(uploaded_file)
26
+ image = np.array(image)
27
+
28
+ st.subheader("Original Image")
29
+ st.image(image, use_container_width=True)
30
+
31
+ # -----------------------------
32
+ # Step 2: Preprocess Image
33
+ # -----------------------------
34
+ pixels = image.reshape((-1, 3))
35
+ pixels = np.float32(pixels)
36
+
37
+ # -----------------------------
38
+ # Step 3: Elbow Curve
39
+ # -----------------------------
40
+ wcss = []
41
+ K = range(1, max_k+1)
42
+ for k in K:
43
+ kmeans = KMeans(n_clusters=k, random_state=42)
44
+ kmeans.fit(pixels)
45
+ wcss.append(kmeans.inertia_)
46
+
47
+ # Plot elbow curve
48
+ fig, ax = plt.subplots(figsize=(6, 4))
49
+ ax.plot(K, wcss, 'bo-')
50
+ ax.set_xlabel("Number of clusters (k)")
51
+ ax.set_ylabel("WCSS (Inertia)")
52
+ ax.set_title("Elbow Curve")
53
+
54
+ # Format y-axis in millions
55
+ ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f'{int(x/1e6)}M'))
56
+
57
+ # Add vertical dotted line for chosen k
58
+ ax.axvline(x=chosen_k, color='r', linestyle='--', label=f'k={chosen_k}')
59
+ ax.legend()
60
+
61
+ st.subheader("Elbow Curve")
62
+ st.pyplot(fig)
63
+
64
+ # -----------------------------
65
+ # Step 4: Apply KMeans with chosen k
66
+ # -----------------------------
67
+ kmeans = KMeans(n_clusters=chosen_k, random_state=42)
68
+ labels = kmeans.fit_predict(pixels)
69
+
70
+ segmented_img = kmeans.cluster_centers_[labels]
71
+ segmented_img = segmented_img.reshape(image.shape)
72
+ segmented_img = np.uint8(segmented_img)
73
+
74
+ # -----------------------------
75
+ # Step 5: Show Results
76
+ # -----------------------------
77
+ st.subheader(f"Segmented Image (k={chosen_k})")
78
+ st.image(segmented_img, use_container_width=True)
79
+
80
+ else:
81
+ st.info("👈 Upload an image from the sidebar to start.")