""" Color Quantification Tool - Hugging Face Space Application Web interface for color analysis with download links to desktop version """ import gradio as gr import numpy as np from PIL import Image import matplotlib.pyplot as plt import pandas as pd import io from sklearn.cluster import KMeans class WebColorAnalyzer: def __init__(self): self.supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif'] def analyze_single_image(self, image, num_clusters=5): """Analyze a single image for web interface""" try: # Convert PIL image to numpy array if isinstance(image, Image.Image): img_array = np.array(image) else: img_array = image # Convert to RGB if needed if len(img_array.shape) == 3 and img_array.shape[2] == 3: img_rgb = img_array elif len(img_array.shape) == 3 and img_array.shape[2] == 4: img_rgb = img_array[:, :, :3] # Remove alpha channel else: return None, "Unsupported image format" # Reshape for clustering pixels = img_rgb.reshape(-1, 3) # Remove pure black pixels (background) mask = np.sum(pixels, axis=1) > 30 if np.sum(mask) < 100: # If too few pixels, use all mask = np.ones(len(pixels), dtype=bool) filtered_pixels = pixels[mask] # Perform K-means clustering kmeans = KMeans(n_clusters=min(num_clusters, len(filtered_pixels)), random_state=42, n_init=10) kmeans.fit(filtered_pixels) # Get dominant colors colors = kmeans.cluster_centers_.astype(int) labels = kmeans.labels_ # Calculate color percentages unique_labels, counts = np.unique(labels, return_counts=True) percentages = (counts / len(labels)) * 100 # Create results results = [] for i, (color, percentage) in enumerate(zip(colors, percentages)): results.append({ 'Color': f'Color {i+1}', 'RGB': f'({color[0]}, {color[1]}, {color[2]})', 'Hex': f'#{color[0]:02x}{color[1]:02x}{color[2]:02x}', 'Percentage': f'{percentage:.1f}%' }) return results, None except Exception as e: return None, f"Analysis error: {str(e)}" def create_color_palette_image(self, results): """Create a color palette visualization""" if not results: return None try: # Create figure fig, ax = plt.subplots(1, 1, figsize=(10, 2)) # Extract colors and percentages colors = [] percentages = [] for result in results: rgb_str = result['RGB'].strip('()') r, g, b = map(int, rgb_str.split(', ')) colors.append([r/255, g/255, b/255]) percentages.append(float(result['Percentage'].strip('%'))) # Create color bars left = 0 for i, (color, percentage) in enumerate(zip(colors, percentages)): width = percentage / 100 ax.barh(0, width, left=left, color=color, height=0.5) # Add percentage text if width > 0.1: # Only show text if bar is wide enough ax.text(left + width/2, 0, f'{percentage:.1f}%', ha='center', va='center', fontweight='bold') left += width ax.set_xlim(0, 1) ax.set_ylim(-0.3, 0.3) ax.set_xlabel('Color Distribution') ax.set_title('Dominant Colors Palette') ax.set_yticks([]) # Convert to image buf = io.BytesIO() plt.savefig(buf, format='png', bbox_inches='tight', dpi=150) buf.seek(0) plt.close() return Image.open(buf) except Exception as e: print(f"Error creating palette: {e}") return None def create_download_interface(): """Create the download and information interface""" download_html = """
Get the full-featured desktop application with advanced analysis capabilities!
File Size: 1.1GB | Platform: Windows 64-bit
Requirements: Windows 10/11, 8GB RAM