""" 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 = """

🖥️ Desktop Version Available

Get the full-featured desktop application with advanced analysis capabilities!

📥 Download Links

📁 GitHub Repository ⬇️ Download Desktop App

✨ Desktop Features

  • 🔬 Advanced multi-color space analysis (RGB, LAB, HSV)
  • 📊 Professional statistical analysis and reporting
  • 🎯 Batch processing of thousands of images
  • 📈 Interactive 3D visualizations and heatmaps
  • 💾 Export to Excel, CSV, JSON formats
  • 🔧 Configurable clustering parameters
  • ⚡ GPU-accelerated processing
  • 🔒 Complete offline operation

File Size: 1.1GB | Platform: Windows 64-bit
Requirements: Windows 10/11, 8GB RAM

""" return download_html def analyze_image_web(image, num_clusters): """Web interface analysis function""" if image is None: return None, "Please upload an image first.", None analyzer = WebColorAnalyzer() results, error = analyzer.analyze_single_image(image, num_clusters) if error: return None, error, None # Create DataFrame for display df = pd.DataFrame(results) # Create color palette visualization palette_img = analyzer.create_color_palette_image(results) return df, "✅ Analysis completed successfully!", palette_img def create_interface(): """Create the main Gradio interface""" with gr.Blocks( title="🎨 Color Quantification Tool", theme=gr.themes.Soft(), ) as demo: gr.Markdown(""" # 🎨 Color Quantification Tool **Professional Color Analysis Platform** - Web Demo Version This is a simplified web version for demonstration. For full functionality, download the desktop application below. """) # Download section gr.HTML(create_download_interface()) gr.Markdown("## 🌐 Try the Web Demo") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📤 Input") image_input = gr.Image( label="Upload Image", type="pil", height=300 ) num_clusters = gr.Slider( minimum=2, maximum=10, value=5, step=1, label="Number of Colors to Extract" ) analyze_btn = gr.Button( "🔍 Analyze Colors", variant="primary", size="lg" ) with gr.Column(scale=2): gr.Markdown("### 📊 Results") status_output = gr.Textbox( label="Status", interactive=False ) results_output = gr.Dataframe( label="Dominant Colors", headers=["Color", "RGB", "Hex", "Percentage"], interactive=False ) palette_output = gr.Image( label="Color Palette", height=150 ) # Event handlers analyze_btn.click( fn=analyze_image_web, inputs=[image_input, num_clusters], outputs=[results_output, status_output, palette_output] ) # Example section gr.Markdown(""" ## 📋 Usage Instructions 1. **Upload an image** using the file uploader 2. **Adjust the number of colors** to extract (2-10) 3. **Click "Analyze Colors"** to start the analysis 4. **View the results** in the table and color palette ### 🔬 What This Demo Shows - Basic color extraction using K-means clustering - Dominant color identification with percentages - Visual color palette representation ### 🚀 Desktop Version Features - **Multi-color space analysis** (RGB, LAB, HSV) - **Advanced distance metrics** (ΔE2000, Bhattacharyya) - **Batch processing** of multiple images - **Statistical analysis** and professional reporting - **3D visualizations** and interactive charts - **Export capabilities** (Excel, CSV, JSON) """) # Footer gr.Markdown(""" --- **🎯 Ready for Advanced Analysis?** Download the full desktop version for professional color quantification with advanced features! *Color Quantification Tool - Making color analysis accessible to everyone* """) return demo if __name__ == "__main__": # Create and launch the interface demo = create_interface() demo.launch()