File size: 12,739 Bytes
2232b2c |
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 |
# import gradio as gr
# import torch
# import os
# import tempfile
# import shutil
# from PIL import Image
# import numpy as np
# from pathlib import Path
# import sys
# import copy
# # --- Import logic from your project ---
# from options.test_options import TestOptions
# from data import create_dataset
# from models import create_model
# try:
# from best_ldr import compute_metrics_for_images, score_records
# except ImportError:
# raise ImportError("Could not import from best_ldr.py. Make sure the file is in the same directory as app.py.")
# print("--- Initializing LDR-to-HDR Model (this may take a moment) ---")
# # --- Global Setup: Load the CycleGAN model once when the app starts ---
# # We need to satisfy the parser's requirement for a dataroot at startup
# if '--dataroot' not in sys.argv:
# sys.argv.extend(['--dataroot', './dummy_dataroot_for_init'])
# # Load the base options
# opt = TestOptions().parse()
# # Manually override settings for our model
# opt.name = 'ldr2hdr_cyclegan_728'
# opt.model = 'test'
# opt.netG = 'resnet_9blocks'
# opt.norm = 'instance'
# opt.no_dropout = True
# opt.checkpoints_dir = './checkpoints'
# opt.gpu_ids = [0] if torch.cuda.is_available() else []
# opt.device = torch.device('cuda:{}'.format(opt.gpu_ids[0])) if opt.gpu_ids else torch.device('cpu')
# # Create the model using these options
# model = create_model(opt)
# model.setup(opt)
# model.eval()
# print("--- Model Loaded Successfully ---")
# # --- Helper Function for Inference ---
# def run_inference(model, image_path, process_options):
# """
# A reusable function to run the model with specific preprocessing options.
# """
# # Deep copy the base options to avoid modifying the global state
# local_opt = copy.deepcopy(opt)
# # Apply the specific settings for this run
# for key, value in process_options.items():
# setattr(local_opt, key, value)
# with tempfile.TemporaryDirectory() as temp_dir:
# shutil.copy(image_path, temp_dir)
# local_opt.dataroot = temp_dir
# local_opt.num_test = 1
# dataset = create_dataset(local_opt)
# for i, data in enumerate(dataset):
# model.set_input(data)
# model.test()
# visuals = model.get_current_visuals()
# for label, image_tensor in visuals.items():
# if label == 'fake':
# image_numpy = (np.transpose(image_tensor.cpu().float().numpy()[0], (1, 2, 0)) + 1) / 2.0 * 255.0
# return Image.fromarray(image_numpy.astype(np.uint8))
# # --- The Main Gradio Processing Function ---
# def process_images_and_display(list_of_temp_files):
# """
# The main workflow: select best LDR, then run two inference modes.
# """
# if not list_of_temp_files:
# raise gr.Error("Please upload your bracketed LDR images.")
# if len(list_of_temp_files) < 2:
# gr.Warning("For best results, upload at least 2 bracketed LDR images.")
# uploaded_filepaths = [Path(f.name) for f in list_of_temp_files]
# try:
# # --- Step 1: Select the Best LDR ---
# print(f"Analyzing {len(uploaded_filepaths)} uploaded images...")
# weights = {"clipped": 0.35, "coverage": 0.25, "exposure": 0.15, "sharpness": 0.15, "noise": 0.10}
# records = compute_metrics_for_images(uploaded_filepaths, resize_max=1024)
# scored_records = score_records(records, weights)
# if not scored_records:
# raise gr.Error("Could not read or score any of the uploaded images.")
# best_ldr_record = scored_records[0]
# best_ldr_path = best_ldr_record['path']
# print(f"Best LDR selected: {os.path.basename(best_ldr_path)} (Score: {best_ldr_record['score']:.4f})")
# chosen_ldr_image = Image.open(best_ldr_path).convert("RGB")
# # --- Step 2: Run Inference in Both Modes ---
# # Mode A: High-Quality Crop (at model's native resolution)
# print("Running Mode A: High-Quality Crop...")
# crop_options = {
# 'preprocess': 'resize_and_crop',
# 'load_size': 728,
# 'crop_size': 728
# }
# hdr_cropped = run_inference(model, best_ldr_path, crop_options)
# print("Mode A successful.")
# # Mode B: Full Image (at a higher resolution)
# print("Running Mode B: Full Image (High-Res Scaled)...")
# scale_options = {
# 'preprocess': 'scale_width',
# 'load_size': 1024, # <-- THIS IS THE CHANGE FOR HIGHER RESOLUTION
# 'crop_size': 728 # This value is ignored by scale_width but needs to be present
# }
# hdr_scaled = run_inference(model, best_ldr_path, scale_options)
# print("Mode B successful.")
# # Return all the images to update the UI
# return uploaded_filepaths, chosen_ldr_image, hdr_cropped, hdr_scaled
# except Exception as e:
# print(f"An error occurred: {e}")
# raise gr.Error(f"An error occurred during processing: {e}")
# # --- Create and Launch the Gradio Interface ---
# with gr.Blocks(theme=gr.themes.Monochrome(), css="footer {display: none !important}") as demo:
# gr.Markdown("# LDR Bracketing to HDR Converter")
# gr.Markdown("Upload a set of bracketed LDR images. The app will automatically select the best one and convert it to HDR using two different methods for comparison.")
# with gr.Row():
# with gr.Column(scale=1, min_width=300):
# input_files = gr.Files(
# label="Upload Bracketed LDR Images",
# file_types=["image"]
# )
# process_button = gr.Button("Process Images", variant="primary")
# with gr.Accordion("See Your Uploads", open=False):
# input_gallery = gr.Gallery(label="Uploaded LDR Bracket", show_label=False, columns=3, height="auto")
# with gr.Column(scale=2):
# gr.Markdown("## Results")
# with gr.Row():
# chosen_ldr_display = gr.Image(label="Best LDR Chosen by Algorithm", type="pil", interactive=False)
# with gr.Row():
# output_cropped = gr.Image(label="Result 1: High-Quality Crop (728x728)", type="pil", interactive=False)
# output_scaled = gr.Image(label="Result 2: Full Image (Scaled to 1024px Width)", type="pil", interactive=False)
# process_button.click(
# fn=process_images_and_display,
# inputs=input_files,
# outputs=[input_gallery, chosen_ldr_display, output_cropped, output_scaled]
# )
# print("--- Launching Gradio App ---")
# demo.launch(share=True)
import gradio as gr
import torch
import os
import tempfile
import shutil
from PIL import Image
import numpy as np
from pathlib import Path
import sys
import copy
# --- Import logic from your project ---
from options.test_options import TestOptions
from data import create_dataset
from models import create_model
try:
from best_ldr import compute_metrics_for_images, score_records
except ImportError:
raise ImportError("Could not import from best_ldr.py. Make sure the file is in the same directory as app.py.")
print("--- Initializing LDR-to-HDR Model (this may take a moment) ---")
# --- Global Setup: Load the CycleGAN model once when the app starts ---
# We need to satisfy the parser's requirement for a dataroot at startup
if '--dataroot' not in sys.argv:
sys.argv.extend(['--dataroot', './dummy_dataroot_for_init'])
# Load the base options
opt = TestOptions().parse()
# Manually override settings for our model
opt.name = 'ldr2hdr_cyclegan_728'
opt.model = 'test'
opt.netG = 'resnet_9blocks'
opt.norm = 'instance'
opt.no_dropout = True
opt.checkpoints_dir = './checkpoints'
opt.gpu_ids = [0] if torch.cuda.is_available() else []
opt.device = torch.device('cuda:{}'.format(opt.gpu_ids[0])) if opt.gpu_ids else torch.device('cpu')
# Create the model using these options
model = create_model(opt)
model.setup(opt)
model.eval()
print("--- Model Loaded Successfully ---")
# --- The Main Gradio Processing Function ---
def process_images_to_hdr(list_of_temp_files):
"""
The main workflow: select best LDR, run inference, and return results for the UI.
"""
if not list_of_temp_files:
raise gr.Error("Please upload your bracketed LDR images.")
if len(list_of_temp_files) < 2:
gr.Warning("For best results, upload at least 2 bracketed LDR images.")
uploaded_filepaths = [Path(f.name) for f in list_of_temp_files]
try:
# --- Step 1: Select the Best LDR ---
print(f"Analyzing {len(uploaded_filepaths)} uploaded images...")
weights = {"clipped": 0.35, "coverage": 0.25, "exposure": 0.15, "sharpness": 0.15, "noise": 0.10}
records = compute_metrics_for_images(uploaded_filepaths, resize_max=1024)
scored_records = score_records(records, weights)
if not scored_records:
raise gr.Error("Could not read or score any of the uploaded images.")
best_ldr_record = scored_records[0]
best_ldr_path = best_ldr_record['path']
print(f"Best LDR selected: {os.path.basename(best_ldr_path)} (Score: {best_ldr_record['score']:.4f})")
# --- Step 2: Run Inference ---
print("Running Full Image (High-Res Scaled) Inference...")
# We only need the one set of options now
inference_options = {
'preprocess': 'scale_width',
'load_size': 1024, # Generate the high-resolution, full image
'crop_size': 728 # This value is ignored but required by the parser
}
# Deep copy the base options to avoid modifying the global state
local_opt = copy.deepcopy(opt)
for key, value in inference_options.items():
setattr(local_opt, key, value)
# Run the model
with tempfile.TemporaryDirectory() as temp_dir:
shutil.copy(best_ldr_path, temp_dir)
local_opt.dataroot = temp_dir
local_opt.num_test = 1
dataset = create_dataset(local_opt)
for i, data in enumerate(dataset):
model.set_input(data)
model.test()
visuals = model.get_current_visuals()
for label, image_tensor in visuals.items():
if label == 'fake':
image_numpy = (np.transpose(image_tensor.cpu().float().numpy()[0], (1, 2, 0)) + 1) / 2.0 * 255.0
final_hdr_image = Image.fromarray(image_numpy.astype(np.uint8))
print("Conversion to HDR successful.")
# Return the gallery of inputs and the single final HDR image
return uploaded_filepaths, final_hdr_image
except Exception as e:
print(f"An error occurred: {e}")
raise gr.Error(f"An error occurred during processing: {e}")
# --- Create and Launch the Gradio Interface ---
with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo:
gr.Markdown(
"""
# LDR Bracketing to HDR Converter
Upload a set of bracketed LDR images. The app will automatically select the best one and convert it to a vibrant, full-resolution HDR image.
"""
)
with gr.Row():
with gr.Column(scale=1, min_width=350):
# --- INPUT ---
input_files = gr.Files(
label="Upload Bracketed LDR Images",
file_types=["image"]
)
process_button = gr.Button("Process Images", variant="primary")
with gr.Accordion("See Your Uploaded Images", open=True):
input_gallery = gr.Gallery(label="Uploaded Images", show_label=False, columns=[2, 3], height="auto")
with gr.Column(scale=2):
# --- OUTPUT ---
gr.Markdown("## Generated HDR Result")
output_image = gr.Image(label="Final HDR Image", type="pil", interactive=False, show_download_button=True)
process_button.click(
fn=process_images_to_hdr,
inputs=input_files,
outputs=[input_gallery, output_image]
)
# gr.Markdown("### Examples")
# gr.Examples(
# examples=[
# [
# "../pix2pix_dataset/testA/077A2406.jpg",
# "../pix2pix_dataset/testA/077A4049.jpg",
# "../pix2pix_dataset/testA/077A4073.jpg"
# ]
# ],
# inputs=input_files
# )
print("--- Launching Gradio App ---")
demo.launch(share=True) |