-
Notifications
You must be signed in to change notification settings - Fork 0
/
delinearize-gui
executable file
·2028 lines (1530 loc) · 59.3 KB
/
delinearize-gui
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
# Copyright (C) 2019 Vladimir Nadvornik
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import tracemalloc
tracemalloc.start()
import gc
import numpy as np
import cv2
import time
import tifffile
import yaml
import argparse
import sys
from guided_filter import *
from astro_utils import noise_level
import logging
cv2.setNumThreads(-1)
def s_curve(img, center, amount):
return ( 1.0 / (1.0 + np.exp(amount *(center - img))) - 1.0 / (1.0 + np.exp(amount * center)) ) / ( 1.0 / (1.0 + np.exp(amount * (center - 1.0))) - 1.0 / (1.0 + np.exp(amount * center)) )
def erf(x):
# save the sign of x
sign = cv2.compare(x, 0, cv2.CMP_LT)
cv2.subtract(0, x, x, mask=sign)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
# A&S formula 7.1.26
t = cv2.divide(1.0, (cv2.add(cv2.multiply(x, p), 1.0)))
y = cv2.multiply(t, a5)
cv2.add(y, a4, y)
cv2.multiply(y, t, y)
cv2.add(y, a3, y)
cv2.multiply(y, t, y)
cv2.add(y, a2, y)
cv2.multiply(y, t, y)
cv2.add(y, a1, y)
cv2.multiply(y, t, y)
cv2.multiply(y, cv2.exp(cv2.multiply(x, x, scale=-1)), y)
#y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*np.exp(-x*x)
cv2.subtract(1, y, y)
cv2.subtract(0, y, y, mask=sign)
#return sign*y # erf(-x) = -erf(x)
return y
def erf2(x):
# save the sign of x
sign = np.sign(x)
x = np.abs(x)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
t = 1.0/(1.0 + p*x)
y = (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t
y = 1.0 - y * np.exp(-x*x)
return sign*y # erf(-x) = -erf(x)
def gauss_s_curve(img, center, sigma):
ret = erf(cv2.divide(cv2.subtract(img, center), sigma * 2**0.5))
cv2.add(ret, 1.0, ret)
cv2.divide(ret, 2.0, ret)
return ret
#return (1 + erf((img - center) / sigma / 2**0.5)) / 2.0
def simple_s_curve(img, center, sigma):
img = cv2.subtract(center, img)
cv2.multiply(img, 1.0/sigma, img)
cv2.exp(img, img)
cv2.add(img, 1.0, img)
cv2.divide(1.0, img, img)
return img
#1.0 / (1.0 + np.exp(amount *(center - img)))
def pyr_size(shape, l):
size = (shape[1], shape[0])
for i in range(l):
size = ( (size[0] + 1) // 2, (size[1] + 1) // 2 )
return size
def gaussian_pyr(img, depth, w = None, lpw = 0.0, ret_wp = False):
img = cv2.UMat(img)
gp = [img]
wp = None
if w is not None and lpw != 0.0:
wp = gaussian_pyr(w ** lpw, depth)
img = cv2.multiply(img, wp[0])
for i in range(depth):
img = cv2.pyrDown(img)
if w is not None and lpw != 0.0:
img1 = cv2.divide(img, wp[i + 1])
cv2.patchNaNs(img1, 0)
gp.append(img1)
else:
gp.append(img)
if ret_wp:
return gp, wp
else:
return gp
def laplacian_pyr(img, depth, gp = None, w = None, lpw = 0.0, shape = None):
if shape is None:
try:
shape = img.shape
except:
shape = img.get().shape
img = cv2.UMat(img)
wp = None
if gp is None:
gp, wp = gaussian_pyr(img, depth, w = w, lpw = lpw, ret_wp = True)
lp = [ gp[-1] ]
for i in range(depth,0,-1):
size = pyr_size(shape, i - 1) #(gp[i - 1].shape[1], gp[i - 1].shape[0])
up = cv2.pyrUp(gp[i], dstsize = size)
lap = cv2.subtract(gp[i-1], up)
if wp is not None:
mask = cv2.compare(wp[i-1], 0.0, cv2.CMP_EQ)
cv2.subtract(lap, lap, lap, mask = mask)
#lap[wp[i-1] == 0.0] = 0.0
lp.append(lap)
return lp[::-1]
def lp_collapse(pyr, shape = None):
if shape is None:
shape = pyr[0].get().shape
depth = len(pyr)
up = pyr[-1]
for i in range(depth - 2, -1, -1):
size = pyr_size(shape, i)
#size = (pyr[i].shape[1], pyr[i].shape[0])
up = cv2.pyrUp(up, dstsize = size)
up = cv2.add(up, pyr[i])
return up
def remap_f_(img, g, sigma, fact):
dif = img - g
gauss = np.exp(-dif * dif / (2 * sigma * sigma))
res = dif * fact * gauss
return res
def remap_f(img, g, sigma, lin):
ret = cv2.addWeighted(simple_s_curve(img, g, sigma), 1.0 - lin, img, lin, 0)
#cv2.imshow("remap", ret)
#cv2.waitKey(3000)
return ret
#return (1.0 - lin) * gauss_s_curve(img, g, sigma) + lin * img
def local_laplacian_pyr(img, depth, sigma, fact, l_min = 0, l_max = 0, w = None, lpw = 0.0, shape=None):
if shape is None:
shape = img.shape
img = cv2.UMat(img)
if l_max <= l_min:
return laplacian_pyr(img, depth, w = w, lpw = lpw)
l_max = min(l_max, depth + 1)
gp = gaussian_pyr(img, depth, w = w, lpw = lpw)
res = laplacian_pyr(img, depth, gp = gp, shape = shape)
steps = min(int(2.0 / sigma ) + 1, 100)
lp_lo = laplacian_pyr(remap_f(img, 0.0, sigma, fact), depth, w = w, lpw = lpw)
for j in range(steps):
print(j)
low_g = j * (1.0 / steps)
high_g = (j + 1) * (1.0 / steps)
lp_hi = laplacian_pyr(remap_f(img, high_g, sigma, fact), depth, w = w, lpw = lpw)
for i in range(l_min, l_max):
#where = np.where((gp[i] >= low_g) & (gp[i] <= high_g))
mask = cv2.inRange(gp[i], low_g, high_g)
#blend = (gp[i][where] - low_g) * steps
blend2 = cv2.subtract(gp[i], low_g)
cv2.multiply(blend2, steps, blend2)
blend1 = cv2.subtract(1.0, blend2)
cv2.multiply(blend1, lp_lo[i], blend1)
cv2.multiply(blend2, lp_hi[i], blend2)
cv2.add(blend1, blend2, res[i], mask = mask)
#res[i][where] = lp_lo[i][where] * (1.0 - blend) + lp_hi[i][where] * blend
lp_lo = lp_hi
return res
def pyr_merge(imgs, depth = 5, p = 1.0):
shape = imgs[0][0].shape
res_pyr = None
weight_pyr = None
for i, (img, w, lpw, lap_sigma, lap_lin, lap_l_min, lap_l_max) in enumerate(imgs):
#lp = laplacian_pyr(img, depth, wp = wp, lpw = lpw)
lp = local_laplacian_pyr(img, depth, lap_sigma, lap_lin, lap_l_min, lap_l_max, w = w, lpw = lpw, shape=shape)
#w = merge_weight(img, lp)
#cv2.imshow("w%d" %i, w)
wp = gaussian_pyr(w, depth)
for i, wp1 in enumerate(wp):
if i < lap_l_min:
cv2.multiply(wp[i], 0.00001, wp[i])
cv2.pow(wp[i], p, wp[i])
lpw = []
for lp1, wp1 in zip(lp, wp):
lpw.append(cv2.multiply(lp1, wp1))
if res_pyr is None:
res_pyr = lpw
weight_pyr = wp
else:
for r1, w1, lpw1, wp1 in zip(res_pyr, weight_pyr, lpw, wp):
cv2.add(r1, lpw1, r1)
cv2.add(w1, wp1, w1)
for i, w1 in enumerate(weight_pyr):
cv2.divide(res_pyr[i], w1, res_pyr[i])
return lp_collapse(res_pyr, shape=shape).get()
def star_erode(img, r):
n = r * 2
res_list = []
for i in range(0, n + 1):
elem0 = np.zeros((r * 2 + 1, r * 2 + 1), np.uint8)
cv2.line(elem0, (r,r), (int(0.5 + r + r * np.sin(0.5 * np.pi * i / n)), int(0.5 + r + r * np.cos(0.5 * np.pi * i / n))) , 1)
for j in range(0, 4):
if j == 0:
elem = elem0
elif j == 1:
elem = elem0[:, ::-1]
elif j == 2:
elem = elem0[::-1, :]
elif j == 3:
elem = elem0[::-1, ::-1]
print(elem)
res_list.append(cv2.erode(img, elem))
img = np.mean(res_list, axis = 0)
return img
def up_erode(img, r, er_shape = 0):
if er_shape == 0:
k = cv2.getStructuringElement(cv2.MORPH_RECT, (r,r))
elif er_shape == 1:
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (r,r))
else:
k = cv2.getStructuringElement(cv2.MORPH_CROSS, (r,r))
size = (img.shape[1], img.shape[0])
up = cv2.pyrUp(img)
up = cv2.erode(up, k)
return cv2.pyrDown(up, dstsize = size)
def up_dilate(img, r):
size = (img.shape[1], img.shape[0])
up = cv2.pyrUp(img)
up = cv2.dilate(up, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (r,r)))
return cv2.pyrDown(up, dstsize = size)
class ProcBase(yaml.YAMLObject):
@classmethod
def to_yaml(cls, dumper, data):
out_dict = dict((k, data.__dict__[k]) for k in cls.params)
return dumper.represent_mapping(cls.yaml_tag, out_dict)
def set_sources(self, sources):
self.sources = sources
self.changed = True
def update_params(self):
pass
def update_sources(self):
imgs = []
changed = False
for s in self.sources:
if type(s) is tuple:
img, changed1 = s[0](s[1])
changed = changed or changed1
else:
img = s
imgs.append(img)
self.params = imgs
return changed
def result(self, i = 0):
self.update_params()
changed = self.update_sources() or self.changed
if changed:
self.res = self.process(*self.params)
self.changed = False
return self.res[i], changed
class NoiseLevel(ProcBase):
yaml_tag = u'!NoiseLevel'
params = ['name']
def __init__(self, name):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def process(self, img):
img = np.atleast_3d(img)
res = []
for c in range(img.shape[2]):
cimg = img[:, :, c]
lp = laplacian_pyr(cimg, 8)
res1 = []
for i, lp1 in enumerate(lp[0:8]):
sigma = noise_level(lp1)
res1.append(sigma)
res.append(res1)
return (res,)
class Layer(ProcBase):
yaml_tag = u'!Layer'
params = ['name', 'a', 'b', 'gamma', 'median', 'median_min', 'erode', 'lap_sigma', 'lap_lin', 'lap_l_min', 'lap_l_max', 'lpw', 'center', 'sigma', 'contrast', 'l0reduce', 'l1reduce']
def __init__(self, name, a=0.3, b=10, gamma=0.5, median=0, erode=0, median_min = 0, lap_sigma = 0.25, lap_lin = 0.0, lap_l_min=0, lap_l_max=100, lpw=0.0, center=0.5, sigma=0.2, contrast=0.0, l0reduce=0, l1reduce=0):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def __repr__(self):
return "%s(a=%r, b=%r, gamma=%r, median=%r, median_min=%r, erode=%r,lap_sigma=%r, lap_lin=%r, lap_l_min=%r, lap_l_max=%r, lpw=%r, center=%r, sigma=%r, contrast=%r)" % (
self.__class__.__name__, self.a, self.b, self.gamma, self.median, self.median_min, self.erode, self.lap_sigma, self.lap_lin, self.lap_l_min, self.lap_l_max, self.lpw, self.center, self.sigma, self.contrast)
def process(self, img, mask):
if self.median > 1:
img = np.array(img, dtype=np.float32)
med = cv2.medianBlur(img, self.median)
if self.median_min > 0:
img = np.amax([img, med], axis = 0)
else:
img = med
if self.l0reduce > 0 or self.l1reduce > 0:
img = np.array(img, dtype=np.float32)
lp = laplacian_pyr(img, 2)
for i, lr in enumerate([self.l0reduce, self.l1reduce]):
if lr > 0:
alp = cv2.absdiff(lp[i], 0)
#cv2.abs(lp[i])
#lp[i] *= alp / (alp + lr)
mul = cv2.add(alp, lr)
cv2.divide(alp, mul, mul)
cv2.patchNaNs(mul, 1)
cv2.multiply(lp[i], mul, lp[i])
img = lp_collapse(lp).get()
if self.erode > 0:
img = up_erode(img, self.erode * 2 + 1) * mask + img * (1.0 - mask)
img = cv2.max(img, 0)
img = img ** self.gamma
print(self.a, self.b, 1.0 / (1.0 + np.exp(self.b * self.a)), 1.0 / (1.0 + np.exp(self.b * (self.a - 1.0))), 1.0 / (1.0 + np.exp(self.b * self.a)))
img = ( 1.0 / (1.0 + np.exp(self.b *(self.a - img))) - 1.0 / (1.0 + np.exp(self.b * self.a)) ) / ( 1.0 / (1.0 + np.exp(self.b * (self.a - 1.0))) - 1.0 / (1.0 + np.exp(self.b * self.a)) )
#img = (img - self.lo) / (self.hi - self.lo)
img = np.clip(img, 0.0, 1.0)
w = np.exp(-0.5 * ((img - self.center) / self.sigma) ** 2) #/ (self.sigma * (2 * np.pi)**0.5)
print("weight", cv2.minMaxLoc(w))
if self.contrast != 0:
# g1 = cv2.GaussianBlur(img, (9, 9), 1)
# g3 = cv2.GaussianBlur(img, (9, 9), 2)
# c = np.abs(g3 - g1)
# #c = cv2.GaussianBlur(c, (9, 9), 2)
# w += c * self.contrast
w += mask * self.contrast
w = np.clip(w, 0.0, 1.0)
return (img, w, self.lpw, self.lap_sigma, self.lap_lin, self.lap_l_min, self.lap_l_max)
def is_disabled(self):
return False
class Lum(ProcBase):
yaml_tag = u'!Lum'
params = ['name', 'offset', 'red', 'green', 'blue', 'offset2','red2', 'green2', 'blue2', 'offset_lum', 'lum']
def __init__(self, name, offset=0.0, red=0.3, green=0.6, blue=0.1, offset2=0.0, red2=0, green2=0, blue2=0, offset_lum=0.0, lum=0):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
self.auto = 0
def process(self, img, l, imc, img_noise, iml_noise, imc_noise):
print("lum noise", img_noise, iml_noise, imc_noise)
if self.auto >= 2:
r_var = np.sum(np.array(img_noise[0][0:3]) ** 2)
g_var = np.sum(np.array(img_noise[1][0:3]) ** 2)
b_var = np.sum(np.array(img_noise[2][0:3]) ** 2)
if iml_noise is not None:
l_var = np.sum(np.array(iml_noise[0][0:3]) ** 2)
else:
l_var = 0
if imc_noise is not None:
r2_var = np.sum(np.array(imc_noise[0][0:3]) ** 2)
g2_var = np.sum(np.array(imc_noise[1][0:3]) ** 2)
b2_var = np.sum(np.array(imc_noise[2][0:3]) ** 2)
else:
r2_var = 0
g2_var = 0
b2_var = 0
print("var ", r_var, g_var, b_var)
print("var2 ", r2_var, g2_var, b2_var)
print("varl ", l_var)
self.red = 0
self.green = 0
self.blue = 0
self.red2 = 0
self.green2 = 0
self.blue2 = 0
self.lum = 0
if r_var > 0:
self.red = 1.0 / r_var
if g_var > 0:
self.green = 1.0 / g_var
if b_var > 0:
self.blue = 1.0 / b_var
if r2_var > 0:
self.red2 = 1.0 / r2_var
if g2_var > 0:
self.green2 = 1.0 / g2_var
if b2_var > 0:
self.blue2 = 1.0 / b2_var
if l_var > 0:
self.lum = 1.0 / l_var
if self.auto >= 1:
s = self.red + self.green + self.blue + self.lum + self.red2 + self.green2 + self.blue2
self.red /= s
self.green /= s
self.blue /= s
self.red2 /= s
self.green2 /= s
self.blue2 /= s
self.lum /= s
self.auto = 0
print(self.red, self.green, self.blue, self.red2, self.green2, self.blue2, self.lum)
img = img + self.offset
img[:,:, 0] *= self.red
img[:,:, 1] *= self.green
img[:,:, 2] *= self.blue
l_channel_o = img[:,:, 0] + img[:,:, 1] + img[:,:, 2]
filt_img = img
if l is not None:
l = l + self.offset_lum
l = l * self.lum
l_channel_o += l
filt_img[:,:, 0] += l
filt_img[:,:, 1] += l
filt_img[:,:, 2] += l
else:
self.lum = 0
if imc is not None:
imc = imc + self.offset2
imc[:,:, 0] *= self.red2
imc[:,:, 1] *= self.green2
imc[:,:, 2] *= self.blue2
l_channel_o += imc[:,:, 0] + imc[:,:, 1] + imc[:,:, 2]
filt_img[:,:, 0] += imc[:,:, 0]
filt_img[:,:, 1] += imc[:,:, 1]
filt_img[:,:, 2] += imc[:,:, 2]
else:
self.red2 = 0
self.green2 = 0
self.blue2 = 0
l_channel_o /= self.red + self.green + self.blue + self.lum + self.red2 + self.green2 + self.blue2
l_channel_o = cv2.max(l_channel_o, 0)
filt_img = cv2.max(filt_img, 0)
return l_channel_o, filt_img
class ColorLayer(ProcBase):
yaml_tag = u'!ColorLayer'
params = ['name', 'offset', 'offset_r', 'offset_b', 'thr', 'saturation', 'wb_r', 'wb_b', 'r_g', 'b_g', 'scnr', 'c_red', 'c_blue', 'matrix', 'normalize']
def __init__(self, name, offset=0.0, offset_r=0.0, offset_b=0.0, thr=0.0, saturation=1.0, wb_r=1.0, wb_b=1.0, r_g=0.0, b_g=0.0, scnr=0, c_red=0.3, c_blue=0.3, matrix=None, normalize=False):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
self.c_green = 1.0 - self.c_red - self.c_blue
global args
if args.matrix is not None:
self.matrix = args.matrix
def process(self, img):
img_o = img
img = np.array(img, copy=True)
if self.normalize:
print(img)
img += self.offset
if self.matrix is not None:
m = np.array(self.matrix).reshape((3, 3)).T
img[:, :] = np.dot(img[:, :], m)
img[:,:, 0] += self.offset_r
img[:,:, 2] += self.offset_b
img[:,:, 0] = img[:,:, 0] * self.wb_r - self.offset * (self.wb_r - 1)
img[:,:, 2] = img[:,:, 2] * self.wb_b - self.offset * (self.wb_b - 1)
#img[:,:, 1] = np.maximum(img[:,:, 1], 0.5 * (img[:,:, 0] + img[:,:, 2]))
if self.scnr == 1:
img[:,:, 1] = np.minimum(img[:,:, 1], 0.5 * (img[:,:, 0] + img[:,:, 2]))
elif self.scnr == 3:
img[:,:, 2] = np.minimum(img[:,:, 2], 0.5 * (img[:,:, 0] + img[:,:, 1]))
elif self.scnr == 5:
img[:,:, 0] = np.minimum(img[:,:, 0], 0.5 * (img[:,:, 1] + img[:,:, 2]))
elif self.scnr == 2:
img[:,:, 0] = np.maximum(img[:,:, 0], 0.5 * (img[:,:, 1] + img[:,:, 2]))
if self.scnr == 4:
img[:,:, 1] = np.maximum(img[:,:, 1], 0.5 * (img[:,:, 0] + img[:,:, 2]))
elif self.scnr == 6:
img[:,:, 2] = np.maximum(img[:,:, 2], 0.5 * (img[:,:, 0] + img[:,:, 1]))
l_channel = img[:,:, 0] * self.c_red + img[:,:, 1] * self.c_green + img[:,:, 2] * self.c_blue
l_channel = np.array(l_channel, dtype=np.float32)
cr_channel = ((img[:,:, 0] * (1.0 + self.r_g) - img[:,:, 1] * self.r_g ) - l_channel) / (1.0 - self.c_red)
cb_channel = ((img[:,:, 2] * (1.0 + self.b_g) - img[:,:, 1] * self.b_g ) - l_channel) / (1.0 - self.c_blue)
l_channel = cv2.max(l_channel, 0)
l_div = cv2.max(l_channel + self.thr, 1e-6)
cr_channel *= self.saturation * l_channel / l_div
cb_channel *= self.saturation * l_channel / l_div
col = cv2.merge((l_channel + cr_channel * (1.0 - self.c_red) , l_channel - cr_channel * (1.0 - self.c_red) * self.c_red / self.c_green - cb_channel * (1.0 - self.c_blue) * self.c_blue / self.c_green , l_channel + cb_channel * (1.0 - self.c_blue)))
col = cv2.max(col, 0)
for i in range(3):
if not np.any(img_o[:, :, i]):
col[:, :, i] = 0
if self.normalize:
colmax = np.amax(col)
col = col / colmax
l_channel /= colmax
return (col, l_channel, cr_channel / l_div, cb_channel / l_div)
def apply_col(self, l_channel, cr_channel, cb_channel):
cr_channel = cr_channel * l_channel
cb_channel = cb_channel * l_channel
res = cv2.merge((l_channel + cr_channel * (1.0 - self.c_red) , l_channel - cr_channel * (1.0 - self.c_red) * self.c_red / self.c_green - cb_channel * (1.0 - self.c_blue) * self.c_blue / self.c_green , l_channel + cb_channel * (1.0 - self.c_blue)))
res /= np.amax(l_channel)
res[res < 0] = 0
return res
class ColorFusion(ProcBase):
yaml_tag = u'!ColorFusion'
params = ['name', 'thr', 'high_pass', 'hp_r1', 'hp_r2', 'gf_r', 'gf_eps', 'saturation', 'wb_r', 'wb_b', 'mask_w', 'mask_sat', 'mask_thr', 'c_red', 'c_blue', 'color2', 'gamma2', 'mix2', 'stars2']
def __init__(self, name, thr=0.0, high_pass=0.0, hp_r1=1, hp_r2=1, gf_r=0, gf_eps=0.01, saturation=1.0, wb_r=1.0, wb_b=1.0, mask_w=1.0, mask_sat=1.0, mask_thr=0.0, c_red=0.3, c_blue=0.3, color2=0, gamma2=1.0, mix2=0, stars2=0):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
self.c_green = 1.0 - self.c_red - self.c_blue
def process(self, img, imc, filt_img, color_mask, star_mask, lum):
img = np.array(img, copy=True)
lum = np.array(lum, copy=True)
over_thr = 0.50
if img.shape[2] == 1:
over_mask = (img[:,:, 0] > np.amax(img[:,:, 0]) * over_thr)
else:
over_mask = (img[:,:, 0] > np.amax(img[:,:, 0]) * over_thr) | (img[:,:, 1] > np.amax(img[:,:, 1]) * over_thr) | (img[:,:, 2] > np.amax(img[:,:, 2]) * over_thr)
over_mask = np.array(np.logical_not(over_mask), dtype=np.float32)
if imc is not None:
#img = np.maximum(img, imc * self.color2)
imc = imc ** self.gamma2 * self.color2
if self.mix2 > 0:
img = (img ** self.mix2 + imc ** self.mix2) ** (1.0 / self.mix2)
star_mask = star_mask * self.stars2
img = imc * star_mask[:, :, None] + img * (1.0 - star_mask)[:, :, None]
img[:,:, 0] = img[:,:, 0] * self.wb_r
img[:,:, 2] = img[:,:, 2] * self.wb_b
l_channel = img[:,:, 0] * self.c_red + img[:,:, 1] * self.c_green + img[:,:, 2] * self.c_blue
l_channel = np.array(l_channel, dtype=np.float32)
cr_channel = ((img[:,:, 0]) - l_channel) / (1.0 - self.c_red)
cb_channel = ((img[:,:, 2]) - l_channel) / (1.0 - self.c_blue)
r1 = self.hp_r1 * 2 + 1
r2 = self.hp_r2 * 2 + 1
hp = l_channel - cv2.GaussianBlur(l_channel, (r1, r1), 0)
hp = np.abs(hp)
hp = cv2.GaussianBlur(hp, (r2, r2), 0)
hp *= self.high_pass
l_div = l_channel + self.thr + hp
cr_channel = cv2.divide(cr_channel, l_div)
cb_channel = cv2.divide(cb_channel, l_div)
#over_mask[np.abs(cr_channel) < hp] = 0
#over_mask[np.abs(cb_channel) < hp] = 0
#over_mask -= np.abs(cr_channel) + np.abs(cb_channel)
#over_mask = np.clip(over_mask, 0, 1)
r_pyr = laplacian_pyr(cr_channel, 8, w = over_mask, lpw = 1.0)
b_pyr = laplacian_pyr(cb_channel, 8, w = over_mask, lpw = 1.0)
cr_channel = lp_collapse(r_pyr).get()
cb_channel = lp_collapse(b_pyr).get()
over_mask = np.clip(over_mask - color_mask * self.mask_w, 0, 1)
r_pyr = laplacian_pyr(cr_channel, 8, w = over_mask, lpw = 1.0)
b_pyr = laplacian_pyr(cb_channel, 8, w = over_mask, lpw = 1.0)
cr_channel_masked = lp_collapse(r_pyr).get()
cb_channel_masked = lp_collapse(b_pyr).get()
l_channel_bg = l_channel - cv2.erode(l_channel, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20)))
mask_sat = self.mask_sat * l_channel_bg / np.maximum(l_channel_bg + self.mask_thr, 1.0e-12)
cr_channel = (cr_channel - cr_channel_masked) * mask_sat + cr_channel_masked
cb_channel = (cb_channel - cb_channel_masked) * mask_sat + cb_channel_masked
#col = cv2.merge((l_channel + cr_channel * (1.0 - self.c_red) , l_channel - cr_channel * (1.0 - self.c_red) * self.c_red / self.c_green - cb_channel * (1.0 - self.c_blue) * self.c_blue / self.c_green , l_channel + cb_channel * (1.0 - self.c_blue)))
if self.gf_r > 0:
#filt2 = GuidedFilter(l_channel, self.gf_r, self.gf_eps ** 2)
filt2 = GuidedFilter(filt_img, self.gf_r, self.gf_eps ** 2)
#col = filt2.filter(col)
#filt2 = cv2.ximgproc.createGuidedFilter(img, self.gf_r, self.gf_eps)
cr_channel = filt2.filter(cr_channel)
cb_channel = filt2.filter(cb_channel)
#l_channel = l_channel_o
#l_channel[l_channel < 0] = 0
# l_channel2 = col[:,:, 0] * self.red + col[:,:, 1] * self.green + col[:,:, 2] * self.blue
# cr_channel = (col[:,:, 0] - l_channel2) / (1.0 - self.red)
# cb_channel = (col[:,:, 2] - l_channel2) / (1.0 - self.blue)
cr_channel *= self.saturation
cb_channel *= self.saturation
cv2.imshow("r", cr_channel * 0.5 + 0.5)
cv2.imshow("b", cb_channel * 0.5 + 0.5)
cv2.imshow("m", over_mask)
return cr_channel, cb_channel, lum, self.c_red, self.c_green, self.c_blue
def apply_col(self, l_channel, cr_channel, cb_channel):
cr_channel = cr_channel * l_channel
cb_channel = cb_channel * l_channel
res = cv2.merge((l_channel + cr_channel * (1.0 - self.c_red) , l_channel - cr_channel * (1.0 - self.c_red) * self.c_red / self.c_green - cb_channel * (1.0 - self.c_blue) * self.c_blue / self.c_green , l_channel + cb_channel * (1.0 - self.c_blue)))
res /= np.amax(l_channel)
res[res < 0] = 0
return res
class ColorApply(ProcBase):
yaml_tag = u'!ColorApply'
params = ['name', ]
def __init__(self, name):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def process(self, l_channel, cr_channel, cb_channel, c_red, c_green, c_blue):
cr_channel = cr_channel * l_channel
cb_channel = cb_channel * l_channel
res = cv2.merge((l_channel + cr_channel * (1.0 - c_red) , l_channel - cr_channel * (1.0 - c_red) * c_red / c_green - cb_channel * (1.0 - c_blue) * c_blue / c_green , l_channel + cb_channel * (1.0 - c_blue)))
res /= np.amax(l_channel)
res[res < 0] = 0
return (res,)
class RGB(ProcBase):
yaml_tag = u'!RGB'
params = ['name', "median", "med_hi", "med_lo", "mask_med", "m_med_hi", "m_med_lo", "erode", "er_shape"]
def __init__(self, name, median=0, med_hi=0, med_lo=0, mask_med=0, m_med_hi=0, m_med_lo=0, erode=0, er_shape=0):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def __repr__(self):
return self.__class__.__name__ + '(' + ', '.join([ "%s=%r" % (p, self.__dict__[p]) for p in self.__class__.params ]) + ')'
def process(self, img, mask):
img = np.array(img, copy=True)
img = np.atleast_3d(img)
if self.median > 0:
med = cv2.medianBlur(img, self.median * 2 + 1)
med = np.atleast_3d(med)
if self.med_hi > 0:
hi = med > img
img[hi] = img[hi] * (1.0 - self.med_hi) + med[hi] * self.med_hi
if self.med_lo > 0:
lo = med < img
img[lo] = img[lo] * (1.0 - self.med_lo) + med[lo] * self.med_lo
if self.mask_med > 0:
img_m = np.array(img, copy=True)
med = cv2.medianBlur(img_m, self.mask_med * 2 + 1)
med = np.atleast_3d(med)
if self.m_med_hi > 0:
hi = med > img_m
img_m[hi] = img_m[hi] * (1.0 - self.m_med_hi) + med[hi] * self.m_med_hi
if self.m_med_lo > 0:
lo = med < img_m
img_m[lo] = img_m[lo] * (1.0 - self.m_med_lo) + med[lo] * self.m_med_lo
for c in range(img.shape[2]):
img[:,:, c] = img[:,:, c] * (1.0 - mask) + img_m[:,:, c] * mask
if self.erode > 0:
img_m = up_erode(img, self.erode * 2 + 1, self.er_shape)
img_m = np.atleast_3d(img_m)
for c in range(img.shape[2]):
img[:,:, c] = img[:,:, c] * (1.0 - mask) + img_m[:,:, c] * mask
return (img,)
class StarMask(ProcBase):
yaml_tag = u'!StarMask'
params = ['name', 'channels', 'level', 'min_level', 'thr', 'dilate', 'blur']
def __init__(self, name, channels=1, level=3, min_level=0, thr=4, dilate=1, blur=1):
print("starmask init")
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def __repr__(self):
return "%s(channels=%r, level=%r, thr=%r, dilate=%r, blur=%r)" % (
self.__class__.__name__, self.channels, self.level, self.thr, self.dilate, self.blur)
def process(self, img, iml, img_noise, iml_noise):
img = np.atleast_3d(img)
if self.channels == 5:
return (np.zeros_like(img[:, :, 0]),)
if self.channels == 4 and iml is None:
return (np.zeros_like(img[:, :, 0]),)
if self.channels == 0:
return (np.ones_like(img[:, :, 0]),)
print("starmask")
layers = []
noise = []
for c in range(img.shape[2]):
layers.append(img[:, :, c])
noise.append(img_noise[c])
if iml is not None:
layers.append(np.atleast_3d(iml)[:, :, 0])
noise.append(iml_noise[0])
gmp = None
for c, cimg in enumerate(layers):
lp = laplacian_pyr(cimg, self.level)
mp = []
for i, lp1 in enumerate(lp[0:self.level]):
if i >= self.min_level:
sigma = noise[c][i]
print("sigma", sigma)
mask = lp1.get() > self.thr * sigma
mask = mask.astype(np.uint8)
else:
mask = np.zeros_like(lp1.get(), dtype=np.uint8)
mp.append(mask)
if gmp is None:
gmp = mp
else:
for i, mp1 in enumerate(mp):
gmp[i] += mp1
for i, mp1 in enumerate(gmp):
print(mp1)
mp1 = np.array(mp1 >= self.channels, dtype=np.float32)
mp1 = up_dilate(mp1, self.dilate * 2 + 1)
gmp[i] = mp1
up = gmp[-1]
for i in range(self.level - 2, -1, -1):
size = pyr_size(img.shape, i)
#size = (gmp[i].shape[1], gmp[i].shape[0])
print(up.shape, gmp[i].shape)
up = cv2.pyrUp(up, dstsize = size)
up += gmp[i]
if self.blur > 0:
up = cv2.GaussianBlur(up, (9, 9), self.blur)
up = np.clip(up, 0, 1)
return (up,)
class Fusion(ProcBase):
yaml_tag = u'!Fusion'
params = ['name', 'depth', 'pw']
def __init__(self, name, depth=50, pw=1.0):
for p in self.__class__.params:
self.__dict__[p] = vars()[p]
def process(self, *args):
imgs = list(zip(*(iter(args),) * 7))
lc = pyr_merge(imgs, self.depth, self.pw)
return (lc,)
def __repr__(self):
return "%s(depth=%r, pw=%r)" % (
self.__class__.__name__, self.depth, self.pw)
class GuiBase:
def __init__(self, shape):
self.x = 0
self.y = 0
self.w = min(shape[1], 800)
self.h = min(shape[0], 600)
self.click_x = 0
self.click_y = 0
self.zoom = False
self.cur_x = 0
self.cur_y = 0
cv2.namedWindow(self.name)
cv2.setMouseCallback(self.name, self.mouse)
self.draw = True
self.draw_time = 0
self.changed = True
self.shape = shape
def set_img(self, img):
self.img = np.array(img, copy = True)
self.draw = True
self.draw_time = 0
def update(self, x):
self.draw = True
self.changed = True
self.draw_time = time.time()
def mouse(self, event,x,y,flags,param):
self.active_time = time.time()
print("mouse", event)
if event == cv2.EVENT_LBUTTONDOWN:
self.click_x = x
self.click_y = y
elif event == cv2.EVENT_LBUTTONUP:
dx = x - self.click_x
dy = y - self.click_y
if not self.zoom:
self.zoom = True
self.x = np.clip(x * self.shape[1] // self.w - self.w // 2, 0, self.shape[1] - self.w)
self.y = np.clip(y * self.shape[0] // self.h - self.h // 2, 0, self.shape[0] - self.h)
elif dx == 0 and dy == 0:
self.zoom = False
else:
self.x = np.clip(self.x - dx, 0, self.shape[1] - self.w)
self.y = np.clip(self.y - dy, 0, self.shape[0] - self.h)
self.draw = True
self.draw_time = time.time()
if event == cv2.EVENT_MBUTTONDOWN:
if self.zoom:
self.cur_x = x + self.x
self.cur_y = y + self.y
else:
self.cur_x = x * self.shape[1] // self.w
self.cur_y = y * self.shape[0] // self.h
self.draw = True
self.draw_time = time.time()
self.mid_click()
self.update_params()
def mid_click(self):
pass
def redraw(self):
if not self.draw or time.time() - self.draw_time < 0.1:
return False
self.do_redraw()
self.draw = False
return True
# def get_img(self, img = None):
# if img is None:
# img = self.img
# if self.zoom: