-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1599 lines (1374 loc) · 69 KB
/
app.py
File metadata and controls
1599 lines (1374 loc) · 69 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import cv2
import numpy as np
from PIL import Image
from skimage.morphology import thin, dilation, disk
import io
from datetime import datetime
import json
# Page configuration with custom theme
st.set_page_config(
page_title="Image Enhancer Pro",
page_icon="🖼️",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://github.com/JosephJonathanFernandes/image-processing-vision-project',
'Report a bug': "https://github.com/JosephJonathanFernandes/image-processing-vision-project/issues",
'About': "# Image Enhancer Pro v2.0\n\nProfessional image processing and computer vision application."
}
)
# Initialize session state for better UX
if 'processed_image' not in st.session_state:
st.session_state.processed_image = None
if 'comparison_mode' not in st.session_state:
st.session_state.comparison_mode = False
if 'show_histogram' not in st.session_state:
st.session_state.show_histogram = False
if 'operation_history' not in st.session_state:
st.session_state.operation_history = []
if 'history_index' not in st.session_state:
st.session_state.history_index = -1
if 'original_image' not in st.session_state:
st.session_state.original_image = None
if 'current_operation' not in st.session_state:
st.session_state.current_operation = None
if 'favorites' not in st.session_state:
st.session_state.favorites = []
if 'show_help' not in st.session_state:
st.session_state.show_help = False
# Enhanced CSS styling with animations
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
font-family: 'Inter', sans-serif;
}
.main-header {
font-size: 3rem;
font-weight: 700;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
margin-bottom: 0.5rem;
animation: fadeInDown 0.8s ease;
}
.main-subtitle {
text-align: center;
color: #666;
font-size: 1.1rem;
margin-bottom: 2rem;
animation: fadeIn 1s ease;
}
.sub-header {
font-size: 1.8rem;
font-weight: 600;
margin-bottom: 1.5rem;
color: #2c3e50;
border-bottom: 3px solid #667eea;
padding-bottom: 0.5rem;
animation: slideInLeft 0.6s ease;
}
.category-header {
font-size: 1.2rem;
font-weight: bold;
margin-top: 1rem;
color: #0D47A1;
}
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
background-color: #f8f9fa;
padding: 10px;
border-radius: 10px;
}
.stTabs [data-baseweb="tab"] {
height: 60px;
background-color: white;
border-radius: 8px;
border: 2px solid #e9ecef;
padding: 0 24px;
font-weight: 500;
transition: all 0.3s ease;
}
.stTabs [data-baseweb="tab"]:hover {
background-color: #f0f0f0;
transform: translateY(-2px);
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.stTabs [aria-selected="true"] {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white !important;
border: none;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.info-box {
background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
padding: 16px;
border-radius: 12px;
border-left: 5px solid #667eea;
margin-bottom: 16px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
animation: fadeIn 0.5s ease;
}
.info-box p {
margin: 0;
color: #2c3e50;
font-size: 0.95rem;
line-height: 1.6;
}
.image-container {
display: flex;
justify-content: center;
margin-top: 1rem;
}
.tool-description {
font-size: 0.9rem;
color: #424242;
margin-bottom: 1rem;
}
.parameter-section {
background-color: #f8f9fa;
padding: 20px;
border-radius: 12px;
margin-bottom: 16px;
border: 1px solid #e9ecef;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.stButton button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px;
border: none;
padding: 0.6rem 2rem;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.stButton button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
}
.stDownloadButton button {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
color: white;
border-radius: 8px;
border: none;
padding: 0.6rem 2rem;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.stDownloadButton button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(17, 153, 142, 0.4);
}
.stats-card {
background: white;
padding: 16px;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 16px;
border-left: 4px solid #667eea;
}
.success-message {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
color: white;
padding: 12px 20px;
border-radius: 8px;
margin: 16px 0;
font-weight: 500;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
animation: slideInRight 0.5s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideInLeft {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.image-container {
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
margin-bottom: 1rem;
}
.image-container:hover {
transform: scale(1.02);
box-shadow: 0 6px 16px rgba(0,0,0,0.15);
}
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
.tooltip {
position: relative;
display: inline-block;
cursor: help;
}
.preset-card {
background: white;
padding: 15px;
border-radius: 8px;
border: 2px solid #e9ecef;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 10px;
}
.preset-card:hover {
border-color: #667eea;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(102, 126, 234, 0.2);
}
.history-item {
background: #f8f9fa;
padding: 10px 15px;
border-radius: 6px;
margin-bottom: 8px;
border-left: 3px solid #667eea;
font-size: 0.9rem;
}
.loading-spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #667eea;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.shortcut-key {
background: #2c3e50;
color: white;
padding: 2px 8px;
border-radius: 4px;
font-family: monospace;
font-size: 0.85rem;
margin-left: 8px;
}
.help-panel {
background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
padding: 20px;
border-radius: 12px;
margin: 20px 0;
border: 2px solid #667eea;
}
</style>
""", unsafe_allow_html=True)
# Helper functions for HCD features
def add_to_history(operation_name, image_data, params=None):
"""Add operation to history for undo/redo"""
# Remove any redo history when new operation is added
if st.session_state.history_index < len(st.session_state.operation_history) - 1:
st.session_state.operation_history = st.session_state.operation_history[:st.session_state.history_index + 1]
st.session_state.operation_history.append({
'operation': operation_name,
'image': image_data,
'params': params,
'timestamp': datetime.now().strftime('%H:%M:%S')
})
st.session_state.history_index = len(st.session_state.operation_history) - 1
# Limit history to 10 items
if len(st.session_state.operation_history) > 10:
st.session_state.operation_history.pop(0)
st.session_state.history_index -= 1
def undo_operation():
"""Undo last operation"""
if st.session_state.history_index > 0:
st.session_state.history_index -= 1
st.session_state.processed_image = st.session_state.operation_history[st.session_state.history_index]['image']
return True
elif st.session_state.history_index == 0:
st.session_state.history_index -= 1
st.session_state.processed_image = None
return True
return False
def redo_operation():
"""Redo previously undone operation"""
if st.session_state.history_index < len(st.session_state.operation_history) - 1:
st.session_state.history_index += 1
st.session_state.processed_image = st.session_state.operation_history[st.session_state.history_index]['image']
return True
return False
def toggle_favorite(operation_name):
"""Add/remove operation from favorites"""
if operation_name in st.session_state.favorites:
st.session_state.favorites.remove(operation_name)
else:
st.session_state.favorites.append(operation_name)
# Preset filters based on common use cases
PRESETS = {
"📸 Portrait Enhancement": {
"operations": ["Brightness +20", "Contrast +15", "Slight Blur"],
"description": "Soften skin and enhance facial features"
},
"🌆 Landscape Boost": {
"operations": ["Saturation +30", "Contrast +20", "Sharpen"],
"description": "Make landscapes pop with vivid colors"
},
"🎨 Vintage Film": {
"operations": ["Sepia", "Reduce Brightness -10", "Add Grain"],
"description": "Classic film photography look"
},
"✨ Social Media": {
"operations": ["Brightness +15", "Saturation +20", "Slight Sharpen"],
"description": "Perfect for Instagram and social posts"
},
"🖤 Dramatic B&W": {
"operations": ["Grayscale", "High Contrast", "Sharpen"],
"description": "Bold black and white conversion"
}
}
def apply_preset_logic(img, preset_name):
# Ensure correct shape and copy
result = img.copy()
if len(result.shape) == 2:
result = cv2.cvtColor(result, cv2.COLOR_GRAY2RGB)
if preset_name == "📸 Portrait Enhancement":
result = cv2.convertScaleAbs(result, alpha=1.15, beta=20)
result = cv2.GaussianBlur(result, (3, 3), 0)
elif preset_name == "🌆 Landscape Boost":
hsv = cv2.cvtColor(result, cv2.COLOR_RGB2HSV)
hsv[:,:,1] = cv2.add(hsv[:,:,1], 30)
result = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
result = cv2.convertScaleAbs(result, alpha=1.2, beta=0)
kernel_sharp = np.array([[0,-1,0], [-1,5,-1], [0,-1,0]])
result = cv2.filter2D(result, -1, kernel_sharp)
elif preset_name == "🎨 Vintage Film":
kernel_sepia = np.array([[0.272, 0.534, 0.131],
[0.349, 0.686, 0.168],
[0.393, 0.769, 0.189]])
result = cv2.transform(result, kernel_sepia)
result = cv2.convertScaleAbs(result, alpha=1.0, beta=-10)
elif preset_name == "✨ Social Media":
result = cv2.convertScaleAbs(result, alpha=1.0, beta=15)
hsv = cv2.cvtColor(result, cv2.COLOR_RGB2HSV)
hsv[:,:,1] = cv2.add(hsv[:,:,1], 20)
result = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
kernel_sharp = np.array([[0,-1,0], [-1,5,-1], [0,-1,0]])
result = cv2.filter2D(result, -1, kernel_sharp)
elif preset_name == "🖤 Dramatic B&W":
result = cv2.cvtColor(result, cv2.COLOR_RGB2GRAY)
result = cv2.cvtColor(result, cv2.COLOR_GRAY2RGB)
result = cv2.convertScaleAbs(result, alpha=1.5, beta=0)
kernel_sharp = np.array([[0,-1,0], [-1,5,-1], [0,-1,0]])
result = cv2.filter2D(result, -1, kernel_sharp)
return result
# Enhanced app header
st.markdown('<h1 class="main-header">🖼️ Image Enhancer Pro</h1>', unsafe_allow_html=True)
st.markdown('<p class="main-subtitle">Transform your images with professional-grade processing tools | Version 2.0</p>', unsafe_allow_html=True)
# Add keyboard shortcut handler
st.markdown("""
<script>
document.addEventListener('keydown', function(e) {
// Ctrl+Z for Undo
if (e.ctrlKey && e.key === 'z') {
e.preventDefault();
document.querySelector('[data-testid="stButton"] button:contains("Undo")').click();
}
// Ctrl+Y for Redo
if (e.ctrlKey && e.key === 'y') {
e.preventDefault();
document.querySelector('[data-testid="stButton"] button:contains("Redo")').click();
}
// ? for Help
if (e.key === '?') {
e.preventDefault();
document.querySelector('[data-testid="stButton"] button:contains("Help")').click();
}
});
</script>
""", unsafe_allow_html=True)
# Enhanced sidebar
with st.sidebar:
st.markdown("## 📤 Upload Image")
uploaded_file = st.file_uploader(
"Choose an image file",
type=["jpg", "jpeg", "png", "bmp", "tiff"],
help="Supported formats: JPG, PNG, BMP, TIFF"
)
if uploaded_file is not None:
st.markdown('<div class="success-message">✓ Image uploaded successfully!</div>', unsafe_allow_html=True)
# Store original image
if st.session_state.original_image is None:
image = Image.open(uploaded_file)
st.session_state.original_image = np.array(image)
# Display image information
image = Image.open(uploaded_file)
if st.session_state.processed_image is not None:
img_np = st.session_state.processed_image
else:
img_np = np.array(image)
st.markdown("### 📊 Image Information")
# Stats cards
col1, col2 = st.columns(2)
with col1:
st.markdown(f"""
<div class="stats-card">
<h4 style="margin:0;color:#2c3e50;font-size:0.9rem;">Width</h4>
<p style="margin:8px 0 0 0;color:#667eea;font-size:1.5rem;font-weight:700;">{img_np.shape[1]}px</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown(f"""
<div class="stats-card">
<h4 style="margin:0;color:#2c3e50;font-size:0.9rem;">Height</h4>
<p style="margin:8px 0 0 0;color:#667eea;font-size:1.5rem;font-weight:700;">{img_np.shape[0]}px</p>
</div>
""", unsafe_allow_html=True)
channels = img_np.shape[2] if len(img_np.shape) > 2 else 1
file_size = len(uploaded_file.getvalue()) / 1024
st.markdown(f"""
<div class="stats-card">
<h4 style="margin:0;color:#2c3e50;font-size:0.9rem;">Channels & Size</h4>
<p style="margin:8px 0 0 0;color:#667eea;font-size:1.2rem;font-weight:700;">{channels} channels | {file_size:.1f} KB</p>
</div>
""", unsafe_allow_html=True)
# Preview
st.markdown("### 👁️ Preview")
st.markdown('<div class="image-container">', unsafe_allow_html=True)
st.image(img_np, width="stretch")
st.markdown('</div>', unsafe_allow_html=True)
# Quick Presets Section
st.markdown("---")
st.markdown("### 🎯 Quick Presets")
st.markdown("<p style='font-size: 0.85rem; color: #666; margin-bottom: 10px;'>Apply professional filters instantly</p>", unsafe_allow_html=True)
for preset_name, preset_data in PRESETS.items():
with st.expander(preset_name):
st.markdown(f"**{preset_data['description']}**")
st.markdown("**Steps:**")
for op in preset_data['operations']:
st.markdown(f"• {op}")
if st.button(f"Apply {preset_name}", key=f"preset_{preset_name}", width="stretch"):
processed_img = apply_preset_logic(img_np, preset_name)
st.session_state.processed_image = processed_img
add_to_history(f"Preset: {preset_name}", processed_img.copy(), {"operation": preset_name})
st.success(f"✓ {preset_name} applied successfully!")
st.rerun()
# Operation History and Undo/Redo
st.markdown("---")
st.markdown("### 📜 Operation History")
col_undo, col_redo = st.columns(2)
with col_undo:
if st.button("⬅️ Undo", width="stretch", disabled=st.session_state.history_index < 0, help="Undo last operation (Ctrl+Z)"):
if undo_operation():
st.success("✓ Undone")
st.rerun()
with col_redo:
if st.button("➡️ Redo", width="stretch", disabled=st.session_state.history_index >= len(st.session_state.operation_history) - 1, help="Redo operation (Ctrl+Y)"):
if redo_operation():
st.success("✓ Redone")
st.rerun()
# Display history
if st.session_state.operation_history:
st.markdown(f"<p style='font-size: 0.85rem; color: #666; margin: 10px 0;'>{len(st.session_state.operation_history)} operations in history</p>", unsafe_allow_html=True)
with st.expander("View History", expanded=False):
for idx, item in enumerate(reversed(st.session_state.operation_history[-5:])):
is_current = (len(st.session_state.operation_history) - 1 - idx) == st.session_state.history_index
marker = "➡️" if is_current else "•"
st.markdown(f"<div class='history-item'>{marker} <b>{item['operation']}</b><br/><small>{item['timestamp']}</small></div>", unsafe_allow_html=True)
else:
st.markdown("<p style='font-size: 0.85rem; color: #999;'>No operations yet</p>", unsafe_allow_html=True)
# Favorites section
st.markdown("---")
st.markdown("### ⭐ Favorite Operations")
if st.session_state.favorites:
for fav in st.session_state.favorites:
st.markdown(f"• {fav}")
else:
st.markdown("<p style='font-size: 0.85rem; color: #999;'>No favorites yet. Star operations to add them here!</p>", unsafe_allow_html=True)
# Help and Keyboard Shortcuts
st.markdown("---")
if st.button("❓ Help & Shortcuts", width="stretch"):
st.session_state.show_help = not st.session_state.show_help
# Options
st.markdown("---")
st.markdown("### ⚙️ Options")
st.session_state.comparison_mode = st.checkbox(
"Show Comparison View",
value=st.session_state.comparison_mode,
help="Display original and processed images side-by-side"
)
if st.button("🔄 Reset All", width="stretch"):
st.session_state.processed_image = None
st.rerun()
# Main content area
if uploaded_file is not None:
# Help Panel
if st.session_state.show_help:
st.markdown("""
<div class="help-panel">
<h3 style="margin-top: 0; color: #2c3e50;">⌨️ Keyboard Shortcuts & Tips</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px;">
<div>
<p style="margin: 5px 0;"><span class="shortcut-key">Ctrl + Z</span> Undo last operation</p>
<p style="margin: 5px 0;"><span class="shortcut-key">Ctrl + Y</span> Redo operation</p>
<p style="margin: 5px 0;"><span class="shortcut-key">Ctrl + S</span> Save image</p>
</div>
<div>
<p style="margin: 5px 0;"><span class="shortcut-key">Ctrl + R</span> Reset all changes</p>
<p style="margin: 5px 0;"><span class="shortcut-key">Tab</span> Navigate between controls</p>
<p style="margin: 5px 0;"><span class="shortcut-key">?</span> Toggle this help</p>
</div>
</div>
<hr style="margin: 20px 0; border: none; border-top: 1px solid #ccc;">
<h4 style="color: #2c3e50; margin-bottom: 10px;">💡 Tips for Best Results</h4>
<ul style="margin: 0; padding-left: 20px; color: #555;">
<li>Use presets for quick professional edits</li>
<li>Check comparison mode to see before/after</li>
<li>Star your favorite operations for quick access</li>
<li>Operations are saved in history - you can undo anytime</li>
<li>Download in PNG for lossless quality or JPG for smaller files</li>
</ul>
</div>
""", unsafe_allow_html=True)
image = Image.open(uploaded_file)
original_img_np = np.array(image)
if st.session_state.processed_image is not None:
img_np = st.session_state.processed_image
else:
img_np = original_img_np
# Show comparison mode before the tabs if activated
if st.session_state.comparison_mode and st.session_state.processed_image is not None:
st.markdown('<h3 class="sub-header">🔍 Comparison View</h3>', unsafe_allow_html=True)
comp_col1, comp_col2 = st.columns(2)
with comp_col1:
st.markdown('**Original Image**')
st.image(original_img_np, width="stretch")
with comp_col2:
st.markdown('**Processed Image**')
st.image(img_np, width="stretch")
st.markdown('---')
if len(img_np.shape) == 2:
gray = img_np
else:
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
kernel = np.ones((3, 3), np.uint8)
# Create tabs for different categories of operations
tab1, tab2, tab3, tab4, tab5 = st.tabs([
"💫 Basic Operations",
"🎨 Color Transformations",
"🔍 Edge Detection",
"📐 Morphological Operations",
"✨ Special Effects"
])
# Tab 1: Basic Operations
with tab1:
st.markdown('<h2 class="sub-header">💫 Basic Image Operations</h2>', unsafe_allow_html=True)
col1, col2 = st.columns([1, 1])
with col1:
# Add favorite button
col_select, col_fav = st.columns([5, 1])
with col_select:
basic_op = st.selectbox(
"Choose a basic operation",
[
"Grayscale",
"Brightness & Contrast",
"Gaussian Blur",
"Median Blur",
"Bilateral Filter",
"Rotation",
"Flip",
"Resize",
"Invert Image",
"Sharpening",
"Histogram Equalization"
],
help="Select an operation to apply to your image"
)
with col_fav:
is_favorite = basic_op in st.session_state.favorites
if st.button("⭐" if is_favorite else "☆", key=f"fav_basic_{basic_op}", help="Add to favorites"):
toggle_favorite(basic_op)
st.rerun()
# Show operation description
operation_descriptions = {
"Grayscale": "Converts the image to grayscale (black and white) by removing color information.",
"Brightness & Contrast": "Adjusts the brightness and contrast levels of the image.",
"Gaussian Blur": "Applies a Gaussian blur filter which reduces noise and detail.",
"Median Blur": "Applies a median filter that reduces noise while preserving edges.",
"Bilateral Filter": "Reduces noise while preserving edges by considering both spatial and intensity differences.",
"Rotation": "Rotates the image by a specified angle in degrees.",
"Flip": "Mirrors the image horizontally, vertically, or both.",
"Resize": "Changes the dimensions of the image.",
"Invert Image": "Creates a negative of the image by inverting all pixel values.",
"Sharpening": "Enhances edges and fine details in the image.",
"Histogram Equalization": "Improves contrast by stretching out the intensity range."
}
st.markdown(f'<div class="info-box"><p>{operation_descriptions.get(basic_op, "")}</p></div>', unsafe_allow_html=True)
# Parameters for operations
result = None
if basic_op == "Brightness & Contrast":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
alpha = st.slider("Contrast", 0.5, 3.0, 1.0, help="1.0 = original, >1.0 = more contrast, <1.0 = less contrast")
beta = st.slider("Brightness", -100, 100, 0, help="0 = original, positive = brighter, negative = darker")
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.convertScaleAbs(img_np, alpha=alpha, beta=beta)
elif basic_op == "Rotation":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
angle = st.slider("Rotation Angle", -180, 180, 0, help="Positive = clockwise, Negative = counter-clockwise")
st.markdown('</div>', unsafe_allow_html=True)
h, w = img_np.shape[:2]
M = cv2.getRotationMatrix2D((w//2, h//2), angle, 1)
result = cv2.warpAffine(img_np, M, (w, h))
elif basic_op == "Flip":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
flip_mode = st.radio("Flip Direction", ["Horizontal", "Vertical", "Both"], help="Choose how to mirror the image")
st.markdown('</div>', unsafe_allow_html=True)
if flip_mode == "Horizontal":
result = cv2.flip(img_np, 1)
elif flip_mode == "Vertical":
result = cv2.flip(img_np, 0)
else:
result = cv2.flip(img_np, -1)
elif basic_op == "Resize":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
maintain_aspect = st.checkbox("Maintain aspect ratio", True, help="Keep original width/height proportions")
if maintain_aspect:
scale = st.slider("Scale factor", 0.1, 2.0, 1.0, 0.1, help="1.0 = original size")
new_width = int(img_np.shape[1] * scale)
new_height = int(img_np.shape[0] * scale)
else:
new_width = st.slider("Width", 50, img_np.shape[1]*2, img_np.shape[1], help="Target width in pixels")
new_height = st.slider("Height", 50, img_np.shape[0]*2, img_np.shape[0], help="Target height in pixels")
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.resize(img_np, (new_width, new_height))
elif basic_op == "Grayscale":
result = gray
elif basic_op == "Gaussian Blur":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
kernel_size = st.slider("Blur Amount", 1, 25, 5, step=2, help="Higher = more blur. Must be odd number.")
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.GaussianBlur(img_np, (kernel_size, kernel_size), 0)
elif basic_op == "Median Blur":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
kernel_size = st.slider("Blur Amount", 1, 25, 5, step=2, help="Higher = more blur. Good for removing salt-and-pepper noise.")
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.medianBlur(img_np, kernel_size)
elif basic_op == "Bilateral Filter":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
d = st.slider("Filter Size", 5, 15, 9)
sigma_color = st.slider("Sigma Color", 10, 150, 75)
sigma_space = st.slider("Sigma Space", 10, 150, 75)
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.bilateralFilter(img_np, d, sigma_color, sigma_space)
elif basic_op == "Invert Image":
result = cv2.bitwise_not(img_np)
elif basic_op == "Sharpening":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
amount = st.slider("Sharpening Amount", 1, 10, 5)
st.markdown('</div>', unsafe_allow_html=True)
kernel_sharp = np.array([[0,-1,0], [-1,1+(2*amount),-1], [0,-1,0]])
result = cv2.filter2D(img_np, -1, kernel_sharp)
elif basic_op == "Histogram Equalization":
if len(img_np.shape) > 2 and img_np.shape[2] == 3:
# For color images
img_yuv = cv2.cvtColor(img_np, cv2.COLOR_RGB2YUV)
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
result = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2RGB)
else:
result = cv2.equalizeHist(gray)
with col2:
if result is not None:
with st.spinner('🎨 Processing image...'):
st.image(result, caption=f"Result: {basic_op}", width="stretch")
# Action buttons with progress feedback
btn_col1, btn_col2 = st.columns(2)
with btn_col1:
if st.button("✅ Apply This Result", key=f"apply_basic_{basic_op}", width="stretch", help="Save this result to continue editing"):
st.session_state.processed_image = result
add_to_history(f"Basic: {basic_op}", result.copy(), {"operation": basic_op})
st.success(f"✓ {basic_op} applied!")
st.balloons()
with btn_col2:
if st.button("🔄 Reset to Original", key=f"reset_basic_{basic_op}", width="stretch", help="Discard changes and start over"):
st.session_state.processed_image = None
st.session_state.operation_history = []
st.session_state.history_index = -1
st.info("Reset to original image")
st.rerun()
# Tab 2: Color Transformations
with tab2:
st.markdown('<h2 class="sub-header">🎨 Color Transformations</h2>', unsafe_allow_html=True)
col1, col2 = st.columns([1, 1])
with col1:
color_op = st.selectbox("Choose a color operation", [
"RGB to HSV",
"HSV to RGB",
"RGB to LAB",
"LAB to RGB",
"RGB to YCrCb",
"Color Mask (HSV)",
"Color Balance",
"Channel Mixing",
"Thresholding",
"Adaptive Thresholding"
])
# Show operation description
color_descriptions = {
"RGB to HSV": "Converts from RGB (Red, Green, Blue) to HSV (Hue, Saturation, Value) color space.",
"HSV to RGB": "Converts from HSV back to RGB color space.",
"RGB to LAB": "Converts from RGB to LAB (Lightness, a, b) color space, which is perceptually uniform.",
"LAB to RGB": "Converts from LAB back to RGB color space.",
"RGB to YCrCb": "Converts from RGB to YCrCb (Luminance, Red-difference, Blue-difference).",
"Color Mask (HSV)": "Creates a mask to isolate specific colors using HSV ranges.",
"Color Balance": "Adjusts the balance of color channels in the image.",
"Channel Mixing": "View and modify individual color channels.",
"Thresholding": "Converts grayscale to binary using a single threshold value.",
"Adaptive Thresholding": "Local thresholding that adapts to different image regions."
}
st.markdown(f'<div class="info-box"><p>{color_descriptions.get(color_op, "")}</p></div>', unsafe_allow_html=True)
# Parameters for operations
result = None
# Ensure we have a 3-channel RGB image for color transformations
if len(img_np.shape) == 2:
color_img_np = cv2.cvtColor(img_np, cv2.COLOR_GRAY2RGB)
elif len(img_np.shape) == 3 and img_np.shape[2] == 4:
color_img_np = cv2.cvtColor(img_np, cv2.COLOR_RGBA2RGB)
else:
color_img_np = img_np.copy()
if color_op == "RGB to HSV":
result = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2HSV)
elif color_op == "HSV to RGB":
hsv = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2HSV)
result = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
elif color_op == "RGB to LAB":
result = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2LAB)
elif color_op == "LAB to RGB":
lab = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2LAB)
result = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
elif color_op == "RGB to YCrCb":
result = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2YCrCb)
elif color_op == "Color Mask (HSV)":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
hsv = cv2.cvtColor(color_img_np, cv2.COLOR_RGB2HSV)
# Create two columns for the HSV sliders
hue_col, satval_col = st.columns(2)
with hue_col:
lower_h = st.slider("Lower Hue", 0, 179, 30)
upper_h = st.slider("Upper Hue", 0, 179, 90)
with satval_col:
lower_s = st.slider("Lower Saturation", 0, 255, 50)
upper_s = st.slider("Upper Saturation", 0, 255, 255)
lower_v = st.slider("Lower Value", 0, 255, 50)
upper_v = st.slider("Upper Value", 0, 255, 255)
lower = np.array([lower_h, lower_s, lower_v])
upper = np.array([upper_h, upper_s, upper_v])
# Preview the mask
show_mask = st.checkbox("Show mask only", False)
st.markdown('</div>', unsafe_allow_html=True)
mask = cv2.inRange(hsv, lower, upper)
if show_mask:
result = mask
else:
result = cv2.bitwise_and(color_img_np, color_img_np, mask=mask)
elif color_op == "Color Balance":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
b, g, r = cv2.split(cv2.cvtColor(color_img_np, cv2.COLOR_RGB2BGR))
r_gain = st.slider("Red Channel", 0.0, 2.0, 1.0, 0.1)
g_gain = st.slider("Green Channel", 0.0, 2.0, 1.0, 0.1)
b_gain = st.slider("Blue Channel", 0.0, 2.0, 1.0, 0.1)
r = cv2.convertScaleAbs(r, alpha=r_gain)
g = cv2.convertScaleAbs(g, alpha=g_gain)
b = cv2.convertScaleAbs(b, alpha=b_gain)
st.markdown('</div>', unsafe_allow_html=True)
balanced = cv2.merge([b, g, r])
result = cv2.cvtColor(balanced, cv2.COLOR_BGR2RGB)
elif color_op == "Channel Mixing":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
channel = st.radio("Select Channel", ["Red", "Green", "Blue", "All"])
st.markdown('</div>', unsafe_allow_html=True)
r, g, b = cv2.split(cv2.cvtColor(color_img_np, cv2.COLOR_RGB2BGR))
if channel == "Red":
result = cv2.cvtColor(cv2.merge([np.zeros_like(b), np.zeros_like(g), r]), cv2.COLOR_BGR2RGB)
elif channel == "Green":
result = cv2.cvtColor(cv2.merge([np.zeros_like(b), g, np.zeros_like(r)]), cv2.COLOR_BGR2RGB)
elif channel == "Blue":
result = cv2.cvtColor(cv2.merge([b, np.zeros_like(g), np.zeros_like(r)]), cv2.COLOR_BGR2RGB)
else:
result = color_img_np
elif color_op == "Thresholding":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
thresh_val = st.slider("Threshold Value", 0, 255, 127)
thresh_type = st.selectbox("Threshold Type", [
"Binary", "Binary Inverted", "Truncate",
"To Zero", "To Zero Inverted"
])
thresh_types = {
"Binary": cv2.THRESH_BINARY,
"Binary Inverted": cv2.THRESH_BINARY_INV,
"Truncate": cv2.THRESH_TRUNC,
"To Zero": cv2.THRESH_TOZERO,
"To Zero Inverted": cv2.THRESH_TOZERO_INV
}
st.markdown('</div>', unsafe_allow_html=True)
_, result = cv2.threshold(gray, thresh_val, 255, thresh_types[thresh_type])
elif color_op == "Adaptive Thresholding":
st.markdown('<div class="parameter-section">', unsafe_allow_html=True)
method = st.radio("Method", ["Gaussian", "Mean"])
block_size = st.slider("Block Size", 3, 99, 11, step=2)
c_value = st.slider("C Value", -10, 30, 2)
adaptive_method = cv2.ADAPTIVE_THRESH_GAUSSIAN_C if method == "Gaussian" else cv2.ADAPTIVE_THRESH_MEAN_C
st.markdown('</div>', unsafe_allow_html=True)
result = cv2.adaptiveThreshold(gray, 255, adaptive_method, cv2.THRESH_BINARY, block_size, c_value)
with col2:
if result is not None:
with st.spinner('🎨 Processing image...'):
st.image(result, caption=f"Result: {color_op}", width="stretch")
btn_col1, btn_col2 = st.columns(2)
with btn_col1:
if st.button("✅ Apply This Result", key=f"apply_color_{color_op}", width="stretch", help="Save this result to continue editing"):
st.session_state.processed_image = result
add_to_history(f"Color: {color_op}", result.copy(), {"operation": color_op})
st.success(f"✓ {color_op} applied!")
st.balloons()
with btn_col2:
if st.button("🔄 Reset to Original", key=f"reset_color_{color_op}", width="stretch", help="Discard changes and start over"):
st.session_state.processed_image = None
st.session_state.operation_history = []
st.session_state.history_index = -1
st.info("Reset to original image")
st.rerun()
# Tab 3: Edge Detection
with tab3:
st.markdown('<h2 class="sub-header">🔍 Edge Detection</h2>', unsafe_allow_html=True)
col1, col2 = st.columns([1, 1])
with col1:
col_select, col_fav = st.columns([5, 1])
with col_select:
edge_op = st.selectbox(
"Choose an edge detection method",
[
"Sobel Edge Detection",
"Manual Sobel Edge Detection",
"Prewitt Edge Detection",
"Laplacian Edge Detection",
"Canny Edge Detection",
"Overlay Edges on Original"
],
help="Select an edge detection algorithm"
)