-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathluminance_stack_processor.py
More file actions
2307 lines (1870 loc) · 112 KB
/
luminance_stack_processor.py
File metadata and controls
2307 lines (1870 loc) · 112 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Luminance Stack Processor - Professional ComfyUI Custom Nodes
Implements HDR processing using the Debevec Algorithm for multiple exposure fusion
Author: Sumit Chatterjee
Version: 1.1.8
Semantic Versioning: MAJOR.MINOR.PATCH
"""
import numpy as np
import torch
import cv2
from typing import Tuple, List, Optional
import logging
import os
# Try to import HDRutils for alternative HDR processing
try:
import HDRutils
HDRUTILS_AVAILABLE = True
except ImportError:
HDRUTILS_AVAILABLE = False
# Try to import imageio for HDR/EXR support
try:
import imageio.v3 as iio
IMAGEIO_AVAILABLE = True
except ImportError:
try:
import imageio as iio
IMAGEIO_AVAILABLE = True
except ImportError:
IMAGEIO_AVAILABLE = False
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def tensor_to_cv2(tensor: torch.Tensor) -> np.ndarray:
"""Convert ComfyUI tensor to OpenCV format for HDR processing
IMPORTANT: OpenCV's Debevec and Robertson algorithms expect 8-bit sRGB images as input.
They internally recover the camera response function, so we should NOT pre-linearize the images.
"""
# ComfyUI tensors are typically [B, H, W, C] in 0-1 range
if len(tensor.shape) == 4:
tensor = tensor.squeeze(0) # Remove batch dimension
# Convert to numpy
image = tensor.cpu().numpy()
# Convert to 8-bit sRGB (no gamma correction - Debevec/Robertson expect sRGB input)
image_8bit = np.clip(image * 255.0, 0, 255).astype(np.uint8)
logger.info(f"Converted to OpenCV: shape={image_8bit.shape}, dtype={image_8bit.dtype}, range=[{image_8bit.min()}, {image_8bit.max()}]")
return image_8bit
def cv2_to_tensor(hdr_image: np.ndarray, output_16bit_linear: bool = True, algorithm_hint: str = "unknown") -> torch.Tensor:
"""Convert OpenCV HDR image to ComfyUI tensor format - VFX pipeline friendly"""
if output_16bit_linear:
logger.info(f"HDR processing ({algorithm_hint}):")
logger.info(f" Input range: [{hdr_image.min():.6f}, {hdr_image.max():.6f}]")
# VFX PIPELINE APPROACH: Different scaling philosophy per algorithm
if algorithm_hint == "radiance_fusion":
# Radiance Fusion: Perfect HDR preservation with Nuke-style operations
# The plus/average operations already create optimal HDR scaling
hdr_linear = hdr_image
logger.info(f" Radiance Fusion: Direct pass-through (Nuke-style HDR preservation)")
elif algorithm_hint == "natural_blend":
# Natural Blend: Preserve EV0 appearance exactly - NO SCALING
# The algorithm already provides the correctly scaled values
hdr_linear = hdr_image
logger.info(f" Natural Blend: Direct pass-through (preserves EV0 appearance)")
elif algorithm_hint == "detail_injection":
# Detail Injection: Preserve the exact values from the algorithm
# Already in linear space with HDR values properly mapped
hdr_linear = hdr_image
logger.info(f" Detail Injection: Direct pass-through (linear space with HDR detail)")
elif algorithm_hint == "mertens":
# Mertens: Medium HDR range, values 1-10 range
p85 = np.percentile(hdr_image, 85.0)
if p85 > 0:
hdr_linear = hdr_image * (3.0 / p85)
else:
hdr_linear = hdr_image * 3.0
hdr_linear = np.clip(hdr_linear, 0.0, 12.0)
elif algorithm_hint in ["debevec", "robertson"]:
# PURE HDR: Direct pass-through of calibrated linear radiance
# No post-processing - the calibrated exposure times handle everything
hdr_linear = hdr_image
logger.info(f" Debevec/Robertson: Direct pass-through (NO post-processing)")
logger.info(f" Pure linear radiance from calibrated exposure times")
else:
# Unknown algorithm - conservative approach
hdr_linear = np.clip(hdr_image * 2.0, 0.0, 10.0)
logger.info(f" Final HDR range: [{hdr_linear.min():.6f}, {hdr_linear.max():.6f}]")
logger.info(f" Max value: {hdr_linear.max():.2f} (VFX raw data)")
# Convert to ComfyUI format: [1, H, W, C] - NO NORMALIZATION!
if len(hdr_linear.shape) == 3:
tensor = torch.from_numpy(hdr_linear.astype(np.float32)).unsqueeze(0)
else:
tensor = torch.from_numpy(hdr_linear.astype(np.float32))
return tensor.float()
else:
# Standard 8-bit conversion (fallback)
image_8bit = np.clip(hdr_image * 255.0, 0, 255).astype(np.uint8)
normalized = image_8bit.astype(np.float32) / 255.0
if len(normalized.shape) == 3:
tensor = torch.from_numpy(normalized).unsqueeze(0)
else:
tensor = torch.from_numpy(normalized)
return tensor.float()
class DebevecHDRProcessor:
"""Core HDR processing using multiple algorithms"""
def __init__(self):
# CRITICAL: Much higher lambda for ultra-smooth response curves
# Default is ~10, we use 100+ for AI-generated images to prevent quantization
self.calibrator = cv2.createCalibrateDebevec(samples=200, lambda_=100.0)
self.merge_debevec = cv2.createMergeDebevec()
# Alternative algorithms
self.merge_mertens = cv2.createMergeMertens()
self.merge_robertson = cv2.createMergeRobertson()
self.calibrator_robertson = cv2.createCalibrateRobertson()
logger.info("Debevec calibrator configured with ultra-high smoothness (lambda=100.0, samples=200)")
def _apply_gradient_adaptive_dithering(self, hdr_image: np.ndarray) -> np.ndarray:
"""
Apply dithering ONLY to luminance in smooth gradients - preserves color perfectly
This prevents color shifts while breaking up banding
This is the professional approach used in tools like LuminanceHDR and Photoshop
Args:
hdr_image: HDR image in linear space (float32, BGR)
Returns:
HDR image with gradient-adaptive dithering (edges preserved, color preserved)
"""
logger.info("Applying luminance-based gradient-adaptive dithering (color-preserving)...")
# Calculate luminance (Rec. 709)
# Note: hdr_image is in BGR format from OpenCV
luminance = (0.0722 * hdr_image[:, :, 0] + # B
0.7152 * hdr_image[:, :, 1] + # G
0.2126 * hdr_image[:, :, 2]) # R
# Calculate gradient magnitude on luminance
grad_x = cv2.Sobel(luminance, cv2.CV_32F, 1, 0, ksize=3)
grad_y = cv2.Sobel(luminance, cv2.CV_32F, 0, 1, ksize=3)
gradient_magnitude = np.sqrt(grad_x**2 + grad_y**2)
# Normalize gradient
if gradient_magnitude.max() > 0:
gradient_norm = gradient_magnitude / gradient_magnitude.max()
else:
gradient_norm = gradient_magnitude
# Smooth gradients get dithering, edges don't
dither_strength_map = 1.0 - gradient_norm
dither_strength_map = cv2.GaussianBlur(dither_strength_map, (5, 5), 1.0)
# Generate dither for LUMINANCE only (single noise pattern for all channels)
# Much subtler strength to avoid visible noise
adaptive_strength = dither_strength_map * (np.abs(luminance) + 0.01) * 0.0008 # 0.08% instead of 0.3%
# Single noise pattern
noise = np.random.normal(0, 1, luminance.shape).astype(np.float32)
# Apply noise to luminance
luminance_dithered = luminance + noise * adaptive_strength
# Calculate luminance change ratio
# Avoid division by zero
safe_luminance = np.maximum(luminance, 1e-6)
luma_ratio = luminance_dithered / safe_luminance
# Apply same ratio to all color channels - preserves color perfectly!
result = hdr_image.copy()
for c in range(3):
result[:, :, c] = hdr_image[:, :, c] * luma_ratio
# Statistics
smooth_pixels = np.sum(dither_strength_map > 0.5)
total_pixels = dither_strength_map.size
logger.info(f" Luminance dithering: {smooth_pixels}/{total_pixels} smooth pixels ({100*smooth_pixels/total_pixels:.1f}%)")
logger.info(f" Color preservation: 100% (luminance-only dithering)")
logger.info(f" Dither strength: 0.08% (very subtle, imperceptible)")
return result.astype(np.float32)
def _compute_exposure_ratio_srgb(self, reference: np.ndarray, target: np.ndarray) -> float:
"""
Compute the brightness ratio between two exposures IN sRGB SPACE
This matches how Debevec sees the images (8-bit sRGB, not linear)
Args:
reference: Reference image in sRGB space (float32 0-1, BGR)
target: Target image to compare in sRGB space (float32 0-1, BGR)
Returns:
float: Brightness ratio in sRGB space (target/reference)
"""
# Convert to grayscale for analysis
ref_gray = cv2.cvtColor(reference, cv2.COLOR_BGR2GRAY)
tgt_gray = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
# Create mask for well-exposed regions (0.2 to 0.8 in reference)
# These regions are least likely to be clipped in either image
mask = (ref_gray > 0.2) & (ref_gray < 0.8) & (tgt_gray > 0.01) & (tgt_gray < 0.99)
if np.sum(mask) < 1000: # Not enough valid pixels
logger.warning("Insufficient well-exposed pixels for calibration, using full image")
mask = np.ones_like(ref_gray, dtype=bool)
# Compute ratio using median (robust to outliers)
ref_values = ref_gray[mask]
tgt_values = tgt_gray[mask]
# Ratio in sRGB space
ratios = tgt_values / (ref_values + 1e-8)
median_ratio = np.median(ratios)
# Log for debugging
logger.info(f" Valid pixels: {np.sum(mask)}, sRGB ratio range: [{np.percentile(ratios, 10):.3f}, {np.percentile(ratios, 90):.3f}]")
return median_ratio
def _calibrate_exposure_times(self, images: List[np.ndarray], nominal_times: List[float]) -> List[float]:
"""
Analyze AI-generated brackets and compute corrected exposure times
that match their actual brightness relationships IN sRGB SPACE
CRITICAL: Calibrates in sRGB space (NOT linear) because Debevec receives
8-bit sRGB images and estimates the response curve internally.
Args:
images: List of AI-generated exposure brackets (8-bit BGR)
nominal_times: Theoretical exposure times [t+2, t0, t-2, ...]
Returns:
Calibrated exposure times that match AI's actual behavior in sRGB space
"""
logger.info("=" * 60)
logger.info("ADAPTIVE EXPOSURE CALIBRATION (sRGB SPACE)")
logger.info("Analyzing AI-generated brackets as Debevec sees them")
logger.info("=" * 60)
# DON'T convert to linear - work in sRGB space like Debevec does!
# Just normalize to 0-1 range
srgb_images = [img.astype(np.float32) / 255.0 for img in images]
# Find EV0 (reference exposure) - should be in the middle
ev0_idx = len(images) // 2
ev0_srgb = srgb_images[ev0_idx]
logger.info(f"Reference image (EV0): Index {ev0_idx}, Nominal time: {nominal_times[ev0_idx]:.6f}s")
logger.info(f"Working in sRGB space (matching Debevec's input)")
# Compute intensity statistics for each image
calibrated_times = []
for i, img_srgb in enumerate(srgb_images):
if i == ev0_idx:
# Reference exposure - keep as is
calibrated_times.append(nominal_times[ev0_idx])
logger.info(f"Image {i} (EV0 reference): time={nominal_times[ev0_idx]:.6f}s")
continue
# Analyze the brightness relationship in sRGB space
logger.info(f"Calibrating Image {i}:")
srgb_ratio = self._compute_exposure_ratio_srgb(ev0_srgb, img_srgb)
# For AI-generated images, use a hybrid approach:
# Apply a gentler power (1.8 instead of 2.2) as AI doesn't follow perfect sRGB gamma
# This accounts for some gamma relationship without overcorrecting
time_ratio = srgb_ratio ** 1.8
calibrated_time = nominal_times[ev0_idx] * time_ratio
calibrated_times.append(calibrated_time)
expected_ratio = nominal_times[i] / nominal_times[ev0_idx]
adjustment_factor = calibrated_time / nominal_times[i]
logger.info(f" sRGB brightness ratio: {srgb_ratio:.3f}")
logger.info(f" Exposure time ratio (^1.8): {time_ratio:.3f}")
logger.info(f" Expected time ratio: {expected_ratio:.3f}")
logger.info(f" Nominal time: {nominal_times[i]:.6f}s → Calibrated time: {calibrated_time:.6f}s")
logger.info(f" Adjustment factor: {adjustment_factor:.3f}x")
logger.info("=" * 60)
logger.info(f"CALIBRATION SUMMARY (sRGB-space calibration):")
logger.info(f" Original times: {[f'{t:.6f}' for t in nominal_times]}")
logger.info(f" Calibrated times: {[f'{t:.6f}' for t in calibrated_times]}")
logger.info(f" Adjustment factors: {[f'{calibrated_times[i]/nominal_times[i]:.3f}x' for i in range(len(nominal_times))]}")
logger.info(f" EV0 anchors absolute scale at {nominal_times[ev0_idx]:.6f}s")
logger.info("=" * 60)
return calibrated_times
def process_hdr(self, images: List[np.ndarray], exposure_times: List[float],
algorithm: str = "detail_injection", auto_calibrate: bool = True,
debevec_exposure_compensation: float = -8.0,
debevec_anti_banding: bool = True) -> np.ndarray:
"""
Process multiple exposure images using various HDR algorithms
VFX PIPELINE NOTE:
- Debevec/Robertson expect 8-bit sRGB input (NOT linearized)
- They output linear radiance values (physical light intensity)
- The output will look flat/desaturated - this is CORRECT for VFX
Args:
images: List of 8-bit sRGB images (0-255 range) - DO NOT pre-linearize!
exposure_times: List of exposure times in seconds
algorithm: HDR algorithm to use:
- "radiance_fusion": Nuke-style plus/average HDR fusion (NEW DEFAULT!)
- "detail_injection": AI-aware detail injection with sRGB->linear conversion
- "natural_blend": Preserves EV0 look with enhanced range
- "mertens": Exposure fusion (display-ready)
- "debevec": True HDR recovery (flat/linear for VFX)
- "robertson": Alternative HDR recovery (flat/linear for VFX)
auto_calibrate: Enable adaptive calibration for AI-generated brackets (debevec/robertson only)
Analyzes actual brightness relationships and corrects exposure times
debevec_exposure_compensation: Exposure compensation in stops for debevec/robertson output
Default: -8.0 (optimal for AI-generated brackets with sRGB calibration)
Adjust if output is too bright/dark
debevec_anti_banding: Apply optional gradient-adaptive dithering to reduce banding
Default: True. Disable for pure lambda=100 smoothness with no color changes.
Returns:
HDR merged image in linear radiance space (float32)
- For Debevec/Robertson: Raw linear radiance (can exceed 1.0)
- For Mertens/Natural: Display-oriented fusion (0-1 range typical)
"""
try:
# Validate input format - OpenCV HDR functions require 8-bit input
processed_images = []
for i, img in enumerate(images):
if img.dtype != np.uint8:
logger.warning(f"Image {i} is not 8-bit (dtype: {img.dtype}), this may cause issues")
# Handle color channels properly
if len(img.shape) == 3 and img.shape[2] == 3: # 3-channel image
# CRITICAL FIX: ALL OpenCV functions work with BGR internally
# ComfyUI provides RGB, so we MUST convert for ALL algorithms
img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
processed_images.append(img_bgr)
logger.info(f"Converting RGB to BGR for {algorithm} (OpenCV standard)")
else:
logger.error(f"Image {i} has invalid shape: {img.shape}")
raise ValueError(f"Image must be 3-channel RGB, got shape: {img.shape}")
# Convert exposure times to numpy array
times = np.array(exposure_times, dtype=np.float32)
# ADAPTIVE AUTO-CALIBRATION for AI-generated images
# CRITICAL: Only apply for debevec and robertson algorithms
if auto_calibrate:
if algorithm in ["debevec", "robertson"]:
logger.info("🔬 AUTO-CALIBRATION ENABLED for AI-generated brackets")
times_calibrated = np.array(self._calibrate_exposure_times(processed_images, times.tolist()), dtype=np.float32)
times = times_calibrated
else:
logger.info(f"⚠️ Auto-calibrate is enabled but has NO EFFECT on '{algorithm}' mode (only works with debevec/robertson)")
else:
logger.info("Auto-calibration DISABLED")
logger.info(f"Processing {len(processed_images)} images with {algorithm} algorithm")
logger.info(f"Exposure times: {times}")
logger.info(f"Image formats: {[img.shape for img in processed_images]}")
logger.info(f"Image dtypes: {[img.dtype for img in processed_images]}")
# Process using selected algorithm
if algorithm == "mertens":
# Mertens Exposure Fusion - uses original gamma, no correction needed
logger.info("Using Mertens Exposure Fusion algorithm...")
hdr_radiance = self.merge_mertens.process(processed_images)
# Mertens output is typically in 0-1 range, gently scale for HDR
if hdr_radiance.max() <= 1.0:
hdr_radiance = hdr_radiance * 1.5 # Gentle boost, preserve contrast
elif algorithm == "radiance_fusion":
# Radiance Fusion - Nuke-inspired HDR blending (NEW DEFAULT!)
logger.info("Using Radiance Fusion - Nuke-style plus/average HDR blending...")
hdr_radiance = self._radiance_fusion(processed_images, times)
elif algorithm == "natural_blend":
# Natural Blend - maintains EV0 appearance with enhanced dynamic range
logger.info("Using Natural Blend exposure blending...")
hdr_radiance = self._blend_ev0_preserving(processed_images, times)
elif algorithm == "detail_injection":
# Detail Injection - AI-aware HDR detail injection
logger.info("Using Detail Injection - AI-aware HDR processing...")
# Always output linear HDR for proper EXR export
hdr_radiance = self._detail_injection(processed_images, times, output_mode="linear")
elif algorithm == "hdrutils" and HDRUTILS_AVAILABLE:
# Use HDRutils library for HDR merging
logger.info("Using HDRutils library for HDR merging...")
hdr_radiance = self._merge_with_hdrutils(processed_images, times)
elif algorithm == "robertson":
# Robertson algorithm - Pure HDR recovery with exposure compensation
logger.info("Using Robertson algorithm - Pure HDR mode...")
response = self.calibrator_robertson.process(processed_images, times)
hdr_radiance = self.merge_robertson.process(processed_images, times, response)
logger.info(f"Robertson raw output: [{hdr_radiance.min():.6f}, {hdr_radiance.max():.6f}]")
# Apply exposure compensation
if debevec_exposure_compensation != 0.0:
compensation_factor = 2.0 ** debevec_exposure_compensation
hdr_radiance = hdr_radiance * compensation_factor
logger.info(f"Applied exposure compensation: {debevec_exposure_compensation:+.1f} stops (factor: {compensation_factor:.6f}x)")
logger.info(f"Robertson compensated output: [{hdr_radiance.min():.6f}, {hdr_radiance.max():.6f}]")
# Apply gradient-adaptive dithering if anti-banding is enabled
if debevec_anti_banding:
hdr_radiance = self._apply_gradient_adaptive_dithering(hdr_radiance)
logger.info(f"Robertson mean radiance: {hdr_radiance.mean():.6f}")
else: # Default to Debevec - Pure HDR recovery with exposure compensation
# Estimate camera response function using Debevec method
logger.info("Using Debevec algorithm - Pure HDR mode...")
# Use higher smoothness for response curve (lambda=50.0)
response = self.calibrator.process(processed_images, times)
logger.info(f"Response function shape: {response.shape}")
# Merge images into HDR using Debevec algorithm
# Debevec outputs linear radiance values (already in linear space)
hdr_radiance = self.merge_debevec.process(processed_images, times, response)
logger.info(f"Debevec raw output: [{hdr_radiance.min():.6f}, {hdr_radiance.max():.6f}]")
# Apply exposure compensation
if debevec_exposure_compensation != 0.0:
compensation_factor = 2.0 ** debevec_exposure_compensation
hdr_radiance = hdr_radiance * compensation_factor
logger.info(f"Applied exposure compensation: {debevec_exposure_compensation:+.1f} stops (factor: {compensation_factor:.6f}x)")
logger.info(f"Debevec compensated output: [{hdr_radiance.min():.6f}, {hdr_radiance.max():.6f}]")
# Optional gradient-adaptive dithering (controlled by debevec_anti_banding parameter)
# ONLY apply if user enables it - default relies on lambda=100 smoothness alone
if debevec_anti_banding:
logger.info("Applying optional gradient-adaptive dithering...")
hdr_radiance = self._apply_gradient_adaptive_dithering(hdr_radiance)
else:
logger.info("Dithering disabled - relying on ultra-smooth response curve (lambda=100) only")
logger.info(f"Debevec mean radiance: {hdr_radiance.mean():.6f}")
# Validate HDR output
if hdr_radiance is None or hdr_radiance.size == 0:
raise ValueError("HDR merge produced empty result")
logger.info(f"HDR merge completed with {algorithm} algorithm:")
logger.info(f" Output shape: {hdr_radiance.shape}")
logger.info(f" Output dtype: {hdr_radiance.dtype}")
logger.info(f" Value range: [{hdr_radiance.min():.6f}, {hdr_radiance.max():.6f}]")
logger.info(f" Mean value: {hdr_radiance.mean():.6f}")
# Check for valid HDR data
if np.all(hdr_radiance == 0):
raise ValueError("HDR merge produced all-zero result")
# CRITICAL: Convert BGR back to RGB for ALL algorithms
# All OpenCV functions output BGR, but ComfyUI needs RGB
if len(hdr_radiance.shape) == 3 and hdr_radiance.shape[2] == 3:
hdr_radiance = cv2.cvtColor(hdr_radiance, cv2.COLOR_BGR2RGB)
logger.info("Converting BGR back to RGB for ComfyUI output")
# The result is already in linear colorspace - preserve HDR data
return hdr_radiance.astype(np.float32)
except Exception as e:
logger.error(f"HDR processing error: {str(e)}")
logger.error(f"Image count: {len(images)}")
logger.error(f"Image shapes: {[img.shape if img is not None else 'None' for img in images]}")
logger.error(f"Exposure times: {exposure_times}")
# Fallback: return the middle exposure image in linear space
if images:
middle_idx = len(images) // 2
fallback = images[middle_idx].astype(np.float32) / 255.0
# Convert back to linear space (reverse gamma correction)
fallback_linear = np.where(fallback <= 0.04045,
fallback / 12.92,
np.power((fallback + 0.055) / 1.055, 2.4))
logger.info(f"Using fallback image (index {middle_idx})")
return fallback_linear.astype(np.float32)
raise e
def _gentle_tone_map(self, hdr_image: np.ndarray, algorithm_name: str) -> np.ndarray:
"""
Apply gentle tone mapping to preserve HDR range while making output usable
Args:
hdr_image: Raw HDR output from Debevec/Robertson
algorithm_name: Name of algorithm for logging
Returns:
Gently processed HDR image with preserved dynamic range
"""
logger.info(f"{algorithm_name} raw output range: [{hdr_image.min():.6f}, {hdr_image.max():.6f}]")
try:
# Gentle processing to preserve HDR range but make it usable
# Method 1: Simple scaling based on percentiles (preserves HDR better than Reinhard)
p95 = np.percentile(hdr_image, 95)
p05 = np.percentile(hdr_image, 5)
if p95 > p05 and p95 > 0:
# Scale so 95th percentile maps to reasonable value (1.0-3.0 range)
scale_factor = 2.0 / p95
scaled = hdr_image * scale_factor
# Apply very gentle gamma correction to improve appearance
gentle_gamma = np.power(np.clip(scaled, 0, 10), 0.8)
logger.info(f"{algorithm_name} after gentle processing: [{gentle_gamma.min():.6f}, {gentle_gamma.max():.6f}]")
return gentle_gamma.astype(np.float32)
else:
# Fallback for edge cases
return np.clip(hdr_image, 0.0, 10.0).astype(np.float32)
except Exception as e:
logger.error(f"Gentle tone mapping failed for {algorithm_name}: {e}")
# Fallback: simple clipping
return np.clip(hdr_image, 0.0, 10.0).astype(np.float32)
def _radiance_fusion(self, images: List[np.ndarray], times: List[float]) -> np.ndarray:
"""
Radiance Fusion - Nuke-inspired HDR blending algorithm
Uses Nuke's plus and average operations for perfect HDR preservation:
1. Plus all outer exposures: (ev-4 + ev-2 + ev+2 + ev+4)
2. Average with center exposure: result + ev0 / 2
This creates beautiful HDR data while maintaining natural appearance.
Args:
images: List of exposure images in BGR format (from OpenCV)
times: Exposure times
Returns:
Radiance fusion result with excellent HDR preservation
"""
logger.info("Radiance Fusion: Nuke-style HDR blending with plus/average operations")
# Convert to float32 for HDR processing
float_images = [img.astype(np.float32) / 255.0 for img in images]
# For 5-stop: [ev+4, ev+2, ev0, ev-2, ev-4] - indices [0,1,2,3,4]
# For 3-stop: [ev+2, ev0, ev-2] - indices [0,1,2]
if len(float_images) == 5:
# 5-stop processing: ev+4, ev+2, ev0, ev-2, ev-4
ev_plus_4 = float_images[0] # Most overexposed
ev_plus_2 = float_images[1] # Overexposed
ev_0 = float_images[2] # Middle exposure
ev_minus_2 = float_images[3] # Underexposed
ev_minus_4 = float_images[4] # Most underexposed
# NUKE PLUS OPERATION: Add all outer exposures
# This preserves full dynamic range from all sources
outer_sum = ev_plus_4 + ev_plus_2 + ev_minus_2 + ev_minus_4
logger.info("5-stop: Added outer exposures (ev±4, ev±2) using Nuke plus operation")
elif len(float_images) == 3:
# 3-stop processing: ev+2, ev0, ev-2
ev_plus_2 = float_images[0] # Overexposed
ev_0 = float_images[1] # Middle exposure
ev_minus_2 = float_images[2] # Underexposed
# NUKE PLUS OPERATION: Add outer exposures
outer_sum = ev_plus_2 + ev_minus_2
logger.info("3-stop: Added outer exposures (ev±2) using Nuke plus operation")
else:
raise ValueError(f"Radiance Fusion requires 3 or 5 images, got {len(float_images)}")
# NUKE AVERAGE OPERATION: (outer_sum + ev0) / 2
# This balances the combined outer detail with the natural center exposure
radiance_result = (outer_sum + ev_0) / 2.0
logger.info(f"Applied Nuke average operation: (outer_sum + ev0) / 2")
logger.info(f"Radiance Fusion result: [{radiance_result.min():.3f}, {radiance_result.max():.3f}]")
logger.info(f"HDR pixels above 1.0: {np.sum(radiance_result > 1.0)} pixels")
# Return with full HDR range preserved (no clipping!)
return radiance_result.astype(np.float32)
def _blend_ev0_preserving(self, images: List[np.ndarray], times: List[float]) -> np.ndarray:
"""
Improved exposure blending that perfectly preserves EV0 appearance
while storing HDR information in values above 1.0
This method uses the EV0 as the base and only modifies areas where
detail is lost (pure white or pure black) with information from other exposures.
Args:
images: List of exposure images in BGR format (from OpenCV)
times: Exposure times
Returns:
Enhanced image that looks identical to EV0 but with HDR values > 1.0
"""
logger.info("Natural Blend: Perfect EV0 preservation with HDR extension")
# Find the EV0 image (middle exposure)
ev0_idx = len(images) // 2
ev0_base = images[ev0_idx].astype(np.float32) / 255.0
logger.info(f"Using image {ev0_idx} as EV0 base (out of {len(images)} images)")
# Convert all images to float (no exposure compensation needed)
float_images = []
for i, img in enumerate(images):
float_img = img.astype(np.float32) / 255.0
float_images.append(float_img)
# Start with EV0 as the base - this ensures perfect appearance match
result = ev0_base.copy()
# Only blend in areas where EV0 has lost detail (highlights and shadows)
gray_ev0 = cv2.cvtColor(ev0_base, cv2.COLOR_BGR2GRAY)
# Process highlights - where EV0 is clipped (near 1.0)
highlight_threshold = 0.95 # Areas above this in EV0 need HDR data
highlight_mask = gray_ev0 > highlight_threshold
if np.any(highlight_mask):
# Use underexposed images for highlight recovery
for i in range(ev0_idx + 1, len(float_images)):
img = float_images[i]
# Use the actual exposure difference for HDR scaling
# Underexposed images have longer exposure times
exposure_ratio = times[ev0_idx] / times[i]
scale_factor = exposure_ratio # This gives proper HDR scaling
# Blend only in highlight areas
for c in range(3):
# Use the underexposed data scaled up for HDR
hdr_values = img[:, :, c] * scale_factor
# Smooth transition: gradually blend as we approach pure white
blend_weight = np.where(highlight_mask,
(gray_ev0 - highlight_threshold) / (1.0 - highlight_threshold),
0.0)
# Blend HDR values only in highlights, preserving EV0 elsewhere
result[:, :, c] = np.where(highlight_mask,
result[:, :, c] * (1 - blend_weight) + hdr_values * blend_weight,
result[:, :, c])
logger.info(f"HDR highlight recovery applied - values up to {result.max():.2f}")
# Process shadows - where EV0 is too dark (near 0.0)
shadow_threshold = 0.05 # Areas below this in EV0 need shadow detail
shadow_mask = gray_ev0 < shadow_threshold
if np.any(shadow_mask):
# Use overexposed images for shadow recovery
for i in range(ev0_idx):
img = float_images[i]
# Blend only in shadow areas
for c in range(3):
# Smooth transition: gradually blend as we approach pure black
blend_weight = np.where(shadow_mask,
(shadow_threshold - gray_ev0) / shadow_threshold,
0.0)
# Blend shadow detail, preserving EV0 elsewhere
result[:, :, c] = np.where(shadow_mask,
result[:, :, c] * (1 - blend_weight * 0.5) + img[:, :, c] * blend_weight * 0.5,
result[:, :, c])
logger.info("Shadow detail recovery applied")
# Ensure midtones exactly match EV0
midtone_mask = np.logical_and(gray_ev0 >= shadow_threshold, gray_ev0 <= highlight_threshold)
for c in range(3):
result[:, :, c] = np.where(midtone_mask, ev0_base[:, :, c], result[:, :, c])
logger.info(f"Natural Blend completed - EV0 appearance preserved")
logger.info(f" HDR range: [{result.min():.3f}, {result.max():.3f}]")
logger.info(f" Values > 1.0: {np.sum(result > 1.0)} pixels")
# NO CLIPPING - preserve HDR values above 1.0
return result.astype(np.float32)
def _merge_with_hdrutils(self, images: List[np.ndarray], times: List[float]) -> np.ndarray:
"""
Use HDRutils library for HDR merging if available
Args:
images: List of 8-bit images
times: Exposure times
Returns:
HDR merged image
"""
try:
# Convert images to the format HDRutils expects
# HDRutils typically expects RGB format
rgb_images = []
for img in images:
if len(img.shape) == 3 and img.shape[2] == 3:
# Convert BGR to RGB for HDRutils
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
rgb_images.append(rgb_img)
else:
rgb_images.append(img)
# Stack images for HDRutils
image_stack = np.stack(rgb_images, axis=0)
# Create HDR merge using HDRutils
# Note: HDRutils.merge might have different parameters
# This is a generic implementation
hdr_image = HDRutils.merge(image_stack, times)
logger.info(f"HDRutils merge complete: range [{hdr_image.min():.6f}, {hdr_image.max():.6f}]")
return hdr_image.astype(np.float32)
except Exception as e:
logger.error(f"HDRutils merge failed: {e}")
logger.info("Falling back to Mertens algorithm")
# Fallback to Mertens
return self.merge_mertens.process(images)
def _create_highlight_mask(self, gray_image: np.ndarray, threshold: float = 0.8) -> np.ndarray:
"""Create a mask for highlight areas that need detail recovery"""
# Smooth transition for highlights
mask = np.zeros_like(gray_image, dtype=np.float32)
# Areas above threshold get progressively more blending
bright_areas = gray_image > threshold
if np.any(bright_areas):
mask[bright_areas] = (gray_image[bright_areas] - threshold) / (1.0 - threshold)
# Smooth the mask to avoid harsh transitions with larger kernel
mask = cv2.GaussianBlur(mask, (41, 41), 0)
return np.clip(mask, 0, 1)
def _create_shadow_mask(self, gray_image: np.ndarray, threshold: float = 0.2) -> np.ndarray:
"""Create a mask for shadow areas that need detail recovery"""
# Smooth transition for shadows
mask = np.zeros_like(gray_image, dtype=np.float32)
# Areas below threshold get progressively more blending
dark_areas = gray_image < threshold
if np.any(dark_areas):
mask[dark_areas] = (threshold - gray_image[dark_areas]) / threshold
# Smooth the mask to avoid harsh transitions with larger kernel
mask = cv2.GaussianBlur(mask, (41, 41), 0)
return np.clip(mask, 0, 1)
def _analyze_gamma(self, images: List[np.ndarray]) -> float:
"""
Analyze input images to detect gamma encoding
AI-generated sRGB images typically have gamma 2.2
Args:
images: List of 8-bit images
Returns:
Detected gamma value (2.2 for sRGB, 1.0 for linear)
"""
# Sample multiple images for better detection
sample_values = []
for img in images[:min(3, len(images))]:
# Convert to float and normalize
img_float = img.astype(np.float32) / 255.0
# Sample mid-gray values (0.3-0.7 range) for gamma analysis
mask = (img_float > 0.3) & (img_float < 0.7)
if np.any(mask):
sample_values.extend(img_float[mask].flatten()[:1000])
if len(sample_values) > 0:
# Analyze distribution to detect gamma curve
sample_array = np.array(sample_values)
median_val = np.median(sample_array)
# AI-generated images tend to have strong gamma curve
# Real linear images would have different distribution
# Simple heuristic: if median is in expected sRGB range, assume gamma 2.2
if 0.4 < median_val < 0.6:
logger.info("Detected sRGB gamma encoding (gamma ≈ 2.2)")
return 2.2
else:
logger.info("Images appear to be in sRGB color space (gamma 2.2)")
return 2.2 # Default to sRGB for AI-generated images
logger.info("Defaulting to sRGB gamma (2.2) for AI-generated images")
return 2.2
def _srgb_to_linear(self, srgb: np.ndarray) -> np.ndarray:
"""
Convert sRGB (gamma-encoded) to linear light space
Standard sRGB to linear transformation:
- For values <= 0.04045: linear = srgb / 12.92
- For values > 0.04045: linear = ((srgb + 0.055) / 1.055) ^ 2.4
Args:
srgb: Image in sRGB color space (0-1 range)
Returns:
Image in linear light space
"""
linear = np.where(
srgb <= 0.04045,
srgb / 12.92,
np.power((srgb + 0.055) / 1.055, 2.4)
)
logger.info(f"sRGB to linear: input range [{srgb.min():.3f}, {srgb.max():.3f}] -> output range [{linear.min():.3f}, {linear.max():.3f}]")
return linear.astype(np.float32)
def _linear_to_srgb(self, linear: np.ndarray) -> np.ndarray:
"""
Convert linear light space to sRGB (gamma-encoded)
Inverse of sRGB transformation - for display purposes only!
This will clip HDR values >1.0 to displayable range.
Standard linear to sRGB transformation:
- For values <= 0.0031308: srgb = linear * 12.92
- For values > 0.0031308: srgb = 1.055 * (linear ^ (1/2.4)) - 0.055
Args:
linear: Image in linear light space
Returns:
Image in sRGB color space (gamma-encoded)
"""
# Tone map HDR values first using simple Reinhard
# This compresses values >1.0 into displayable range
linear_tonemapped = linear / (1.0 + linear)
# Apply sRGB gamma encoding
srgb = np.where(
linear_tonemapped <= 0.0031308,
linear_tonemapped * 12.92,
1.055 * np.power(linear_tonemapped, 1.0 / 2.4) - 0.055
)
# Clamp to valid range
srgb = np.clip(srgb, 0.0, 1.0)
logger.info(f"Linear to sRGB (tonemapped): input range [{linear.min():.3f}, {linear.max():.3f}] -> output range [{srgb.min():.3f}, {srgb.max():.3f}]")
return srgb.astype(np.float32)
def _smooth_step(self, edge0: float, edge1: float, x: np.ndarray) -> np.ndarray:
"""
Hermite interpolation for smooth transitions
Creates smooth S-curve for natural blending
Args:
edge0: Lower edge
edge1: Upper edge
x: Input values
Returns:
Smoothly interpolated values (0-1)
"""
t = np.clip((x - edge0) / (edge1 - edge0), 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
def _inject_detail_preserve_color(self, base_rgb: np.ndarray, detail_rgb: np.ndarray,
blend: np.ndarray) -> np.ndarray:
"""
Inject detail while preserving hue and color ratios
Uses luminance-based scaling to maintain color appearance
while changing detail and brightness
Args:
base_rgb: Base RGB image (H, W, 3)
detail_rgb: Detail source RGB image (H, W, 3)
blend: Blend weight map (H, W)
Returns:
Result with injected detail
"""
# Calculate luminance using Rec. 709 coefficients
base_luma = (0.2126 * base_rgb[:, :, 2] +
0.7152 * base_rgb[:, :, 1] +
0.0722 * base_rgb[:, :, 0]) # Note: BGR order from OpenCV
detail_luma = (0.2126 * detail_rgb[:, :, 2] +
0.7152 * detail_rgb[:, :, 1] +
0.0722 * detail_rgb[:, :, 0])
# Calculate new luminance
new_luma = base_luma * (1 - blend) + detail_luma * blend
# Scale RGB to match new luminance while preserving color ratios
result_rgb = np.zeros_like(base_rgb)
# Avoid division by zero
safe_base_luma = np.maximum(base_luma, 1e-6)
scale = new_luma / safe_base_luma
# Apply scaling to each channel
for c in range(3):
result_rgb[:, :, c] = base_rgb[:, :, c] * scale
# In near-black areas, use detail color directly
near_black = base_luma < 0.001
if np.any(near_black):
for c in range(3):
result_rgb[:, :, c] = np.where(
near_black,
detail_rgb[:, :, c] * blend,
result_rgb[:, :, c]
)
return result_rgb
def _detail_injection(self, images: List[np.ndarray], times: List[float], output_mode: str = "linear") -> np.ndarray:
"""
Detail Injection algorithm for AI-generated HDR stacks
This algorithm is designed specifically for AI-generated exposure stacks
where images don't follow photometric relationships. It:
1. Analyzes gamma encoding and converts to linear space
2. Uses EV0 as base (preserves natural look)
3. Injects highlight detail from underexposed images (EV-2, EV-4) into >1.0 range
4. Injects shadow detail from overexposed images (EV+2, EV+4) into near-zero range
5. Preserves color ratios using luminance-based scaling
6. Applies automatic brightness compensation to target 18% gray
Args:
images: List of exposure images in BGR format (from OpenCV)
times: Exposure times
output_mode: Always "linear" for true HDR output
Returns:
Linear HDR image with detail injection (perfect for EXR export)
"""
logger.info("=" * 80)
logger.info("DETAIL INJECTION ALGORITHM - AI-Aware HDR Processing")
logger.info("=" * 80)
# Step 1: Analyze and convert to linear space
logger.info("\nStep 1: Gamma Analysis and Linear Conversion")
logger.info("-" * 40)
detected_gamma = self._analyze_gamma(images)
# Convert all images from 8-bit sRGB to linear float
linear_images = []
for i, img in enumerate(images):
# Convert to 0-1 range
img_float = img.astype(np.float32) / 255.0
# Convert sRGB to linear
img_linear = self._srgb_to_linear(img_float)
linear_images.append(img_linear)
logger.info(f" Image {i}: sRGB -> linear, range [{img_linear.min():.4f}, {img_linear.max():.4f}]")
# Identify images by exposure
num_images = len(linear_images)
ev0_idx = num_images // 2
if num_images == 5:
# 5-stop: [EV+4, EV+2, EV0, EV-2, EV-4]