File size: 11,483 Bytes
e735ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
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()