0% found this document useful (0 votes)
5 views

Code Snip

This document contains Python code for a color analyzer GUI built with Streamlit. It allows a user to upload an image, select the number of color clusters, and run K-Means clustering on the image pixels. It then displays statistics on the clustered colors such as a pie chart of the color distribution, bar chart of color counts, and scatter plot of colors. It also shows the clustered image side by side with the original and allows copying hex codes to the clipboard.

Uploaded by

shrutisuman03
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Code Snip

This document contains Python code for a color analyzer GUI built with Streamlit. It allows a user to upload an image, select the number of color clusters, and run K-Means clustering on the image pixels. It then displays statistics on the clustered colors such as a pie chart of the color distribution, bar chart of color counts, and scatter plot of colors. It also shows the clustered image side by side with the original and allows copying hex codes to the clipboard.

Uploaded by

shrutisuman03
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

import streamlit as st

from PIL import ImageTk, Image


from sklearn.cluster import KMeans
import numpy as np
import clipboard
import matplotlib.pyplot as plt

def copy_hex_code(hex_code):
st.write(hex_code)
st.experimental_set_query_params(hex_code=hex_code)

def main():
st.set_page_config(page_title="Color Analyser GUI", page_icon=":eyeglasses:",
layout="wide")
st.title("Color Analyzer")
st.sidebar.title("Settings")

# Create file uploader


uploaded_file = st.sidebar.file_uploader("Select an image")

# Create number of clusters input


n_clusters = st.sidebar.number_input("Number of clusters", min_value=1,
value=3)

# Create run button


run_button = st.sidebar.button("Run Clustering")

# Display selected image and clustered image side by side


col1, col2 = st.columns(2)
if uploaded_file is not None:
image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image = image.resize((new_width, new_height))
col1.image(image, caption="Uploaded Image", use_column_width=True)

if run_button:
if uploaded_file is None:
st.error("Please select an image")
return

# Load image and convert to numpy array


image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image_array = np.array(image.resize((new_width, new_height)))

# Reshape the array to a 2D matrix of pixels


width, height, depth = image_array.shape
pixel_matrix = image_array.reshape(width * height, depth)

# Run KMeans algorithm


kmeans = KMeans(n_clusters=n_clusters)
kmeans.fit(pixel_matrix)
# Replace each pixel with its corresponding cluster center
new_image_array = np.zeros_like(pixel_matrix)
hex_codes = []
for i, cluster_label in enumerate(kmeans.labels_):
new_image_array[i] = kmeans.cluster_centers_[cluster_label]
hex_code = "#%02x%02x%02x" % tuple(map(int,
kmeans.cluster_centers_[cluster_label]))
if hex_code not in hex_codes:
hex_codes.append(hex_code)

# Create a new image with the computed colors


new_image_array = new_image_array.reshape(width, height, depth)
new_image = Image.fromarray(np.uint8(new_image_array))
new_image = new_image.resize((new_width, new_height))
col2.image(new_image, caption=f"{n_clusters} Cluster(s)",
use_column_width=True)

# Display hex codes and colors


st.write("Colors:")
for i, hex_code in enumerate(hex_codes):
col1, col2 = st.columns([1, 10])
with col1:
color_image = Image.new("RGB", (50, 50), hex_code)
color_image = color_image.resize((30, 30))
st.image(color_image, use_column_width=True)
with col2:
st.write(hex_code)
copy_button = st.button("Copy", key=hex_code)
if copy_button:
copy_hex_code(hex_code)

if __name__ == "__main__":
main()
import streamlit as st
from PIL import Image
from sklearn.cluster import KMeans
import numpy as np
import clipboard
import matplotlib.pyplot as plt

def copy_hex_code(hex_code):
st.write(f"Copied {hex_code} to clipboard")
clipboard.copy(hex_code)

def main():
st.set_page_config(page_title="Color Analyser GUI", page_icon=":eyeglasses:",
layout="wide")
st.title("Color Analyzer")
st.sidebar.title("Settings")

# Create file uploader


uploaded_file = st.sidebar.file_uploader("Select an image")

# Create number of clusters input


n_clusters = st.sidebar.number_input("Number of clusters", min_value=1,
value=3)

# Create run button


run_button = st.sidebar.button("Run Clustering")

# Display selected image


if uploaded_file is not None:
image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image = image.resize((new_width, new_height))
st.image(image, caption="Uploaded Image", use_column_width=True)

# Run clustering algorithm


if run_button:
if uploaded_file is None:
st.error("Please select an image")
return

# Load image and convert to numpy array


image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image_array = np.array(image.resize((new_width, new_height)))

# Reshape the array to a 2D matrix of pixels


width, height, depth = image_array.shape
pixel_matrix = image_array.reshape(width * height, depth)

# Run KMeans algorithm


kmeans = KMeans(n_clusters=n_clusters)
kmeans.fit(pixel_matrix)

# Replace each pixel with its corresponding cluster center


new_image_array = np.zeros_like(pixel_matrix)
hex_codes = []
color_counts = []
for i, cluster_label in enumerate(kmeans.labels_):
new_image_array[i] = kmeans.cluster_centers_[cluster_label]
hex_code = "#%02x%02x%02x" % tuple(map(int,
kmeans.cluster_centers_[cluster_label]))
if hex_code not in hex_codes:
hex_codes.append(hex_code)
color_counts.append(1)
else:
index = hex_codes.index(hex_code)
color_counts[index] += 1

# Create a new image with the computed colors


new_image_array = new_image_array.reshape(width, height, depth)
image = Image.fromarray(np.uint8(new_image_array))
image = image.resize((new_width, new_height))
st.image(image, caption=f"{n_clusters} Cluster(s)", use_column_width=True)

# Display hex codes and colors


st.write("Colors:")

# Display hex codes and colors


st.write("Colors:")
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
colors = []
labels = []
sizes = []
for i, hex_code in enumerate(hex_codes):
colors.append(hex_code)
labels.append(hex_code)
sizes.append(color_counts[i])
col1, col2, col3 = st.columns([1, 4, 3])
with col1:
color_image = Image.new("RGB", (50, 50), hex_code)
color_image = color_image.resize((60, 30))
st.image(color_image)
with col2:
st.write(hex_code)
with col3:
st.write(f"Count: {color_counts[i]}")

# Display pie chart of color distribution


fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
st.write("Color Distribution:")
st.pyplot(fig)

# Create bar chart of color counts


fig, ax = plt.subplots()
ax.bar(hex_codes, color_counts, color=hex_codes)
plt.xticks(rotation=45)
plt.xlabel('Hex Codes')
plt.ylabel('Count')
plt.title('Color Counts')
st.write("Color Counts:")
st.pyplot(fig)

# Create scatter plot of colors


fig, ax = plt.subplots()
ax.scatter([i for i in range(len(hex_codes))], color_counts,
color=hex_codes)
plt.xticks([i for i in range(len(hex_codes))], hex_codes, rotation=45)
plt.xlabel('Hex Codes')
plt.ylabel('Count')
plt.title('Color Scatter Plot')
st.write("Color Scatter Plot:")
st.pyplot(fig)

if __name__ == "__main__":
main()

import streamlit as st
from PIL import Image
from sklearn.cluster import KMeans
import numpy as np
import clipboard
import matplotlib.pyplot as plt

def copy_hex_code(hex_code):
st.write(f"Copied {hex_code} to clipboard")
clipboard.copy(hex_code)

def main():
st.set_page_config(page_title="Color Analyser GUI", page_icon=":eyeglasses:",
layout="wide")
st.title("Color Analyzer")
st.sidebar.title("Settings")

# Create file uploader


uploaded_file = st.sidebar.file_uploader("Select an image")

# Create number of clusters input


n_clusters = st.sidebar.number_input("Number of clusters", min_value=1,
value=3)

# Create run button


run_button = st.sidebar.button("Run Clustering")

# Display selected image


if uploaded_file is not None:
image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image = image.resize((new_width, new_height))
st.image(image, caption="Uploaded Image", use_column_width=True)

# Run clustering algorithm


if run_button:
if uploaded_file is None:
st.error("Please select an image")
return

# Load image and convert to numpy array


image = Image.open(uploaded_file)
orig_width, orig_height = image.size
new_height = 300
new_width = int(orig_width / orig_height * new_height)
image_array = np.array(image.resize((new_width, new_height)))

# Reshape the array to a 2D matrix of pixels


width, height, depth = image_array.shape
pixel_matrix = image_array.reshape(width * height, depth)

# Run KMeans algorithm


kmeans = KMeans(n_clusters=n_clusters)
kmeans.fit(pixel_matrix)

# Replace each pixel with its corresponding cluster center


new_image_array = np.zeros_like(pixel_matrix)
hex_codes = []
color_counts = []
for i, cluster_label in enumerate(kmeans.labels_):
new_image_array[i] = kmeans.cluster_centers_[cluster_label]
hex_code = "#%02x%02x%02x" % tuple(map(int,
kmeans.cluster_centers_[cluster_label]))
if hex_code not in hex_codes:
hex_codes.append(hex_code)
color_counts.append(1)
else:
index = hex_codes.index(hex_code)
color_counts[index] += 1

# Create a new image with the computed colors


new_image_array = new_image_array.reshape(width, height, depth)
image = Image.fromarray(np.uint8(new_image_array))
image = image.resize((new_width, new_height))
st.image(image, caption=f"{n_clusters} Cluster(s)", use_column_width=True)

# Display hex codes and colors


st.write("Colors:")

# Display hex codes and colors


st.write("Colors:")
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
colors = []
labels = []
sizes = []
for i, hex_code in enumerate(hex_codes):
colors.append(hex_code)
labels.append(hex_code)
sizes.append(color_counts[i])
col1, col2, col3 = st.columns([1, 4, 3])
with col1:
color_image = Image.new("RGB", (50, 50), hex_code)
color_image = color_image.resize((60, 30))
st.image(color_image)
with col2:
st.write(hex_code)
with col3:
st.write(f"Count: {color_counts[i]}")

# Display pie chart of color distribution


fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
st.write("Color Distribution:")
st.pyplot(fig)

# Create bar chart of color counts


fig, ax = plt.subplots()
ax.bar(hex_codes, color_counts, color=hex_codes)
plt.xticks(rotation=45)
plt.xlabel('Hex Codes')
plt.ylabel('Count')
plt.title('Color Counts')
st.write("Color Counts:")
st.pyplot(fig)

# Create scatter plot of colors


fig, ax = plt.subplots()
ax.scatter([i for i in range(len(hex_codes))], color_counts,
color=hex_codes)
plt.xticks([i for i in range(len(hex_codes))], hex_codes, rotation=45)
plt.xlabel('Hex Codes')
plt.ylabel('Count')
plt.title('Color Scatter Plot')
st.write("Color Scatter Plot:")
st.pyplot(fig)

if __name__ == "__main__":
main()

You might also like