kangxinyuan's picture
Create app.py
e735ed6 verified
"""
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 = """
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin: 10px 0;">
<h2 style="color: white; margin-bottom: 20px;">πŸ–₯️ Desktop Version Available</h2>
<p style="color: white; font-size: 16px; margin-bottom: 20px;">
Get the full-featured desktop application with advanced analysis capabilities!
</p>
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin: 15px 0;">
<h3 style="color: white; margin-bottom: 10px;">πŸ“₯ Download Links</h3>
<div style="display: flex; justify-content: center; gap: 15px; flex-wrap: wrap;">
<a href="https://github.com/your-username/ColorQuantificationTool"
style="background: #4285f4; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
πŸ“ GitHub Repository
</a>
<a href="https://github.com/your-username/ColorQuantificationTool/releases"
style="background: #0078d4; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
⬇️ Download Desktop App
</a>
</div>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin: 15px 0;">
<h3 style="color: white; margin-bottom: 10px;">✨ Desktop Features</h3>
<div style="text-align: left; color: white;">
<ul style="list-style: none; padding: 0;">
<li>πŸ”¬ Advanced multi-color space analysis (RGB, LAB, HSV)</li>
<li>πŸ“Š Professional statistical analysis and reporting</li>
<li>🎯 Batch processing of thousands of images</li>
<li>πŸ“ˆ Interactive 3D visualizations and heatmaps</li>
<li>πŸ’Ύ Export to Excel, CSV, JSON formats</li>
<li>πŸ”§ Configurable clustering parameters</li>
<li>⚑ GPU-accelerated processing</li>
<li>πŸ”’ Complete offline operation</li>
</ul>
</div>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
<p style="color: white; margin: 0;">
<strong>File Size:</strong> 1.1GB | <strong>Platform:</strong> Windows 64-bit<br>
<strong>Requirements:</strong> Windows 10/11, 8GB RAM
</p>
</div>
</div>
"""
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()