A1mal commited on
Commit
2100677
·
verified ·
1 Parent(s): 58cc6af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -221
app.py CHANGED
@@ -1,265 +1,115 @@
1
- import tensorflow as tf
2
- from tensorflow.keras.models import load_model
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
- import io
10
- import os
11
- import multiprocessing
12
-
13
- from modules.enhance import enhancement_pipeline, detect_brightness
14
- from modules.parallel import parallel_enhancement
15
- from modules.metrics import calculate_execution_metrics, get_image_info
16
- from modules.dataset_loader import get_lol_dataset_samples, load_lol_pair
17
-
18
- # ---------------------------------------------------------
19
- # LOAD MODEL
20
- # ---------------------------------------------------------
21
- model = load_model("lowlight_enhancer.keras")
22
 
23
  # ---------------------------------------------------------
24
- # AI ENHANCEMENT (FIXED PROPERLY)
25
  # ---------------------------------------------------------
26
- def model_enhance(img):
27
- h, w = img.shape[:2]
28
 
29
- img_resized = cv2.resize(img, (128,128))
30
- img_resized = img_resized / 255.0
31
 
32
- pred = model.predict(np.expand_dims(img_resized, axis=0), verbose=0)[0]
33
- pred = (pred * 255).astype(np.uint8)
 
 
34
 
35
- pred = cv2.resize(pred, (w, h))
36
 
37
- # 🔥 Better than sharpening (reduces blur properly)
38
- pred = cv2.detailEnhance(pred, sigma_s=10, sigma_r=0.15)
39
-
40
- return pred
41
 
42
  # ---------------------------------------------------------
43
- # UI CONFIG
44
  # ---------------------------------------------------------
45
- st.set_page_config(
46
- page_title="Parallel Low Light Image Enhancement",
47
- page_icon="⚡",
48
- layout="wide"
49
- )
50
 
51
- st.markdown("""
52
- <style>
53
- .stMetric {
54
- background-color: #1a1c24;
55
- padding: 20px;
56
- border-radius: 12px;
57
- border: 1px solid #30363d;
58
- }
59
- </style>
60
- """, unsafe_allow_html=True)
61
 
62
  # ---------------------------------------------------------
63
- # SIDEBAR
64
  # ---------------------------------------------------------
65
- st.sidebar.title("⚡ PLL-SIE System")
66
 
67
- app_mode = st.sidebar.selectbox(
68
- "Navigation",
69
- ["Image Workspace", "LOL Dataset Explorer", "Webcam Live", "Project Report"]
70
- )
71
-
72
- if app_mode != "Project Report":
73
- st.sidebar.subheader("Enhancement Parameters")
74
-
75
- gamma_val = st.sidebar.slider("Gamma", 0.5, 4.0, 1.8, 0.1)
76
- clahe_clip = st.sidebar.slider("CLAHE", 1.0, 10.0, 3.0, 0.5)
77
- denoise_h = st.sidebar.slider("Denoise", 0, 30, 12)
78
-
79
- st.sidebar.markdown("---")
80
-
81
- cpu_count = multiprocessing.cpu_count()
82
- parallel_cores = st.sidebar.number_input(
83
- "CPU Cores",
84
- 1,
85
- cpu_count,
86
- max(1, cpu_count-1)
87
- )
88
 
89
- st.sidebar.markdown("---")
90
- st.sidebar.subheader("Processing Mode")
91
-
92
- mode = st.sidebar.selectbox(
93
- "Select Method",
94
- ["Parallel (CPU)", "Sequential", "AI Model"]
95
- )
96
 
97
  # ---------------------------------------------------------
98
- # CORE FUNCTION (FIXED CONFIG + PARALLEL)
99
  # ---------------------------------------------------------
100
- def run_image_enhancement(input_img):
101
-
102
- config = {
103
- "gamma_enable": True,
104
- "gamma": gamma_val,
105
- "clahe_enable": True,
106
- "clahe_clip": clahe_clip,
107
- "denoise_enable": True,
108
- "denoise_h": denoise_h,
109
- "sharpen_enable": True,
110
- "cores": parallel_cores
111
- }
112
-
113
- # AI MODEL
114
- if mode == "AI Model":
115
- start = time.time()
116
- result = model_enhance(input_img)
117
- exec_time = time.time() - start
118
 
119
- return {
120
- "result": result,
121
- "sequential_time": exec_time,
122
- "parallel_time": exec_time,
123
- "speedup": 1.0
124
- }
125
 
126
- # SEQUENTIAL
127
- elif mode == "Sequential":
128
- start = time.time()
129
- result = enhancement_pipeline(input_img, config)
130
- seq_time = time.time() - start
131
 
132
- return {
133
- "result": result,
134
- "sequential_time": seq_time,
135
- "parallel_time": seq_time,
136
- "speedup": 1.0
137
- }
138
-
139
- # PARALLEL
140
- else:
141
- return calculate_execution_metrics(
142
- enhancement_pipeline,
143
- parallel_enhancement,
144
- input_img,
145
- config
146
- )
147
 
148
  # ---------------------------------------------------------
149
- # MAIN APP
150
  # ---------------------------------------------------------
151
- def main():
152
-
153
- if app_mode == "Image Workspace":
154
- st.header("Image Enhancement Workspace")
155
-
156
- uploaded_file = st.file_uploader(
157
- "Upload Image",
158
- type=['jpg', 'png', 'jpeg']
159
- )
160
-
161
- if uploaded_file:
162
- img = Image.open(uploaded_file).convert("RGB")
163
- img_np = np.array(img)
164
-
165
- info = get_image_info(img_np)
166
- brightness = detect_brightness(img_np)
167
-
168
- c1, c2, c3 = st.columns(3)
169
-
170
- c1.metric("Brightness", f"{brightness:.1f}")
171
- c2.metric("Megapixels", f"{info['megapixels']:.2f}")
172
- c3.metric("Status", "Low Light" if brightness < 70 else "Normal")
173
-
174
- if st.button("Run Enhancement"):
175
- with st.spinner("Processing..."):
176
- metrics = run_image_enhancement(img_np)
177
-
178
- col1, col2 = st.columns(2)
179
-
180
- with col1:
181
- st.subheader("Original")
182
- st.image(img_np)
183
 
184
- with col2:
185
- st.subheader(f"Enhanced ({mode})")
186
- st.image(metrics['result'])
187
 
188
- st.markdown("---")
189
 
190
- m1, m2, m3 = st.columns(3)
191
- m1.metric("Sequential", f"{metrics['sequential_time']:.4f}s")
192
- m2.metric("Parallel", f"{metrics['parallel_time']:.4f}s")
193
- m3.metric("Speedup", f"{metrics['speedup']:.2f}x")
194
-
195
- fig = go.Figure(data=[
196
- go.Bar(name='Sequential', x=['Time'], y=[metrics['sequential_time']]),
197
- go.Bar(name='Parallel', x=['Time'], y=[metrics['parallel_time']])
198
- ])
199
- st.plotly_chart(fig)
200
-
201
- result_pil = Image.fromarray(metrics['result'])
202
- buf = io.BytesIO()
203
- result_pil.save(buf, format="PNG")
204
-
205
- st.download_button(
206
- "Download Image",
207
- buf.getvalue(),
208
- "enhanced.png"
209
- )
210
-
211
- elif app_mode == "LOL Dataset Explorer":
212
- st.header("LOL Dataset Explorer")
213
-
214
- samples = get_lol_dataset_samples()
215
 
216
- if not samples:
217
- st.warning("Dataset not found")
218
- else:
219
- selected = st.selectbox("Select Sample", [s['name'] for s in samples])
220
- sample = next(s for s in samples if s['name'] == selected)
221
 
222
- low, high = load_lol_pair(sample)
223
 
224
- col1, col2, col3 = st.columns(3)
 
225
 
226
- col1.image(low, caption="Low")
227
- col2.image(high, caption="Ground Truth")
 
 
 
 
 
 
 
228
 
229
- enhanced = enhancement_pipeline(low, {
230
- "gamma_enable": True,
231
- "gamma": gamma_val,
232
- "clahe_enable": True,
233
- "clahe_clip": clahe_clip,
234
- "denoise_enable": True,
235
- "denoise_h": denoise_h,
236
- "sharpen_enable": True
237
- })
238
 
239
- col3.image(enhanced, caption="Enhanced")
240
 
241
- elif app_mode == "Webcam Live":
242
- st.header("Webcam Enhancement")
 
243
 
244
- img_file = st.camera_input("Capture Image")
 
245
 
246
- if img_file:
247
- img = Image.open(img_file)
248
- img_np = np.array(img)
249
 
250
- result = run_image_enhancement(img_np)
 
 
251
 
252
- st.image(result['result'])
253
 
254
- elif app_mode == "Project Report":
255
- if os.path.exists("README.md"):
256
- with open("README.md", "r") as f:
257
- st.markdown(f.read())
258
- else:
259
- st.error("README not found")
260
 
261
- # ---------------------------------------------------------
262
- # RUN
263
- # ---------------------------------------------------------
264
- if __name__ == "__main__":
265
- main()
 
1
+ import io
 
 
 
2
  import numpy as np
 
3
  from PIL import Image
4
  import plotly.graph_objects as go
5
+ import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # ---------------------------------------------------------
8
+ # RESULT DISPLAY
9
  # ---------------------------------------------------------
 
 
10
 
11
+ with col2:
12
+ st.subheader(f"Enhanced ({mode})")
13
 
14
+ # Ensure correct dtype + color format
15
+ result_img = metrics['result']
16
+ if isinstance(result_img, np.ndarray):
17
+ result_img = np.clip(result_img, 0, 255).astype(np.uint8)
18
 
19
+ st.image(result_img, use_container_width=True)
20
 
21
+ st.markdown("---")
 
 
 
22
 
23
  # ---------------------------------------------------------
24
+ # METRICS
25
  # ---------------------------------------------------------
 
 
 
 
 
26
 
27
+ m1, m2, m3 = st.columns(3)
28
+ m1.metric("Sequential", f"{metrics['sequential_time']:.4f}s")
29
+ m2.metric("Parallel", f"{metrics['parallel_time']:.4f}s")
30
+ m3.metric("Speedup", f"{metrics['speedup']:.2f}x")
 
 
 
 
 
 
31
 
32
  # ---------------------------------------------------------
33
+ # PLOTLY CHART
34
  # ---------------------------------------------------------
 
35
 
36
+ fig = go.Figure(data=[
37
+ go.Bar(name='Sequential', x=['Time'], y=[metrics['sequential_time']]),
38
+ go.Bar(name='Parallel', x=['Time'], y=[metrics['parallel_time']])
39
+ ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
 
42
 
43
  # ---------------------------------------------------------
44
+ # DOWNLOAD BUTTON (FIXED BUFFER HANDLING)
45
  # ---------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ result_pil = Image.fromarray(np.uint8(result_img))
 
 
 
 
 
48
 
49
+ buf = io.BytesIO()
50
+ result_pil.save(buf, format="PNG")
51
+ buf.seek(0) # 🔴 IMPORTANT FIX
 
 
52
 
53
+ st.download_button(
54
+ label="Download Image",
55
+ data=buf,
56
+ file_name="enhanced.png",
57
+ mime="image/png"
58
+ )
 
 
 
 
 
 
 
 
 
59
 
60
  # ---------------------------------------------------------
61
+ # LOL DATASET EXPLORER
62
  # ---------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ elif app_mode == "LOL Dataset Explorer":
65
+ st.header("LOL Dataset Explorer")
 
66
 
67
+ samples = get_lol_dataset_samples()
68
 
69
+ if not samples:
70
+ st.warning("Dataset not found")
71
+ else:
72
+ selected = st.selectbox("Select Sample", [s['name'] for s in samples])
73
+ sample = next(s for s in samples if s['name'] == selected)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ low, high = load_lol_pair(sample)
 
 
 
 
76
 
77
+ col1, col2, col3 = st.columns(3)
78
 
79
+ col1.image(low, caption="Low", use_container_width=True)
80
+ col2.image(high, caption="Ground Truth", use_container_width=True)
81
 
82
+ enhanced = enhancement_pipeline(low, {
83
+ "gamma_enable": True,
84
+ "gamma": gamma_val,
85
+ "clahe_enable": True,
86
+ "clahe_clip": clahe_clip,
87
+ "denoise_enable": True,
88
+ "denoise_h": denoise_h,
89
+ "sharpen_enable": True
90
+ })
91
 
92
+ # FIX: ensure proper format
93
+ enhanced = np.clip(enhanced, 0, 255).astype(np.uint8)
 
 
 
 
 
 
 
94
 
95
+ col3.image(enhanced, caption="Enhanced", use_container_width=True)
96
 
97
+ # ---------------------------------------------------------
98
+ # WEBCAM MODE
99
+ # ---------------------------------------------------------
100
 
101
+ elif app_mode == "Webcam Live":
102
+ st.header("Webcam Enhancement")
103
 
104
+ img_file = st.camera_input("Capture Image")
 
 
105
 
106
+ if img_file:
107
+ img = Image.open(img_file).convert("RGB")
108
+ img_np = np.array(img)
109
 
110
+ result = run_image_enhancement(img_np)
111
 
112
+ output = result['result']
113
+ output = np.clip(output, 0, 255).astype(np.uint8)
 
 
 
 
114
 
115
+ st.image(output, use_container_width=True)