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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -147
app.py CHANGED
@@ -1,175 +1,218 @@
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
- # MAIN APP
14
  # ---------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- st.title("Low Light Image Enhancement System")
 
 
19
 
20
- app_mode = st.sidebar.selectbox(
21
- "Choose Mode",
22
- ["Single Image Enhancement", "LOL Dataset Explorer", "Webcam Live", "Project Report"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  )
 
 
24
 
25
- # =====================================================
26
- # SINGLE IMAGE ENHANCEMENT
27
- # =====================================================
28
- if app_mode == "Single Image Enhancement":
29
-
30
- uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
31
-
32
- if uploaded_file is not None:
33
-
34
- # ---------- SAFE IMAGE LOAD ----------
35
- image = Image.open(uploaded_file).convert("RGB")
36
- image_np = np.array(image)
37
-
38
- # ---------- RUN PIPELINE ----------
39
- metrics = run_image_enhancement(image_np)
40
-
41
- col1, col2 = st.columns(2)
42
-
43
- with col1:
44
- st.subheader("Original")
45
- st.image(image_np, use_container_width=True)
46
-
47
- with col2:
48
- st.subheader(f"Enhanced ({mode})")
49
-
50
- # ---------- CRITICAL FIX: SAFE OUTPUT ----------
51
- result_img = metrics["result"]
52
-
53
- if isinstance(result_img, np.ndarray):
54
- result_img = np.nan_to_num(result_img) # remove NaNs/Infs
55
- result_img = np.clip(result_img, 0, 255)
56
- result_img = result_img.astype(np.uint8)
57
-
58
- st.image(result_img, use_container_width=True)
59
-
60
  st.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- # =================================================
63
- # METRICS
64
- # =================================================
65
- m1, m2, m3 = st.columns(3)
66
- m1.metric("Sequential", f"{metrics['sequential_time']:.4f}s")
67
- m2.metric("Parallel", f"{metrics['parallel_time']:.4f}s")
68
- m3.metric("Speedup", f"{metrics['speedup']:.2f}x")
69
-
70
- # =================================================
71
- # PLOT
72
- # =================================================
73
- fig = go.Figure(data=[
74
- go.Bar(name='Sequential', x=['Time'], y=[metrics['sequential_time']]),
75
- go.Bar(name='Parallel', x=['Time'], y=[metrics['parallel_time']])
76
- ])
77
-
78
- st.plotly_chart(fig, use_container_width=True)
79
-
80
- # =================================================
81
- # DOWNLOAD
82
- # =================================================
83
- result_pil = Image.fromarray(result_img)
84
-
85
- buf = io.BytesIO()
86
- result_pil.save(buf, format="PNG")
87
- buf.seek(0)
88
-
89
- st.download_button(
90
- label="Download Enhanced Image",
91
- data=buf,
92
- file_name="enhanced.png",
93
- mime="image/png"
94
- )
95
-
96
- # =====================================================
97
- # LOL DATASET EXPLORER
98
- # =====================================================
99
  elif app_mode == "LOL Dataset Explorer":
100
-
101
- st.header("LOL Dataset Explorer")
102
-
103
  samples = get_lol_dataset_samples()
104
-
105
  if not samples:
106
- st.warning("Dataset not found")
107
- return
108
-
109
- selected = st.selectbox("Select Sample", [s['name'] for s in samples])
110
- sample = next(s for s in samples if s['name'] == selected)
111
-
112
- low, high = load_lol_pair(sample)
113
-
114
- col1, col2, col3 = st.columns(3)
115
-
116
- col1.image(low, caption="Low", use_container_width=True)
117
- col2.image(high, caption="Ground Truth", use_container_width=True)
118
-
119
- enhanced = enhancement_pipeline(low, {
120
- "gamma_enable": True,
121
- "gamma": gamma_val,
122
- "clahe_enable": True,
123
- "clahe_clip": clahe_clip,
124
- "denoise_enable": True,
125
- "denoise_h": denoise_h,
126
- "sharpen_enable": True
127
- })
128
-
129
- # ---------- CRITICAL FIX ----------
130
- enhanced = np.nan_to_num(enhanced)
131
- enhanced = np.clip(enhanced, 0, 255).astype(np.uint8)
132
-
133
- col3.image(enhanced, caption="Enhanced", use_container_width=True)
134
 
135
- # =====================================================
136
- # WEBCAM MODE
137
- # =====================================================
138
  elif app_mode == "Webcam Live":
139
-
140
- st.header("Webcam Enhancement")
141
-
142
- img_file = st.camera_input("Capture Image")
143
-
144
- if img_file:
145
-
146
- img = Image.open(img_file).convert("RGB")
147
  img_np = np.array(img)
 
 
 
148
 
149
- result = run_image_enhancement(img_np)
150
-
151
- output = result["result"]
152
-
153
- # ---------- FIX ----------
154
- output = np.nan_to_num(output)
155
- output = np.clip(output, 0, 255).astype(np.uint8)
156
-
157
- st.image(output, use_container_width=True)
158
-
159
- # =====================================================
160
- # PROJECT REPORT
161
- # =====================================================
162
  elif app_mode == "Project Report":
163
-
164
  if os.path.exists("README.md"):
165
  with open("README.md", "r") as f:
166
  st.markdown(f.read())
167
  else:
168
- st.error("README not found")
169
 
170
-
171
- # ---------------------------------------------------------
172
- # RUN
173
- # ---------------------------------------------------------
174
  if __name__ == "__main__":
175
- main()
 
 
 
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()