A1mal commited on
Commit
a9de7ea
·
verified ·
1 Parent(s): f93c2d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -71
app.py CHANGED
@@ -1,78 +1,218 @@
1
- import os
2
- import numpy as np
3
- import cv2
4
  import streamlit as st
 
 
 
5
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # -----------------------------
8
- # ADAPTIVE PIPELINE
9
- # -----------------------------
10
- def enhancement_pipeline(img, config=None):
11
-
12
- if config is None:
13
- config = {}
14
-
15
- img = np.array(img).astype(np.float32)
16
- brightness = np.mean(img)
17
-
18
- # Bright image → no change
19
- if brightness > 160:
20
- return img.astype(np.uint8)
21
-
22
- # Medium light
23
- if brightness > 100:
24
- gamma = 1.1
25
- apply_clahe = False
26
- else:
27
- gamma = config.get("gamma", 1.3)
28
- apply_clahe = config.get("clahe_enable", True)
29
-
30
- # Gamma correction
31
- img = img / 255.0
32
- img = np.power(img, gamma) * 255.0
33
- img = np.clip(img, 0, 255).astype(np.uint8)
34
-
35
- # CLAHE only for dark images
36
- if apply_clahe:
37
- lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
38
- l, a, b = cv2.split(lab)
39
-
40
- clahe = cv2.createCLAHE(2.0, (8, 8))
41
- l = clahe.apply(l)
42
-
43
- img = cv2.merge((l, a, b))
44
- img = cv2.cvtColor(img, cv2.COLOR_LAB2RGB)
45
-
46
- return np.clip(img, 0, 255).astype(np.uint8)
47
-
48
-
49
- # -----------------------------
50
- # STREAMLIT APP
51
- # -----------------------------
52
  def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- st.title("Low Light Enhancement System")
55
-
56
- uploaded = st.file_uploader("Upload Image", type=["jpg", "png", "jpeg"])
57
-
58
- if uploaded is not None:
59
-
60
- img = Image.open(uploaded).convert("RGB")
61
- img_np = np.array(img)
62
-
63
- result = enhancement_pipeline(img_np, {
64
- "gamma": 1.2,
65
- "clahe_enable": True
66
- })
67
-
68
- col1, col2 = st.columns(2)
69
-
70
- col1.image(img_np, caption="Original")
71
- col2.image(result, caption="Enhanced")
72
-
73
-
74
- # -----------------------------
75
- # RUN
76
- # -----------------------------
77
  if __name__ == "__main__":
78
  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()