Spaces:
Sleeping
Sleeping
File size: 2,579 Bytes
fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 f3985ab fe26723 |
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 |
# Importing the Gradio library for creating interactive web interfaces
import gradio as gr
# Importing necessary libraries for image processing
import numpy as np
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
# Function to perform k-means color quantization on an image
def knn_color_quantization(image, n_colors):
# Reshaping the image into a 2D array of pixels
pixels = np.reshape(image, (image.shape[0] * image.shape[1], image.shape[2]))
# Performing k-means clustering to find the dominant colors
kmeans = KMeans(n_clusters=n_colors, random_state=42)
kmeans.fit(pixels)
# Getting the cluster centers as the representative colors
kmeans_centers = kmeans.cluster_centers_
# Fitting a nearest neighbors model to find the closest color for each pixel
knn = NearestNeighbors(n_neighbors=1)
knn.fit(kmeans_centers)
# Finding the closest color for each pixel and reconstructing the quantized image
distances, indices = knn.kneighbors(pixels)
quantized_pixels = kmeans_centers[indices.flatten()]
quantized_image = np.reshape(quantized_pixels, image.shape)
# Scaling the image values to the range [0, 1]
quantized_image = quantized_image / 255.0
return quantized_image
# Function to create the Gradio interface for color quantization
def color_quantization_app(image, num_colors):
# Calling the knn_color_quantization function to quantize the image
quantized_image = knn_color_quantization(image, num_colors)
# Converting the pixel values back to the range [0, 255] and casting to uint8
quantized_image = (quantized_image * 255).astype(np.uint8)
return quantized_image
# Creating a Gradio interface object
iface = gr.Interface(
# Specifying the function to be executed
fn=color_quantization_app,
# Defining the inputs for the interface (an uploaded image and a slider for number of colors)
inputs=[gr.Image(label="Uploaded Image", sources='upload', type="numpy"), gr.Slider(minimum=2,maximum=300,value=8, label='Number of Colors',interactive=True)],
# Defining the output for the interface (quantized image)
outputs=gr.Image(label="Quantized Image"),
# Disabling live updates
live=False,
# Disabling user flagging of outputs
allow_flagging="never",
# Applying a custom theme retrieved from Gradio Hub
theme=dark_minimalist,
# Adding custom CSS to hide the footer of the interface
css="""
footer {
visibility: hidden;
}
"""
)
# Launching the Gradio interface
iface.launch()
|