A1mal commited on
Commit
f29da31
·
verified ·
1 Parent(s): 67a7c4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -188
app.py CHANGED
@@ -1,218 +1,177 @@
 
 
1
  import tensorflow as tf
2
- from tensorflow import keras
3
- import streamlit as st
4
  import cv2
 
 
5
  import numpy as np
6
- import time
7
- from PIL import Image
8
  import plotly.graph_objects as go
9
- from modules.enhance import enhancement_pipeline, detect_brightness
10
- from modules.parallel import parallel_enhancement
11
- from modules.metrics import calculate_execution_metrics, get_image_info
12
- from modules.dataset_loader import get_lol_dataset_samples, load_lol_pair
13
- import io
14
- import os
15
- import multiprocessing
16
- from tensorflow.keras.models import load_model
17
- model = load_model("lowlight_enhancer.keras")
18
 
19
  # ---------------------------------------------------------
20
- # UI CONFIGURATION
21
  # ---------------------------------------------------------
22
- st.set_page_config(
23
- page_title="Parallel Low Light Image Enhancement",
24
- page_icon="⚡",
25
- layout="wide",
26
- initial_sidebar_state="expanded"
27
- )
28
-
29
- # Custom CSS for Professional Branding
30
- st.markdown("""
31
- <style>
32
- .stMetric {
33
- background-color: #1a1c24;
34
- padding: 20px;
35
- border-radius: 12px;
36
- border: 1px solid #30363d;
37
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
38
- }
39
- .stButton>button {
40
- width: 100%;
41
- border-radius: 8px;
42
- height: 60px;
43
- font-weight: bold;
44
- text-transform: uppercase;
45
- letter-spacing: 1px;
46
- }
47
- </style>
48
- """, unsafe_allow_html=True)
49
 
50
  # ---------------------------------------------------------
51
- # SIDEBAR CONTROLS
52
  # ---------------------------------------------------------
53
- st.sidebar.markdown("<h1 style='color:#ff4b4b;'>⚡ PLL-SIE System</h1>", unsafe_allow_html=True)
54
- st.sidebar.caption("Parallel Low Light Smart Image Enhancement")
55
- st.sidebar.markdown("---")
56
-
57
- app_mode = st.sidebar.selectbox("Navigation", ["Image Workspace", "LOL Dataset Explorer", "Webcam Live", "Project Report"])
58
-
59
- if app_mode != "Project Report":
60
- st.sidebar.subheader("🎚️ Enhancement Params")
61
- gamma_val = st.sidebar.slider("Gamma Correction", 0.5, 4.0, 1.8, 0.1)
62
- clahe_clip = st.sidebar.slider("CLAHE Contrast", 1.0, 10.0, 3.0, 0.5)
63
- denoise_h = st.sidebar.slider("Noise Reduction", 0, 30, 12, 1)
64
-
65
- st.sidebar.markdown("---")
66
- st.sidebar.subheader("⚙️ System Status")
67
- cpu_count = multiprocessing.cpu_count()
68
- st.sidebar.info(f"Available Logical Cores: {cpu_count}")
69
- parallel_cores = st.sidebar.number_input("Cores to allocate", 1, cpu_count, max(1, cpu_count-1))
70
-
71
- st.sidebar.markdown("---")
72
- st.sidebar.markdown("### Development Info")
73
- st.sidebar.write("v1.2.0-Production")
74
 
75
- # ---------------------------------------------------------
76
- # CORE LOGIC
77
- # ---------------------------------------------------------
78
 
79
- def run_image_enhancement(input_img):
80
- config = {
81
- "gamma_enable": True,
82
- "gamma": gamma_val,
83
- "clahe_enable": True,
84
- "clahe_clip": clahe_clip,
85
- "denoise_enable": True,
86
- "denoise_h": denoise_h,
87
- "sharpen_enable": True,
88
- "cores": parallel_cores
89
- }
90
-
91
- results = calculate_execution_metrics(
92
- enhancement_pipeline,
93
- parallel_enhancement,
94
- input_img,
95
- config
96
  )
97
-
98
- return results
99
 
100
- def main():
101
- if app_mode == "Image Workspace":
102
- st.header("📸 Image Enhancement Workspace")
103
- uploaded_file = st.file_uploader("Select source image", type=['jpg', 'jpeg', 'png', 'tiff'], key="main_image_loader")
104
-
105
- if uploaded_file:
106
- img = Image.open(uploaded_file).convert("RGB")
107
- img_np = np.array(img)
108
-
109
- info = get_image_info(img_np)
110
- brightness = detect_brightness(img_np)
111
-
112
- # Metadata Dashboard
113
- col_b1, col_b2, col_b3 = st.columns(3)
114
- with col_b1:
115
- st.metric("Mean Brightness", f"{brightness:.1f} cd/m²")
116
- with col_b2:
117
- st.metric("Total Pixels", f"{info['megapixels']:.2f} MP")
118
- with col_b3:
119
- status = "🔴 UNDEREXPOSED" if brightness < 70 else "🟢 OPTIMAL"
120
- st.metric("System Auto-Diagnosis", status)
121
-
 
 
 
 
 
 
 
 
122
  st.markdown("---")
123
- if st.button("🚀 EXECUTE MULTIPROCESSING PIPELINE"):
124
- with st.spinner("Synchronizing CPU workers..."):
125
- metrics = run_image_enhancement(img_np)
126
-
127
- # Visualization
128
- c1, c2 = st.columns(2)
129
- with c1:
130
- st.subheader("Input Frame")
131
- st.image(img_np, use_container_width=True)
132
- with c2:
133
- st.subheader("Enhanced Signal")
134
- st.image(metrics['result'], use_container_width=True)
135
-
136
- # Performance Graph
137
- st.markdown("---")
138
- st.subheader("📈 Throughput Analytics")
139
-
140
- m1, m2, m3 = st.columns(3)
141
- m1.metric("Sequential (ST)", f"{metrics['sequential_time']:.4f}s")
142
- m2.metric("Parallel (MP)", f"{metrics['parallel_time']:.4f}s")
143
- m3.metric("Efficiency Gain", f"{metrics['speedup']:.2f}x")
144
-
145
- fig = go.Figure(data=[
146
- go.Bar(name='Single-Thread', x=['Execution'], y=[metrics['sequential_time']], marker_color='#ff4b4b'),
147
- go.Bar(name='Multi-Process', x=['Execution'], y=[metrics['parallel_time']], marker_color='#00d1ff')
148
- ])
149
- fig.update_layout(template="plotly_dark", barmode='group', height=300)
150
- st.plotly_chart(fig, use_container_width=True)
151
-
152
- # Download
153
- result_pil = Image.fromarray(metrics['result'])
154
- buf = io.BytesIO()
155
- result_pil.save(buf, format="PNG")
156
- st.download_button(
157
- label="💾 Export High-Fidelity Result",
158
- data=buf.getvalue(),
159
- file_name="enhanced_parallel_output.png",
160
- mime="image/png"
161
- )
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  elif app_mode == "LOL Dataset Explorer":
164
- st.header("📂 LOL Dataset Browser")
165
- st.write("Browse and compare ground truth vs low-light enhancement from the LOL dataset.")
166
-
167
  samples = get_lol_dataset_samples()
 
168
  if not samples:
169
- st.info("Place the LOL dataset in folder: dataset/LOLdataset/low to use this feature.")
170
- # Mock / Placeholder info
171
- st.write("Dataset Structure Example:")
172
- st.code("""
173
- dataset/
174
- └── LOLdataset/
175
- ├── low/ (485 images)
176
- └── high/ (485 images)
177
- """)
178
- else:
179
- selected_sample_name = st.selectbox("Select Sample", [s['name'] for s in samples])
180
- sample = next(s for s in samples if s['name'] == selected_sample_name)
181
-
182
- low, high = load_lol_pair(sample)
183
-
184
- col1, col2, col3 = st.columns(3)
185
- with col1:
186
- st.subheader("Low Light (Input)")
187
- st.image(low, use_container_width=True)
188
- with col2:
189
- st.subheader("Ground Truth")
190
- st.image(high, use_container_width=True)
191
- with col3:
192
- st.subheader("PLL-SIE Enhanced")
193
- res = enhancement_pipeline(low, {"gamma": gamma_val, "clahe_limit": clahe_clip, "denoise_h": denoise_h})
194
- st.image(res, use_container_width=True)
195
 
 
 
 
 
 
 
 
 
196
  elif app_mode == "Webcam Live":
197
- st.header("🎥 Live Signal Capture")
198
- st.markdown("Use your camera to capture and optimize dark environment frames.")
199
-
200
- img_file_buffer = st.camera_input("Snapshot for Smart Optimization")
201
-
202
- if img_file_buffer:
203
- img = Image.open(img_file_buffer).convert("RGB")
 
204
  img_np = np.array(img)
205
- with st.spinner("Optimizing stream..."):
206
- metrics = run_image_enhancement(img_np)
207
- st.image(metrics['result'], caption="Optimized View Result")
208
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  elif app_mode == "Project Report":
210
- # Check if README.md exists
211
  if os.path.exists("README.md"):
212
  with open("README.md", "r") as f:
213
  st.markdown(f.read())
214
  else:
215
- st.error("Report (README.md) not found.")
216
 
 
 
 
 
217
  if __name__ == "__main__":
218
- main()
 
1
+ import os
2
+ import io
3
  import tensorflow as tf
 
 
4
  import cv2
5
+ import multiprocessing
6
+ import threading
7
  import numpy as np
8
+ import streamlit as st
 
9
  import plotly.graph_objects as go
10
+ from PIL import Image
 
 
 
 
 
 
 
 
11
 
12
  # ---------------------------------------------------------
13
+ # SAFE HELPER
14
  # ---------------------------------------------------------
15
+ def safe_uint8(img):
16
+ img = np.array(img)
17
+ img = np.nan_to_num(img)
18
+ img = np.clip(img, 0, 255)
19
+ return img.astype(np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # ---------------------------------------------------------
22
+ # MAIN APP
23
  # ---------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ def main():
26
+
27
+ st.title("Low Light Image Enhancement System")
28
 
29
+ app_mode = st.sidebar.selectbox(
30
+ "Choose Mode",
31
+ ["Single Image Enhancement", "LOL Dataset Explorer", "Webcam Live", "Project Report"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  )
 
 
33
 
34
+ # =====================================================
35
+ # SINGLE IMAGE ENHANCEMENT
36
+ # =====================================================
37
+ if app_mode == "Single Image Enhancement":
38
+
39
+ uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
40
+
41
+ if uploaded_file is not None:
42
+
43
+ # ---------- SAFE IMAGE LOAD ----------
44
+ image = Image.open(uploaded_file).convert("RGB")
45
+ image_np = np.array(image)
46
+
47
+ # ---------- RUN PIPELINE ----------
48
+ metrics = run_image_enhancement(image_np)
49
+
50
+ col1, col2 = st.columns(2)
51
+
52
+ with col1:
53
+ st.subheader("Original")
54
+ st.image(image_np, use_container_width=True)
55
+
56
+ with col2:
57
+ st.subheader(f"Enhanced ({mode})")
58
+
59
+ # ---------- FIX APPLIED ONLY ----------
60
+ result_img = safe_uint8(metrics["result"])
61
+
62
+ st.image(result_img, use_container_width=True)
63
+
64
  st.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ # =================================================
67
+ # METRICS
68
+ # =================================================
69
+ m1, m2, m3 = st.columns(3)
70
+ m1.metric("Sequential", f"{metrics['sequential_time']:.4f}s")
71
+ m2.metric("Parallel", f"{metrics['parallel_time']:.4f}s")
72
+ m3.metric("Speedup", f"{metrics['speedup']:.2f}x")
73
+
74
+ # =================================================
75
+ # PLOT
76
+ # =================================================
77
+ fig = go.Figure(data=[
78
+ go.Bar(name='Sequential', x=['Time'], y=[metrics['sequential_time']]),
79
+ go.Bar(name='Parallel', x=['Time'], y=[metrics['parallel_time']])
80
+ ])
81
+
82
+ st.plotly_chart(fig, use_container_width=True)
83
+
84
+ # =================================================
85
+ # DOWNLOAD
86
+ # =================================================
87
+ result_pil = Image.fromarray(safe_uint8(result_img))
88
+
89
+ buf = io.BytesIO()
90
+ result_pil.save(buf, format="PNG")
91
+ buf.seek(0)
92
+
93
+ st.download_button(
94
+ label="Download Enhanced Image",
95
+ data=buf,
96
+ file_name="enhanced.png",
97
+ mime="image/png"
98
+ )
99
+
100
+ # =====================================================
101
+ # LOL DATASET EXPLORER
102
+ # =====================================================
103
  elif app_mode == "LOL Dataset Explorer":
104
+
105
+ st.header("LOL Dataset Explorer")
106
+
107
  samples = get_lol_dataset_samples()
108
+
109
  if not samples:
110
+ st.warning("Dataset not found")
111
+ return
112
+
113
+ selected = st.selectbox("Select Sample", [s['name'] for s in samples])
114
+ sample = next(s for s in samples if s['name'] == selected)
115
+
116
+ low, high = load_lol_pair(sample)
117
+
118
+ col1, col2, col3 = st.columns(3)
119
+
120
+ col1.image(low, caption="Low", use_container_width=True)
121
+ col2.image(high, caption="Ground Truth", use_container_width=True)
122
+
123
+ enhanced = enhancement_pipeline(low, {
124
+ "gamma_enable": True,
125
+ "gamma": gamma_val,
126
+ "clahe_enable": True,
127
+ "clahe_clip": clahe_clip,
128
+ "denoise_enable": True,
129
+ "denoise_h": denoise_h,
130
+ "sharpen_enable": True
131
+ })
 
 
 
 
132
 
133
+ # ---------- FIX APPLIED ONLY ----------
134
+ enhanced = safe_uint8(enhanced)
135
+
136
+ col3.image(enhanced, caption="Enhanced", use_container_width=True)
137
+
138
+ # =====================================================
139
+ # WEBCAM MODE
140
+ # =====================================================
141
  elif app_mode == "Webcam Live":
142
+
143
+ st.header("Webcam Enhancement")
144
+
145
+ img_file = st.camera_input("Capture Image")
146
+
147
+ if img_file:
148
+
149
+ img = Image.open(img_file).convert("RGB")
150
  img_np = np.array(img)
 
 
 
151
 
152
+ result = run_image_enhancement(img_np)
153
+
154
+ output = result["result"]
155
+
156
+ # ---------- FIX APPLIED ONLY ----------
157
+ output = safe_uint8(output)
158
+
159
+ st.image(output, use_container_width=True)
160
+
161
+ # =====================================================
162
+ # PROJECT REPORT
163
+ # =====================================================
164
  elif app_mode == "Project Report":
165
+
166
  if os.path.exists("README.md"):
167
  with open("README.md", "r") as f:
168
  st.markdown(f.read())
169
  else:
170
+ st.error("README not found")
171
 
172
+
173
+ # ---------------------------------------------------------
174
+ # RUN
175
+ # ---------------------------------------------------------
176
  if __name__ == "__main__":
177
+ main()