-
Notifications
You must be signed in to change notification settings - Fork 12
/
image_enhancement.py
1936 lines (1460 loc) · 64 KB
/
image_enhancement.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 09:40:58 2020
Image enhancement functions
@author: Vasileios Vonikakis (bbonik@gmail.com)
"""
import math
import imageio
import numpy as np
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage import img_as_float
from skimage.exposure import rescale_intensity, adjust_gamma
plt.close('all')
#TODO: better memory management!!!! Too many copying of images.
#something like "inplace"?
def map_value(
value,
range_in=(0,1),
range_out=(0,1),
invert=False,
non_lin_convex=None,
non_lin_concave=None):
'''
---------------------------------------------------------------------------
Map a scalar value to an output range in a linear/non-linear way
---------------------------------------------------------------------------
Map scalar values to a particular range, in a linear or non-linear way.
This can be helpful for adjusting the range and nonlinear response of
parameters.
For more info on the non-linear functions check:
Vonikakis, V., Winkler, S. (2016). A center-surround framework for spatial
image processing. Proc. IS&T Human Vision & Electronic Imaging.
INPUTS
------
value: float
Input value to be mapped.
range_in: tuple (min,max)
Range of input value. The min and max values that the input value can
attain.
range_out: tuple (min,max)
Range of output value. The min and max values that the mapped input
value can attain.
invert: Bool
Invert or not the input value. If invert, then min->max and max->min.
non_lin_convex: None or float (0,inf)
If None, no non-linearity is applied. If float, then a convex
non-linearity is applied, which lowers the values, while not affecting
the min and max. non_lin_convex controls the steepness of the
non-linear mapping. Small values near zero, result in a steeper curve.
non_lin_concave: None or float (0,inf)
If None, no non-linearity is applied. If float, then a concave
non-linearity is applied, which increases the values, while not
affecting min and max. non_lin_concave controls the steepness of the
non-linear mapping. Small values near zero, result in a steeper curve.
OUTPUT
------
Mapped value
'''
# truncate value to within input range limits
if value > range_in[1]: value = range_in[1]
if value < range_in[0]: value = range_in[0]
# map values linearly to [0,1]
value = (value - range_in[0]) / (range_in[1] - range_in[0])
# invert values
if invert is True: value = 1 - value
# apply convex non-linearity
if non_lin_convex is not None:
value = (value * non_lin_convex) / (1 + non_lin_convex - value)
# apply concave non-linearity
if non_lin_concave is not None:
value = ((1 + non_lin_concave) * value) / (non_lin_concave + value)
# mapping value to the output range in a linear way
value = value * (range_out[1] - range_out[0]) + range_out[0]
return value
def get_membership_luts(
resolution=256,
lower_threshold=0.35,
upper_threshold=0.65,
verbose=False):
'''
---------------------------------------------------------------------------
Creates 3 paramteric traspezoid membership functions
---------------------------------------------------------------------------
The trapezoid functions are defined as piece-wise functions between the
0, lower_threshold, upper_threshold, 1. These trapezoid membership
functions can be used to filter out which parts of each exposure to be
used during exposure fusion. More details can be found in the following
paper:
Vonikakis, V., Bouzos, O. & Andreadis, I. (2011). Multi-Exposure Image
Fusion Based on Illumination Estimation, SIPA2011 (pp.135-142), Greece.
INPUTS
------
resolution: int
The size of the LUT (how many inputs).
lower_threshold: float in the range [0,1]
The position of the lower inflection point of the trapezoid functions.
It should be always lower compared to the upper_threshold.
upper_threshold: float in the range [0,1]
The position of the upper inflection point of the trapezoid functions.
It should be always higher compared to the lower_threshold.
verbose: boolean
Display outputs.
OUTPUT
------
lut_lower: float numpy array of size equal to resolution, values in [0,1]
The lower trepezoid membership function.
lut_mid: float numpy array of size equal to resolution, values in [0,1]
The middle trepezoid membership function.
lut_upper float numpy array of size equal to resolution, values in [0,1]
The upper trepezoid membership function.
'''
lut_lower = np.zeros(resolution, dtype='float')
lut_mid = np.zeros(resolution, dtype='float')
lut_upper = np.zeros(resolution, dtype='float')
for i in range(resolution):
i_float = i / (resolution - 1)
# lower trapezoid membership function
if i_float <= lower_threshold:
lut_lower[i] = i_float / lower_threshold
else:
lut_lower[i] = 1
# middle trapezoid membership function
if i_float <= lower_threshold:
lut_mid[i] = i_float / lower_threshold
elif i_float <= upper_threshold:
lut_mid[i] = 1
else:
lut_mid[i] = (1 - i_float) / (1 - upper_threshold)
# upper trapezoid membership function
if i_float <= upper_threshold:
lut_upper[i] = 1
else:
lut_upper[i] = (1 - i_float) / (1 - upper_threshold)
if verbose is True:
plt.figure()
plt.subplot(1,3,1)
plt.plot(lut_lower)
plt.title('Lower')
plt.grid(True)
plt.subplot(1,3,2)
plt.plot(lut_mid)
plt.title('Middle')
plt.grid(True)
plt.subplot(1,3,3)
plt.plot(lut_upper)
plt.title('Upper')
plt.grid(True)
plt.suptitle('Trapezoid membership functions')
plt.show()
return lut_lower, lut_mid, lut_upper
def get_sigmoid_lut(
resolution=256,
threshold=0.2,
non_linearirty=0.2,
verbose=False):
'''
---------------------------------------------------------------------------
Creates a paramteric sigmoid function and stores it in a LUT
---------------------------------------------------------------------------
The sigmoid function is defined as a piece-wise function of 2 inverse
non-linearities. This allows full control of the inflection point
(threshold) and the degree of 'sharpness' of each non-linearity. The
non-linear curves used here are described in the paper:
Vonikakis, V., Winkler, S. (2016). A center-surround framework for spatial
image processing. Proc. IS&T Human Vision & Electronic Imaging.
INPUTS
------
resolution: int
The size of the LUT (how many inputs).
threshold: float in the range [0,1]
The position of the inflection point of the sigmoid function (0.5 in
the mid_tonedle of the range).
non_linearirty: float in range (0, inf)
Controls the non-linearity of the curve before and after the inflection
point. It should not be 0. The smaller it is (asymptotically to 0) the
'sharper' the non-linearity. After ~5 it asymptotically approaches a
linerity.
verbose: boolean
Display outputs.
OUTPUT
------
lut: float numpy array of size equal to resolution
The output sigmoid lut.
'''
max_value = resolution - 1 # the maximum attainable value
thr = threshold * max_value # threshold in the range [0,resolution-1]
alpha = non_linearirty * max_value # controls non-linearity degree
beta = max_value - thr
if beta == 0: beta = 0.001
lut = np.zeros(resolution, dtype='float')
for i in range(resolution):
i_comp = i - thr # complement of i
# upper part of the piece-wise sigmoid function
if i >= thr:
lut[i] = (((((alpha + beta) * i_comp) / (alpha + i_comp)) *
(1 / (2 * beta))) + 0.5)
# lower part of the piece-wise sigmoid function
else:
lut[i] = (alpha * i) / (alpha - i_comp) * (1 / (2 * thr))
if verbose is True:
plt.figure()
plt.plot(lut)
plt.title('Sigmoid LUT | ' +
'thr=' + str(int(thr)) + ' (' + str(round(threshold, 3)) +
') | nonlin=' + str(int(alpha)) +
' (' + str(round(non_linearirty, 3)) + ')')
plt.grid(True)
plt.tight_layout()
plt.show()
return lut
def get_photometric_mask(
image,
smoothing=0.2,
grayscale_out=True,
verbose=False):
'''
---------------------------------------------------------------------------
Estimate the photometric mask of an image by using edge-aware blurring
---------------------------------------------------------------------------
Applies strong blurring while preserving the strong edges of the image in
order to avoid halo artifacts. Inspired by the paper:
Shaked, Doron & Keshet, Renato. (2004). "Robust Recursive Envelope
Operators for Fast Retinex."
INPUTS
------
image: numpy array (WxH or WxHxK of uint8 [0.255] or float [0,1])
Input image.
smoothing: float in the interval [0,1]
Value controlling the blur's strenght. 0 indicates no blur. Values
between 0-1 increase blurring strength while preserving edges. Values
above 1 approximate very strong gaussian blurring (large sigmas) where
no edges are preserved. Practically, values above 10 result into a
uniform image.
grayscale_out: logical
Whether or not the photometric mask is going to be grayscale or not.
If the input image is already grayscale (2D) then this parameter is
irrelevant.
verbose: boolean
Display outputs.
OUTPUT
------
image_ph_mask: numpy array of WxH or WxHxK of float [0,1]
Photometric mask of the input image.
'''
'''
Intuition about the threshold and non_linearirty values of the LUTs
threshold:
The larger it is, the stronger the blurring, the better the local
contrast but also more halo artifacts (less edge preservation).
non_linearirty:
The lower it is, the more it preserves the edges, but also has more
'bleeding' effects.
'''
# internal parameters
THR_A = smoothing
THR_B = 0.04 # ~10/255
NON_LIN = 0.12 # ~30/255
LUT_RES = 256
# get sigmoid LUTs
lut_a = get_sigmoid_lut(
resolution=LUT_RES,
threshold=THR_A,
non_linearirty=NON_LIN,
verbose=verbose
)
lut_a_max = len(lut_a) -1
lut_b = get_sigmoid_lut(
resolution=LUT_RES,
threshold=THR_B,
non_linearirty=NON_LIN,
verbose=verbose
)
lut_b_max = len(lut_b) -1
# dealing with different number of channels
if len(image.shape) == 3:
if grayscale_out is True:
image_ph_mask = rgb2gray(image.copy()) # [0,1] 2D
else:
image_ph_mask = img_as_float(image.copy()) # [0,1] 3D
elif len(image.shape) == 2:
image_ph_mask = img_as_float(image.copy()) # [0,1] 2D
else:
image_ph_mask = img_as_float(image.copy()) # [0,1] ?D
# if image is 2D, expand dimensions to 3D for code compatibility
# (filtering assumes a 3D image)
if len(image_ph_mask.shape) == 2:
image_ph_mask = np.expand_dims(image_ph_mask, axis=2)
# robust recursive envelope
# up -> down
for i in range(1, image_ph_mask.shape[0]-1):
d = np.abs(image_ph_mask[i-1,:,:] - image_ph_mask[i+1,:,:]) # diff
d = lut_a[(d * lut_a_max).astype(int)]
image_ph_mask[i,:,:] = ((image_ph_mask[i,:,:] * d) +
(image_ph_mask[i-1,:,:] * (1-d)))
# left -> right
for j in range(1, image_ph_mask.shape[1]-1):
d = np.abs(image_ph_mask[:,j-1,:] - image_ph_mask[:,j+1,:]) # diff
d = lut_a[(d * lut_a_max).astype(int)]
image_ph_mask[:,j,:] = ((image_ph_mask[:,j,:] * d) +
(image_ph_mask[:,j-1,:] * (1-d)))
# down -> up
for i in range(image_ph_mask.shape[0]-2, 1, -1):
d = np.abs(image_ph_mask[i-1,:,:] - image_ph_mask[i+1,:,:]) # diff
d = lut_a[(d * lut_a_max).astype(int)]
image_ph_mask[i,:,:] = ((image_ph_mask[i,:,:] * d) +
(image_ph_mask[i+1,:,:] * (1-d)))
# right -> left
for j in range(image_ph_mask.shape[1]-2, 1, -1):
d = np.abs(image_ph_mask[:,j-1,:] - image_ph_mask[:,j+1,:]) # diff
d = lut_b[(d * lut_b_max).astype(int)]
image_ph_mask[:,j,:] = ((image_ph_mask[:,j,:] * d) +
(image_ph_mask[:,j+1,:] * (1-d)))
# up -> down
for i in range(1, image_ph_mask.shape[0]-1):
d = np.abs(image_ph_mask[i-1,:,:] - image_ph_mask[i+1,:,:]) # diff
d = lut_b[(d * lut_b_max).astype(int)]
image_ph_mask[i,:,:] = ((image_ph_mask[i,:,:] * d) +
(image_ph_mask[i-1,:,:] * (1-d)))
# convert back to 2D if grayscale is needed
if grayscale_out is True:
image_ph_mask = np.squeeze(image_ph_mask)
if verbose is True:
plt.figure()
plt.subplot(1,2,1)
plt.imshow(image)
plt.title('Input image')
plt.axis('off')
plt.subplot(1,2,2)
if grayscale_out is True:
plt.imshow(image_ph_mask, cmap='gray', vmin=0, vmax=1)
else:
plt.imshow(image_ph_mask, vmin=0, vmax=1)
plt.title('Photometric mask')
plt.axis('off')
plt.tight_layout(True)
plt.suptitle('Estimation of photometric mask')
plt.show()
return image_ph_mask
def blend_expoures(
exposure_list,
threshold_dark=0.35,
threshold_bright=0.65,
verbose=False
):
'''
---------------------------------------------------------------------------
Blend a collection of exposures to a single image
---------------------------------------------------------------------------
Function to blend a list of image exposures, using illumination estimation
across 2 spatial scales.
Based on the following paper:
Vonikakis, V., Bouzos, O. & Andreadis, I. (2011). Multi-Exposure Image
Fusion Based on Illumination Estimation, SIPA2011 (pp.135-142), Greece.
INPUTS
------
exposure_list: list of numpy image arrays
List of numpy arrays (image exposures) which will be blended. Arrays
can be either grayscale, or color (3 channels).
threshold_dark: float in the interval [0,1]
Lower threshold for the membership function which will be applied to
the brightest exposure (long exposure). See above paper for more info.
threshold_dark < threshold_bright
threshold_bright: float in the interval [0,1]
Higher threshold for the membership function which will be applied to
the darkest exposure (short exposure). See above paper for more info.
threshold_bright > threshold_dark
verbose: boolean
Display outputs.
OUTPUT
------
exposure_out: numpy array, float [0,1]
Output image of the blended exposures. If input images are grayscale,
exposure_out is also grayscale. If input images are color, then
exposure_out is also color.
'''
# internal constants
SCALE_COARSE = 0.6 # [0,1], 0->fine, 1->coarse
SCALE_FINE = 0.2 # [0,1], 0->fine, 1->coarse
LUMINANCE_MIDDLE = 0.5 # middle of the luminance scale in [0,1]
GAMA_MAX = 2 # max gama to be used for darkening images
GAMA_MIN = 0.2 # min gama to be used for brightening images
LUT_RESOLUTION = 256
total_exposures = len(exposure_list)
# color or grayscale
if len(exposure_list[0].shape) > 2: # check the 1st image of the list
color_exposures = True
else:
color_exposures = False
#--- sort exposures from darkest to brightest
exposure_list_gray = []
mean_luminance_list = []
if color_exposures is True:
exposure_list_red = []
exposure_list_green = []
exposure_list_blue = []
for image in exposure_list:
image_gray = rgb2gray(image)
exposure_list_gray.append(image_gray) # grayscale
mean_luminance_list.append(image_gray.mean()) # mean luminance
if color_exposures is True:
exposure_list_red.append(img_as_float(image[:,:,0])) # red
exposure_list_green.append(img_as_float(image[:,:,1])) # green
exposure_list_blue.append(img_as_float(image[:,:,2])) # blue
# sort according to mean luminance
indx_lum_ascending = sorted(
range(len(mean_luminance_list)),
key=lambda i: mean_luminance_list[i]
)
if verbose is True:
print('Darkest to brightest exposure sequence:', indx_lum_ascending)
# convert into a numpy array of hight x width x number of exposures
# (the 3rd dimension has the separate grayscale or color exposures)
exposure_array_gray = np.array(exposure_list_gray)
exposure_array_gray = np.moveaxis(exposure_array_gray, 0, -1)
exposure_array_gray = exposure_array_gray[:,:,indx_lum_ascending]
if color_exposures is True:
exposure_array_red = np.array(exposure_list_red)
exposure_array_red = np.moveaxis(exposure_array_red, 0, -1)
exposure_array_red = exposure_array_red[:,:,indx_lum_ascending]
exposure_array_green = np.array(exposure_list_green)
exposure_array_green = np.moveaxis(exposure_array_green, 0, -1)
exposure_array_green = exposure_array_green[:,:,indx_lum_ascending]
exposure_array_blue = np.array(exposure_list_blue)
exposure_array_blue = np.moveaxis(exposure_array_blue, 0, -1)
exposure_array_blue = exposure_array_blue[:,:,indx_lum_ascending]
#--- generate illumination estimation in 2 spatial scales
illumination_coarse = get_photometric_mask(
exposure_array_gray.copy(),
smoothing=SCALE_COARSE,
grayscale_out=False, # estimaste each channel separately
verbose=False)
illumination_fine = get_photometric_mask(
exposure_array_gray.copy(),
smoothing=SCALE_FINE,
grayscale_out=False, # estimaste each channel separately
verbose=False)
# min max normalization for each exposure.
# make sure that each exposure has a 0 and 1 somewhere
for i in range(total_exposures):
illumination_coarse[:,:,i] = rescale_intensity(
illumination_coarse[:,:,i],
in_range='image',
out_range='dtype'
)
illumination_fine[:,:,i] = rescale_intensity(
illumination_fine[:,:,i],
in_range='image',
out_range='dtype'
)
#--- Autoadjusting extreme exposures
# (This would be better if done in a data-driven way)
# if darkest exposure is too bright, darken it
# if brightest exposure is too dark, brighten it
# darkest: if mean_lum>0.5 (too bright)
# scale gamma linearly in the interval [1, GAMA_MAX]
mean_lum = illumination_coarse[:,:,0].mean()
if mean_lum > LUMINANCE_MIDDLE:
gamma_new = map_value(
mean_lum,
range_in=(LUMINANCE_MIDDLE,1),
range_out=(1,GAMA_MAX)
)
if verbose:
print(
'Darkest coarse exposure too bright! Applying gamma:',
gamma_new
)
illumination_coarse[:,:,0] = adjust_gamma(
image = illumination_coarse[:,:,0],
gamma = gamma_new
)
mean_lum = illumination_fine[:,:,0].mean()
if mean_lum > LUMINANCE_MIDDLE:
gamma_new = map_value(
mean_lum,
range_in=(LUMINANCE_MIDDLE,1),
range_out=(1,GAMA_MAX)
)
if verbose:
print(
'Darkest fine exposure too bright! Applying gamma:',
gamma_new
)
illumination_fine[:,:,0] = adjust_gamma(
image = illumination_fine[:,:,0],
gamma = gamma_new
)
# brightest: if mean_lum<0.5 (too dark)
# scale gamma linearly in the interval [GAMA_MIN, 1]
mean_lum = illumination_coarse[:,:,-1].mean()
if mean_lum < LUMINANCE_MIDDLE:
gamma_new = map_value(
mean_lum,
range_in=(0,LUMINANCE_MIDDLE),
range_out=(GAMA_MIN,1)
)
if verbose:
print(
'Brightest coarse exposure too dark! Applying gamma:',
gamma_new
)
illumination_coarse[:,:,-1] = adjust_gamma(
image = illumination_coarse[:,:,-1],
gamma = gamma_new
)
mean_lum = illumination_fine[:,:,-1].mean()
if mean_lum < LUMINANCE_MIDDLE:
gamma_new = map_value(
mean_lum,
range_in=(0,LUMINANCE_MIDDLE),
range_out=(GAMA_MIN,1)
)
if verbose:
print(
'Brightest fine exposure too dark! Applying gamma:',
gamma_new
)
illumination_fine[:,:,-1] = adjust_gamma(
image = illumination_fine[:,:,-1],
gamma = gamma_new
)
#--- Apply membership functions to illumination to get exposure weights
# generate membership function LUTs
weights_lower, weights_mid, weights_upper = get_membership_luts(
resolution=LUT_RESOLUTION,
lower_threshold=threshold_dark, # defines lower cutofd
upper_threshold=threshold_bright, # defines upper cutofd
verbose=verbose
)
lut_resolution = len(weights_lower) - 1
weights_coarse = np.zeros(illumination_coarse.shape, dtype=float)
weights_coarse[:,:,0] = (weights_lower[(illumination_coarse[:,:,0] *
lut_resolution).astype(int)])
weights_coarse[:,:,1:-1] = (weights_mid[(illumination_coarse[:,:,1:-1] *
lut_resolution).astype(int)])
weights_coarse[:,:,-1] = (weights_upper[(illumination_coarse[:,:,-1] *
lut_resolution).astype(int)])
weights_fine = np.zeros(illumination_fine.shape, dtype=float)
weights_fine[:,:,0] = (weights_lower[(illumination_fine[:,:,0] *
lut_resolution).astype(int)])
weights_fine[:,:,1:-1] = (weights_mid[(illumination_fine[:,:,1:-1] *
lut_resolution).astype(int)])
weights_fine[:,:,-1] = (weights_upper[(illumination_fine[:,:,-1] *
lut_resolution).astype(int)])
#TODO: apply local contrast enhancement to the exposure images, 2 times
# (one for each illumination scale)
#--- Weighted average of exposures based on the exposure weights
# grayscale
exposure_coarse = weights_coarse * exposure_array_gray
exposure_coarse = (np.sum(exposure_coarse, axis=2) /
np.sum(weights_coarse, axis=2))
exposure_fine = weights_fine * exposure_array_gray
exposure_fine = (np.sum(exposure_fine, axis=2) /
np.sum(weights_fine, axis=2))
exposure_out_gray = (exposure_coarse + exposure_fine) / 2
exposure_out = exposure_out_gray
if color_exposures is True:
# red
exposure_coarse_red = weights_coarse * exposure_array_red
exposure_coarse_red = (np.sum(exposure_coarse_red, axis=2) /
np.sum(weights_coarse, axis=2))
exposure_fine_red = weights_fine * exposure_array_red
exposure_fine_red = (np.sum(exposure_fine_red, axis=2) /
np.sum(weights_fine, axis=2))
exposure_out_red = (exposure_coarse_red + exposure_fine_red) / 2
# green
exposure_coarse_green = weights_coarse * exposure_array_green
exposure_coarse_green = (np.sum(exposure_coarse_green, axis=2) /
np.sum(weights_coarse, axis=2))
exposure_fine_green = weights_fine * exposure_array_green
exposure_fine_green = (np.sum(exposure_fine_green, axis=2) /
np.sum(weights_fine, axis=2))
exposure_out_green = (exposure_coarse_green + exposure_fine_green) / 2
# blue
exposure_coarse_blue = weights_coarse * exposure_array_blue
exposure_coarse_blue = (np.sum(exposure_coarse_blue, axis=2) /
np.sum(weights_coarse, axis=2))
exposure_fine_blue = weights_fine * exposure_array_blue
exposure_fine_blue = (np.sum(exposure_fine_blue, axis=2) /
np.sum(weights_fine, axis=2))
exposure_out_blue = (exposure_coarse_blue + exposure_fine_blue) / 2
# combine all blended color channels to one image
exposure_out_color = np.zeros(
(exposure_out_gray.shape[0], exposure_out_gray.shape[1], 3),
dtype=float
)
exposure_out_color[:,:,0] = exposure_out_red
exposure_out_color[:,:,1] = exposure_out_green
exposure_out_color[:,:,2] = exposure_out_blue
exposure_out = exposure_out_color
#--- Visualizations
if verbose is True:
# display intermediate stages of the method
plt.figure()
for i in range(total_exposures):
plt.subplot(6,total_exposures,i+1)
plt.imshow(exposure_array_gray[:,:,i], cmap='gray')
plt.title('Exposure ' + str(i))
plt.axis('off')
plt.subplot(6,total_exposures,i+1+total_exposures)
plt.imshow(illumination_coarse[:,:,i], cmap='gray')
plt.title('ill.coarse ' + str(i))
plt.axis('off')
plt.subplot(6,total_exposures,i+1+(total_exposures*2))
plt.imshow(illumination_fine[:,:,i], cmap='gray')
plt.title('ill.fine ' + str(i))
plt.axis('off')
plt.subplot(6,total_exposures,i+1+(total_exposures*3))
plt.imshow(weights_coarse[:,:,i], cmap='gray')
plt.title('W.coarse ' + str(i))
plt.axis('off')
plt.subplot(6,total_exposures,i+1+(total_exposures*4))
plt.imshow(weights_fine[:,:,i], cmap='gray')
plt.title('W.fine ' + str(i))
plt.axis('off')
plt.subplot(6,total_exposures,1+(total_exposures*5))
plt.imshow(exposure_coarse, cmap='gray')
plt.title('Coarse blended')
plt.axis('off')
plt.subplot(6,total_exposures,2+(total_exposures*5))
plt.imshow(exposure_fine, cmap='gray')
plt.title('Fine blended')
plt.axis('off')
plt.subplot(6,total_exposures,3+(total_exposures*5))
plt.imshow(exposure_out_gray, cmap='gray')
plt.title('Final blend')
plt.axis('off')
plt.suptitle('List of exposures')
plt.tight_layout()
plt.tight_layout()
plt.show()
# display final color result
plt.figure()
grid = plt.GridSpec(total_exposures, total_exposures)
if color_exposures is False:
cmap = 'gray'
else:
cmap = None
for i in range(total_exposures):
plt.subplot(grid[0,i])
plt.imshow(exposure_list[indx_lum_ascending[i]], cmap=cmap)
plt.title('Exposure ' + str(i))
plt.axis('off')
plt.subplot(grid[1:,:])
plt.imshow(exposure_out, cmap=cmap)
plt.title('Final blend')
plt.axis('off')
plt.tight_layout()
plt.suptitle('Full color blend')
plt.show()
return exposure_out
def apply_local_contrast_enhancement(
image,
image_ph_mask,
degree=1.5,
verbose=False):
'''
---------------------------------------------------------------------------
Adjust local contrast in an image
---------------------------------------------------------------------------
Increase or decrease the level of local details (local contrast) in an
image. Details are defined as deviations from the local neighborhood
provided by the photometric mask. Dark regions receive also a boost in
local contrast.
INPUTS
------
image: numpy array of WxH of float [0,1]
Input grayscale image.
image_ph_mask: numpy array of WxH of float [0,1]
Grayscale image whose values represent the neighborhood of the pixels
of the input image. Usually, this image some type of edge aware
filtering, such as bilateral filtering, robust recursive envelopes etc.
degree: float [0,inf].
How to change the local contrast.
0: total attenuation of details.
<1: attenuation of details
1: details unchanged
>1: increased local details
verbose: boolean
Display outputs.
OUTPUT
------
image_out: numpy array of WxH of float [0,1]
Output image with adjusted local contrast.
'''
DARK_BOOST = 0.2
THRESHOLD_DARK_TONES = 100 / 255
detail_amplification_global = degree
image_details = image - image_ph_mask # image details
# special treatment for dark regions
detail_amplification_local = image_ph_mask / THRESHOLD_DARK_TONES
detail_amplification_local[detail_amplification_local>1] = 1
detail_amplification_local = ((1 - detail_amplification_local) *
DARK_BOOST) + 1 # [1, 1.2]
# apply all detail adjustements
image_details = (image_details *
detail_amplification_global *
detail_amplification_local)
# add details back to the local neighborhood
image_out = image_ph_mask + image_details
# stay within range
image_out = np.clip(a=image_out, a_min=0, a_max=1, out=image_out)
if verbose is True:
plt.figure()
plt.subplot(1,3,1)
plt.imshow(image, cmap='gray', vmin=0, vmax=1)
plt.title('Input image')
plt.axis('off')
plt.subplot(1,3,2)
plt.imshow(image_ph_mask, cmap='gray', vmin=0, vmax=1)
plt.title('Ph. mask')
plt.axis('off')
plt.subplot(1,3,3)
plt.imshow(image_out, cmap='gray', vmin=0, vmax=1)
plt.title('Output')
plt.axis('off')
plt.tight_layout(True)
plt.suptitle('Local contrast enhancement [x' + str(degree) + ']')
plt.show()
return image_out
def apply_spatial_tonemapping(
image,
image_ph_mask,
mid_tone=0.5,
tonal_width=0.5,
areas_dark=0.5,
areas_bright=0.5,
preserve_tones = True,
verbose=True):
'''
---------------------------------------------------------------------------
Apply spatially variable tone mapping based on the local neighborhood
---------------------------------------------------------------------------
Applies different tone mapping curves in each pixel based on its surround.
For surround, the photometric mask is used. Alternatively, other filters
could be used, like gaussian, bilateral filter, edge-avoiding wavelets etc.
Dark pixels are brightened, bright pixels are darkened, and pixels in the
mid_tonedle of the tone range are minimally affected. More information
about the technique can be found in the following papers:
Related publications:
Vonikakis, V., Andreadis, I., & Gasteratos, A. (2008). Fast centre-surround
contrast modification. IET Image processing 2(1), 19-34.
Vonikakis, V., Winkler, S. (2016). A center-surround framework for spatial
image processing. Proc. IS&T Human Vision & Electronic Imaging.
INPUTS
------
image: numpy array of WxH of float [0,1]
Input grayscale image with values in the interval [0,1].
image_ph_mask: numpy array of WxH of float [0,1]
Grayscale image whose values represent the neighborhood of the pixels
of the input image. Usually, this image some type of edge aware
filtering, such as bilateral filtering, robust recursive envelopes etc.
mid_tone: float [0,1]
The mid point between the 'dark' and 'bright' tones. This is equivalent
to a pixel value [0,255], but in the interval [0,1].
tonal_width: float [0,1]
The range of pixel values that will be affected by the correction.
Lower values will localize the enhancement only in a narrow range of
pixel values, whereas for higher values the enhancement will extend to
a greater range of pixel values.
areas_dark: float [0,1]
Degree of enhencement in the dark image areas (0 = no enhencement)
areas_bright: float [0,1]
Degree of enhencement in the bright image areas (0 = no enhencement)
preserve_tones: boolean
Whether or not to preserve well-exposed tones around the middle of the
range.
verbose: boolean
Display outputs.
OUTPUT
------
image_tonemapped: numpy array of WxH of float [0,1]
Tonemapped grayscale image.
'''
# defining parameters