kangxinyuan commited on
Commit
e735ed6
Β·
verified Β·
1 Parent(s): fdc5de6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -0
app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Color Quantification Tool - Hugging Face Space Application
3
+ Web interface for color analysis with download links to desktop version
4
+ """
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ from PIL import Image
9
+ import matplotlib.pyplot as plt
10
+ import pandas as pd
11
+ import io
12
+ from sklearn.cluster import KMeans
13
+
14
+ class WebColorAnalyzer:
15
+ def __init__(self):
16
+ self.supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif']
17
+
18
+ def analyze_single_image(self, image, num_clusters=5):
19
+ """Analyze a single image for web interface"""
20
+ try:
21
+ # Convert PIL image to numpy array
22
+ if isinstance(image, Image.Image):
23
+ img_array = np.array(image)
24
+ else:
25
+ img_array = image
26
+
27
+ # Convert to RGB if needed
28
+ if len(img_array.shape) == 3 and img_array.shape[2] == 3:
29
+ img_rgb = img_array
30
+ elif len(img_array.shape) == 3 and img_array.shape[2] == 4:
31
+ img_rgb = img_array[:, :, :3] # Remove alpha channel
32
+ else:
33
+ return None, "Unsupported image format"
34
+
35
+ # Reshape for clustering
36
+ pixels = img_rgb.reshape(-1, 3)
37
+
38
+ # Remove pure black pixels (background)
39
+ mask = np.sum(pixels, axis=1) > 30
40
+ if np.sum(mask) < 100: # If too few pixels, use all
41
+ mask = np.ones(len(pixels), dtype=bool)
42
+
43
+ filtered_pixels = pixels[mask]
44
+
45
+ # Perform K-means clustering
46
+ kmeans = KMeans(n_clusters=min(num_clusters, len(filtered_pixels)),
47
+ random_state=42, n_init=10)
48
+ kmeans.fit(filtered_pixels)
49
+
50
+ # Get dominant colors
51
+ colors = kmeans.cluster_centers_.astype(int)
52
+ labels = kmeans.labels_
53
+
54
+ # Calculate color percentages
55
+ unique_labels, counts = np.unique(labels, return_counts=True)
56
+ percentages = (counts / len(labels)) * 100
57
+
58
+ # Create results
59
+ results = []
60
+ for i, (color, percentage) in enumerate(zip(colors, percentages)):
61
+ results.append({
62
+ 'Color': f'Color {i+1}',
63
+ 'RGB': f'({color[0]}, {color[1]}, {color[2]})',
64
+ 'Hex': f'#{color[0]:02x}{color[1]:02x}{color[2]:02x}',
65
+ 'Percentage': f'{percentage:.1f}%'
66
+ })
67
+
68
+ return results, None
69
+
70
+ except Exception as e:
71
+ return None, f"Analysis error: {str(e)}"
72
+
73
+ def create_color_palette_image(self, results):
74
+ """Create a color palette visualization"""
75
+ if not results:
76
+ return None
77
+
78
+ try:
79
+ # Create figure
80
+ fig, ax = plt.subplots(1, 1, figsize=(10, 2))
81
+
82
+ # Extract colors and percentages
83
+ colors = []
84
+ percentages = []
85
+ for result in results:
86
+ rgb_str = result['RGB'].strip('()')
87
+ r, g, b = map(int, rgb_str.split(', '))
88
+ colors.append([r/255, g/255, b/255])
89
+ percentages.append(float(result['Percentage'].strip('%')))
90
+
91
+ # Create color bars
92
+ left = 0
93
+ for i, (color, percentage) in enumerate(zip(colors, percentages)):
94
+ width = percentage / 100
95
+ ax.barh(0, width, left=left, color=color, height=0.5)
96
+
97
+ # Add percentage text
98
+ if width > 0.1: # Only show text if bar is wide enough
99
+ ax.text(left + width/2, 0, f'{percentage:.1f}%',
100
+ ha='center', va='center', fontweight='bold')
101
+
102
+ left += width
103
+
104
+ ax.set_xlim(0, 1)
105
+ ax.set_ylim(-0.3, 0.3)
106
+ ax.set_xlabel('Color Distribution')
107
+ ax.set_title('Dominant Colors Palette')
108
+ ax.set_yticks([])
109
+
110
+ # Convert to image
111
+ buf = io.BytesIO()
112
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=150)
113
+ buf.seek(0)
114
+ plt.close()
115
+
116
+ return Image.open(buf)
117
+
118
+ except Exception as e:
119
+ print(f"Error creating palette: {e}")
120
+ return None
121
+
122
+ def create_download_interface():
123
+ """Create the download and information interface"""
124
+
125
+ download_html = """
126
+ <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin: 10px 0;">
127
+ <h2 style="color: white; margin-bottom: 20px;">πŸ–₯️ Desktop Version Available</h2>
128
+ <p style="color: white; font-size: 16px; margin-bottom: 20px;">
129
+ Get the full-featured desktop application with advanced analysis capabilities!
130
+ </p>
131
+
132
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin: 15px 0;">
133
+ <h3 style="color: white; margin-bottom: 10px;">πŸ“₯ Download Links</h3>
134
+ <div style="display: flex; justify-content: center; gap: 15px; flex-wrap: wrap;">
135
+ <a href="https://github.com/your-username/ColorQuantificationTool"
136
+ style="background: #4285f4; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
137
+ πŸ“ GitHub Repository
138
+ </a>
139
+ <a href="https://github.com/your-username/ColorQuantificationTool/releases"
140
+ style="background: #0078d4; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;">
141
+ ⬇️ Download Desktop App
142
+ </a>
143
+ </div>
144
+ </div>
145
+
146
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin: 15px 0;">
147
+ <h3 style="color: white; margin-bottom: 10px;">✨ Desktop Features</h3>
148
+ <div style="text-align: left; color: white;">
149
+ <ul style="list-style: none; padding: 0;">
150
+ <li>πŸ”¬ Advanced multi-color space analysis (RGB, LAB, HSV)</li>
151
+ <li>πŸ“Š Professional statistical analysis and reporting</li>
152
+ <li>🎯 Batch processing of thousands of images</li>
153
+ <li>πŸ“ˆ Interactive 3D visualizations and heatmaps</li>
154
+ <li>πŸ’Ύ Export to Excel, CSV, JSON formats</li>
155
+ <li>πŸ”§ Configurable clustering parameters</li>
156
+ <li>⚑ GPU-accelerated processing</li>
157
+ <li>πŸ”’ Complete offline operation</li>
158
+ </ul>
159
+ </div>
160
+ </div>
161
+
162
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
163
+ <p style="color: white; margin: 0;">
164
+ <strong>File Size:</strong> 1.1GB | <strong>Platform:</strong> Windows 64-bit<br>
165
+ <strong>Requirements:</strong> Windows 10/11, 8GB RAM
166
+ </p>
167
+ </div>
168
+ </div>
169
+ """
170
+
171
+ return download_html
172
+
173
+ def analyze_image_web(image, num_clusters):
174
+ """Web interface analysis function"""
175
+ if image is None:
176
+ return None, "Please upload an image first.", None
177
+
178
+ analyzer = WebColorAnalyzer()
179
+ results, error = analyzer.analyze_single_image(image, num_clusters)
180
+
181
+ if error:
182
+ return None, error, None
183
+
184
+ # Create DataFrame for display
185
+ df = pd.DataFrame(results)
186
+
187
+ # Create color palette visualization
188
+ palette_img = analyzer.create_color_palette_image(results)
189
+
190
+ return df, "βœ… Analysis completed successfully!", palette_img
191
+
192
+ def create_interface():
193
+ """Create the main Gradio interface"""
194
+
195
+ with gr.Blocks(
196
+ title="🎨 Color Quantification Tool",
197
+ theme=gr.themes.Soft(),
198
+ ) as demo:
199
+
200
+ gr.Markdown("""
201
+ # 🎨 Color Quantification Tool
202
+
203
+ **Professional Color Analysis Platform** - Web Demo Version
204
+
205
+ This is a simplified web version for demonstration. For full functionality, download the desktop application below.
206
+ """)
207
+
208
+ # Download section
209
+ gr.HTML(create_download_interface())
210
+
211
+ gr.Markdown("## 🌐 Try the Web Demo")
212
+
213
+ with gr.Row():
214
+ with gr.Column(scale=1):
215
+ gr.Markdown("### πŸ“€ Input")
216
+
217
+ image_input = gr.Image(
218
+ label="Upload Image",
219
+ type="pil",
220
+ height=300
221
+ )
222
+
223
+ num_clusters = gr.Slider(
224
+ minimum=2,
225
+ maximum=10,
226
+ value=5,
227
+ step=1,
228
+ label="Number of Colors to Extract"
229
+ )
230
+
231
+ analyze_btn = gr.Button(
232
+ "πŸ” Analyze Colors",
233
+ variant="primary",
234
+ size="lg"
235
+ )
236
+
237
+ with gr.Column(scale=2):
238
+ gr.Markdown("### πŸ“Š Results")
239
+
240
+ status_output = gr.Textbox(
241
+ label="Status",
242
+ interactive=False
243
+ )
244
+
245
+ results_output = gr.Dataframe(
246
+ label="Dominant Colors",
247
+ headers=["Color", "RGB", "Hex", "Percentage"],
248
+ interactive=False
249
+ )
250
+
251
+ palette_output = gr.Image(
252
+ label="Color Palette",
253
+ height=150
254
+ )
255
+
256
+ # Event handlers
257
+ analyze_btn.click(
258
+ fn=analyze_image_web,
259
+ inputs=[image_input, num_clusters],
260
+ outputs=[results_output, status_output, palette_output]
261
+ )
262
+
263
+ # Example section
264
+ gr.Markdown("""
265
+ ## πŸ“‹ Usage Instructions
266
+
267
+ 1. **Upload an image** using the file uploader
268
+ 2. **Adjust the number of colors** to extract (2-10)
269
+ 3. **Click "Analyze Colors"** to start the analysis
270
+ 4. **View the results** in the table and color palette
271
+
272
+ ### πŸ”¬ What This Demo Shows
273
+ - Basic color extraction using K-means clustering
274
+ - Dominant color identification with percentages
275
+ - Visual color palette representation
276
+
277
+ ### πŸš€ Desktop Version Features
278
+ - **Multi-color space analysis** (RGB, LAB, HSV)
279
+ - **Advanced distance metrics** (Ξ”E2000, Bhattacharyya)
280
+ - **Batch processing** of multiple images
281
+ - **Statistical analysis** and professional reporting
282
+ - **3D visualizations** and interactive charts
283
+ - **Export capabilities** (Excel, CSV, JSON)
284
+ """)
285
+
286
+ # Footer
287
+ gr.Markdown("""
288
+ ---
289
+
290
+ **🎯 Ready for Advanced Analysis?**
291
+
292
+ Download the full desktop version for professional color quantification with advanced features!
293
+
294
+ *Color Quantification Tool - Making color analysis accessible to everyone*
295
+ """)
296
+
297
+ return demo
298
+
299
+ if __name__ == "__main__":
300
+ # Create and launch the interface
301
+ demo = create_interface()
302
+ demo.launch()