-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.py
9246 lines (6891 loc) · 361 KB
/
test.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
"""
import os
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
os.environ["PLAIDML_DEVICE_IDS"] = "opencl_nvidia_geforce_gtx_1060_6gb.0"
import keras
KL = keras.layers
x = KL.Input ( (128,128,64) )
label = KL.Input( (1,), dtype="int32")
y = x[:,:,:, label[0,0] ]
import code
code.interact(local=dict(globals(), **locals()))
"""
# import os
# os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
# os.environ["PLAIDML_DEVICE_IDS"] = "opencl_nvidia_geforce_gtx_1060_6gb.0"
# import keras
# K = keras.backend
# import numpy as np
# shape = (64, 64, 3)
# def encflow(x):
# x = keras.layers.Conv2D(128, 5, strides=2, padding="same")(x)
# x = keras.layers.Conv2D(256, 5, strides=2, padding="same")(x)
# x = keras.layers.Dense(3)(keras.layers.Flatten()(x))
# return x
# def modelify(model_functor):
# def func(tensor):
# return keras.models.Model (tensor, model_functor(tensor))
# return func
# encoder = modelify (encflow)( keras.Input(shape) )
# inp = x = keras.Input(shape)
# code_t = encoder(x)
# loss = K.mean(code_t)
# train_func = K.function ([inp],[loss], keras.optimizers.Adam().get_updates(loss, encoder.trainable_weights) )
# train_func ([ np.zeros ( (1, 64, 64, 3) ) ])
# import code
# code.interact(local=dict(globals(), **locals()))
##########################
"""
import os
os.environ['TF_CUDNN_WORKSPACE_LIMIT_IN_MB'] = '1024'
#os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0'
import numpy as np
import tensorflow as tf
keras = tf.keras
KL = keras.layers
K = keras.backend
bgr_shape = (128, 128, 3)
batch_size = 80#132 #max -tf.1.11.0-cuda 9
#batch_size = 86 #max -tf.1.13.1-cuda 10
class PixelShuffler(keras.layers.Layer):
def __init__(self, size=(2, 2), data_format=None, **kwargs):
super(PixelShuffler, self).__init__(**kwargs)
self.size = size
def call(self, inputs):
input_shape = K.int_shape(inputs)
if len(input_shape) != 4:
raise ValueError('Inputs should have rank ' +
str(4) +
'; Received input shape:', str(input_shape))
batch_size, h, w, c = input_shape
if batch_size is None:
batch_size = -1
rh, rw = self.size
oh, ow = h * rh, w * rw
oc = c // (rh * rw)
out = K.reshape(inputs, (batch_size, h, w, rh, rw, oc))
out = K.permute_dimensions(out, (0, 1, 3, 2, 4, 5))
out = K.reshape(out, (batch_size, oh, ow, oc))
return out
def compute_output_shape(self, input_shape):
if len(input_shape) != 4:
raise ValueError('Inputs should have rank ' +
str(4) +
'; Received input shape:', str(input_shape))
height = input_shape[1] * self.size[0] if input_shape[1] is not None else None
width = input_shape[2] * self.size[1] if input_shape[2] is not None else None
channels = input_shape[3] // self.size[0] // self.size[1]
if channels * self.size[0] * self.size[1] != input_shape[3]:
raise ValueError('channels of input and size are incompatible')
return (input_shape[0],
height,
width,
channels)
def get_config(self):
config = {'size': self.size}
base_config = super(PixelShuffler, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def upscale (dim):
def func(x):
return PixelShuffler()((KL.Conv2D(dim * 4, kernel_size=3, strides=1, padding='same')(x)))
return func
inp = KL.Input(bgr_shape)
x = inp
x = KL.Conv2D(128, 5, strides=2, padding='same')(x)
x = KL.Conv2D(256, 5, strides=2, padding='same')(x)
x = KL.Conv2D(512, 5, strides=2, padding='same')(x)
x = KL.Conv2D(1024, 5, strides=2, padding='same')(x)
x = KL.Dense(1024)(KL.Flatten()(x))
x = KL.Dense(8 * 8 * 1024)(x)
x = KL.Reshape((8, 8, 1024))(x)
x = upscale(512)(x)
x = upscale(256)(x)
x = upscale(128)(x)
x = upscale(64)(x)
x = KL.Conv2D(3, 5, strides=1, padding='same')(x)
model = keras.models.Model ([inp], [x])
model.compile(optimizer=keras.optimizers.Adam(lr=5e-5, beta_1=0.5, beta_2=0.999), loss='mae')
training_data = np.zeros ( (batch_size,128,128,3) )
loss = model.train_on_batch( [training_data], [training_data] )
print ("FINE")
import sys
sys.exit()
"""
import os
#os.environ["DFL_PLAIDML_BUILD"] = "1"
import pickle
import math
import sys
import argparse
from core import pathex
from core import osex
from facelib import LandmarksProcessor
from facelib import FaceType
from pathlib import Path
import numpy as np
from numpy import linalg as npla
import cv2
import time
import multiprocessing
import threading
import traceback
from tqdm import tqdm
from DFLIMG import *
from core.cv2ex import *
import shutil
from core import imagelib
from core.interact import interact as io
def umeyama(src, dst, estimate_scale):
"""Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate scaling factor.
Returns
-------
T : (N + 1, N + 1)
The homogeneous similarity transformation matrix. The matrix contains
NaN values only if the problem is not well-conditioned.
References
----------
.. [1] "Least-squares estimation of transformation parameters between two
point patterns", Shinji Umeyama, PAMI 1991, DOI: 10.1109/34.88573
"""
num = src.shape[0]
dim = src.shape[1]
# Compute mean of src and dst.
src_mean = src.mean(axis=0)
dst_mean = dst.mean(axis=0)
# Subtract mean from src and dst.
src_demean = src - src_mean
dst_demean = dst - dst_mean
# Eq. (38).
A = np.dot(dst_demean.T, src_demean) / num
# Eq. (39).
d = np.ones((dim,), dtype=np.double)
if np.linalg.det(A) < 0:
d[dim - 1] = -1
T = np.eye(dim + 1, dtype=np.double)
U, S, V = np.linalg.svd(A)
# Eq. (40) and (43).
rank = np.linalg.matrix_rank(A)
if rank == 0:
return np.nan * T
elif rank == dim - 1:
if np.linalg.det(U) * np.linalg.det(V) > 0:
T[:dim, :dim] = np.dot(U, V)
else:
s = d[dim - 1]
d[dim - 1] = -1
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V))
d[dim - 1] = s
else:
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V.T))
if estimate_scale:
# Eq. (41) and (42).
scale = 1.0 / src_demean.var(axis=0).sum() * np.dot(S, d)
else:
scale = 1.0
T[:dim, dim] = dst_mean - scale * np.dot(T[:dim, :dim], src_mean.T)
T[:dim, :dim] *= scale
return T
def random_transform(image, rotation_range=10, zoom_range=0.5, shift_range=0.05, random_flip=0):
h, w = image.shape[0:2]
rotation = np.random.uniform(-rotation_range, rotation_range)
scale = np.random.uniform(1 - zoom_range, 1 + zoom_range)
tx = np.random.uniform(-shift_range, shift_range) * w
ty = np.random.uniform(-shift_range, shift_range) * h
mat = cv2.getRotationMatrix2D((w // 2, h // 2), rotation, scale)
mat[:, 2] += (tx, ty)
result = cv2.warpAffine(
image, mat, (w, h), borderMode=cv2.BORDER_REPLICATE)
if np.random.random() < random_flip:
result = result[:, ::-1]
return result
# get pair of random warped images from aligned face image
def random_warp(image, coverage=160, scale = 5, zoom = 1):
assert image.shape == (256, 256, 3)
range_ = np.linspace(128 - coverage//2, 128 + coverage//2, 5)
mapx = np.broadcast_to(range_, (5, 5))
mapy = mapx.T
mapx = mapx + np.random.normal(size=(5,5), scale=scale)
mapy = mapy + np.random.normal(size=(5,5), scale=scale)
interp_mapx = cv2.resize(mapx, (80*zoom,80*zoom))[8*zoom:72*zoom,8*zoom:72*zoom].astype('float32')
interp_mapy = cv2.resize(mapy, (80*zoom,80*zoom))[8*zoom:72*zoom,8*zoom:72*zoom].astype('float32')
warped_image = cv2.remap(image, interp_mapx, interp_mapy, cv2.INTER_LINEAR)
src_points = np.stack([mapx.ravel(), mapy.ravel() ], axis=-1)
dst_points = np.mgrid[0:65*zoom:16*zoom,0:65*zoom:16*zoom].T.reshape(-1,2)
mat = umeyama(src_points, dst_points, True)[0:2]
target_image = cv2.warpAffine(image, mat, (64*zoom,64*zoom))
return warped_image, target_image
def input_process(stdin_fd, sq, str):
sys.stdin = os.fdopen(stdin_fd)
try:
inp = input (str)
sq.put (True)
except:
sq.put (False)
def input_in_time (str, max_time_sec):
sq = multiprocessing.Queue()
p = multiprocessing.Process(target=input_process, args=( sys.stdin.fileno(), sq, str))
p.start()
t = time.time()
inp = False
while True:
if not sq.empty():
inp = sq.get()
break
if time.time() - t > max_time_sec:
break
p.terminate()
sys.stdin = os.fdopen( sys.stdin.fileno() )
return inp
def subprocess(sq,cq):
prefetch = 2
while True:
while prefetch > -1:
cq.put ( np.array([1]) ) #memory leak numpy==1.16.0 , but all fine in 1.15.4
#cq.put ( [1] ) #no memory leak
prefetch -= 1
sq.get() #waiting msg from serv to continue posting
prefetch += 1
def get_image_hull_mask (image_shape, image_landmarks):
if len(image_landmarks) != 68:
raise Exception('get_image_hull_mask works only with 68 landmarks')
hull_mask = np.zeros(image_shape[0:2]+(1,),dtype=np.float32)
cv2.fillConvexPoly( hull_mask, cv2.convexHull( np.concatenate ( (image_landmarks[0:17], image_landmarks[48:], [image_landmarks[0]], [image_landmarks[8]], [image_landmarks[16]])) ), (1,) )
cv2.fillConvexPoly( hull_mask, cv2.convexHull( np.concatenate ( (image_landmarks[27:31], [image_landmarks[33]]) ) ), (1,) )
cv2.fillConvexPoly( hull_mask, cv2.convexHull( np.concatenate ( (image_landmarks[17:27], [image_landmarks[0]], [image_landmarks[27]], [image_landmarks[16]], [image_landmarks[33]])) ), (1,) )
return hull_mask
def umeyama(src, dst, estimate_scale):
"""Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate scaling factor.
Returns
-------
T : (N + 1, N + 1)
The homogeneous similarity transformation matrix. The matrix contains
NaN values only if the problem is not well-conditioned.
References
----------
.. [1] "Least-squares estimation of transformation parameters between two
point patterns", Shinji Umeyama, PAMI 1991, DOI: 10.1109/34.88573
"""
num = src.shape[0]
dim = src.shape[1]
# Compute mean of src and dst.
src_mean = src.mean(axis=0)
dst_mean = dst.mean(axis=0)
# Subtract mean from src and dst.
src_demean = src - src_mean
dst_demean = dst - dst_mean
# Eq. (38).
A = np.dot(dst_demean.T, src_demean) / num
# Eq. (39).
d = np.ones((dim,), dtype=np.double)
if np.linalg.det(A) < 0:
d[dim - 1] = -1
T = np.eye(dim + 1, dtype=np.double)
U, S, V = np.linalg.svd(A)
# Eq. (40) and (43).
rank = np.linalg.matrix_rank(A)
if rank == 0:
return np.nan * T
elif rank == dim - 1:
if np.linalg.det(U) * np.linalg.det(V) > 0:
T[:dim, :dim] = np.dot(U, V)
else:
s = d[dim - 1]
d[dim - 1] = -1
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V))
d[dim - 1] = s
else:
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V.T))
if estimate_scale:
# Eq. (41) and (42).
scale = 1.0 / src_demean.var(axis=0).sum() * np.dot(S, d)
else:
scale = 1.0
T[:dim, dim] = dst_mean - scale * np.dot(T[:dim, :dim], src_mean.T)
T[:dim, :dim] *= scale
return T
#mean_face_x = np.array([
#0.000213256, 0.0752622, 0.18113, 0.29077, 0.393397, 0.586856, 0.689483, 0.799124,
#0.904991, 0.98004, 0.490127, 0.490127, 0.490127, 0.490127, 0.36688, 0.426036,
#0.490127, 0.554217, 0.613373, 0.121737, 0.187122, 0.265825, 0.334606, 0.260918,
#0.182743, 0.645647, 0.714428, 0.793132, 0.858516, 0.79751, 0.719335, 0.254149,
#0.340985, 0.428858, 0.490127, 0.551395, 0.639268, 0.726104, 0.642159, 0.556721,
#0.490127, 0.423532, 0.338094, 0.290379, 0.428096, 0.490127, 0.552157, 0.689874,
#0.553364, 0.490127, 0.42689 ])
#
#mean_face_y = np.array([
#0.106454, 0.038915, 0.0187482, 0.0344891, 0.0773906, 0.0773906, 0.0344891,
#0.0187482, 0.038915, 0.106454, 0.203352, 0.307009, 0.409805, 0.515625, 0.587326,
#0.609345, 0.628106, 0.609345, 0.587326, 0.216423, 0.178758, 0.179852, 0.231733,
#0.245099, 0.244077, 0.231733, 0.179852, 0.178758, 0.216423, 0.244077, 0.245099,
#0.780233, 0.745405, 0.727388, 0.742578, 0.727388, 0.745405, 0.780233, 0.864805,
#0.902192, 0.909281, 0.902192, 0.864805, 0.784792, 0.778746, 0.785343, 0.778746,
#0.784792, 0.824182, 0.831803, 0.824182 ])
#
#landmarks_2D = np.stack( [ mean_face_x, mean_face_y ], axis=1 )
#alignments = []
#
#aligned_path_image_paths = pathex.get_image_paths("D:\\DeepFaceLab\\workspace issue\\data_dst\\aligned")
#for filepath in tqdm(aligned_path_image_paths, desc="Collecting alignments", ascii=True ):
# filepath = Path(filepath)
#
# if filepath.suffix == '.png':
# dflimg = DFLPNG.load( str(filepath), print_on_no_embedded_data=True )
# elif filepath.suffix == '.jpg':
# dflimg = DFLJPG.load ( str(filepath), print_on_no_embedded_data=True )
# else:
# print ("%s is not a dfl image file" % (filepath.name) )
#
# #source_filename_stem = Path( dflimg.get_source_filename() ).stem
# #if source_filename_stem not in alignments.keys():
# # alignments[ source_filename_stem ] = []
#
# #alignments[ source_filename_stem ].append (dflimg.get_source_landmarks())
# alignments.append (dflimg.get_source_landmarks())
import string
def tdict2kw_conv2d ( w, b=None ):
if b is not None:
return [ np.transpose(w.numpy(), [2,3,1,0]), b.numpy() ]
else:
return [ np.transpose(w.numpy(), [2,3,1,0])]
def tdict2kw_depconv2d ( w, b=None ):
if b is not None:
return [ np.transpose(w.numpy(), [2,3,0,1]), b.numpy() ]
else:
return [ np.transpose(w.numpy(), [2,3,0,1]) ]
def tdict2kw_bn2d( d, name_prefix ):
return [ d[name_prefix+'.weight'].numpy(),
d[name_prefix+'.bias'].numpy(),
d[name_prefix+'.running_mean'].numpy(),
d[name_prefix+'.running_var'].numpy() ]
def t2kw_conv2d (src):
if src.bias is not None:
return [ np.transpose(src.weight.data.cpu().numpy(), [2,3,1,0]), src.bias.data.cpu().numpy() ]
else:
return [ np.transpose(src.weight.data.cpu().numpy(), [2,3,1,0])]
def t2kw_bn2d(src):
return [ src.weight.data.cpu().numpy(), src.bias.data.cpu().numpy(), src.running_mean.cpu().numpy(), src.running_var.cpu().numpy() ]
import scipy as sp
def color_transfer_mkl(x0, x1):
eps = np.finfo(float).eps
h,w,c = x0.shape
h1,w1,c1 = x1.shape
x0 = x0.reshape ( (h*w,c) )
x1 = x1.reshape ( (h1*w1,c1) )
a = np.cov(x0.T)
b = np.cov(x1.T)
Da2, Ua = np.linalg.eig(a)
Da = np.diag(np.sqrt(Da2.clip(eps, None)))
C = np.dot(np.dot(np.dot(np.dot(Da, Ua.T), b), Ua), Da)
Dc2, Uc = np.linalg.eig(C)
Dc = np.diag(np.sqrt(Dc2.clip(eps, None)))
Da_inv = np.diag(1./(np.diag(Da)))
t = np.dot(np.dot(np.dot(np.dot(np.dot(np.dot(Ua, Da_inv), Uc), Dc), Uc.T), Da_inv), Ua.T)
mx0 = np.mean(x0, axis=0)
mx1 = np.mean(x1, axis=0)
result = np.dot(x0-mx0, t) + mx1
return np.clip ( result.reshape ( (h,w,c) ), 0, 1)
def color_transfer_idt(i0, i1, bins=256, n_rot=20):
relaxation = 1 / n_rot
h,w,c = i0.shape
h1,w1,c1 = i1.shape
i0 = i0.reshape ( (h*w,c) )
i1 = i1.reshape ( (h1*w1,c1) )
n_dims = c
d0 = i0.T
d1 = i1.T
for i in range(n_rot):
r = sp.stats.special_ortho_group.rvs(n_dims).astype(np.float32)
d0r = np.dot(r, d0)
d1r = np.dot(r, d1)
d_r = np.empty_like(d0)
for j in range(n_dims):
lo = min(d0r[j].min(), d1r[j].min())
hi = max(d0r[j].max(), d1r[j].max())
p0r, edges = np.histogram(d0r[j], bins=bins, range=[lo, hi])
p1r, _ = np.histogram(d1r[j], bins=bins, range=[lo, hi])
cp0r = p0r.cumsum().astype(np.float32)
cp0r /= cp0r[-1]
cp1r = p1r.cumsum().astype(np.float32)
cp1r /= cp1r[-1]
f = np.interp(cp0r, cp1r, edges[1:])
d_r[j] = np.interp(d0r[j], edges[1:], f, left=0, right=bins)
d0 = relaxation * np.linalg.solve(r, (d_r - d0r)) + d0
return np.clip ( d0.T.reshape ( (h,w,c) ), 0, 1)
from core import imagelib
def color_transfer_mix(img_src,img_trg):
img_src = (img_src*255.0).astype(np.uint8)
img_trg = (img_trg*255.0).astype(np.uint8)
img_src_lab = cv2.cvtColor(img_src, cv2.COLOR_BGR2LAB)
img_trg_lab = cv2.cvtColor(img_trg, cv2.COLOR_BGR2LAB)
rct_light = np.clip ( imagelib.linear_color_transfer(img_src_lab[...,0:1].astype(np.float32)/255.0,
img_trg_lab[...,0:1].astype(np.float32)/255.0 )[...,0]*255.0,
0, 255).astype(np.uint8)
img_src_lab[...,0] = (np.ones_like (rct_light)*100).astype(np.uint8)
img_src_lab = cv2.cvtColor(img_src_lab, cv2.COLOR_LAB2BGR)
img_trg_lab[...,0] = (np.ones_like (rct_light)*100).astype(np.uint8)
img_trg_lab = cv2.cvtColor(img_trg_lab, cv2.COLOR_LAB2BGR)
img_rct = imagelib.color_transfer_sot( img_src_lab.astype(np.float32), img_trg_lab.astype(np.float32) )
img_rct = np.clip(img_rct, 0, 255).astype(np.uint8)
img_rct = cv2.cvtColor(img_rct, cv2.COLOR_BGR2LAB)
img_rct[...,0] = rct_light
img_rct = cv2.cvtColor(img_rct, cv2.COLOR_LAB2BGR)
return (img_rct / 255.0).astype(np.float32)
def color_transfer_mix2(img_src,img_trg):
img_src = (img_src*255.0).astype(np.uint8)
img_trg = (img_trg*255.0).astype(np.uint8)
img_src_lab = cv2.cvtColor(img_src, cv2.COLOR_BGR2YUV)
img_trg_lab = cv2.cvtColor(img_trg, cv2.COLOR_BGR2YUV)
rct_light = np.clip ( imagelib.linear_color_transfer(img_src_lab[...,0:1].astype(np.float32)/255.0,
img_trg_lab[...,0:1].astype(np.float32)/255.0 )[...,0]*255.0,
0, 255).astype(np.uint8)
img_src_lab[...,0] = (np.ones_like (rct_light)*100).astype(np.uint8)
img_src_lab = cv2.cvtColor(img_src_lab, cv2.COLOR_YUV2BGR)
img_trg_lab[...,0] = (np.ones_like (rct_light)*100).astype(np.uint8)
img_trg_lab = cv2.cvtColor(img_trg_lab, cv2.COLOR_YUV2BGR)
img_rct = imagelib.color_transfer_sot( img_src_lab.astype(np.float32), img_trg_lab.astype(np.float32) )
img_rct = np.clip(img_rct, 0, 255).astype(np.uint8)
img_rct = cv2.cvtColor(img_rct, cv2.COLOR_BGR2YUV)
img_rct[...,0] = rct_light
img_rct = cv2.cvtColor(img_rct, cv2.COLOR_YUV2BGR)
return (img_rct / 255.0).astype(np.float32)
def nd_cor(pts1, pts2):
dtype = pts1.dtype
for iter in range(10):
dir = np.random.normal(size=2).astype(dtype)
dir /= npla.norm(dir)
proj_pts1 = pts1*dir
proj_pts2 = pts2*dir
id_pts1 = np.argsort (proj_pts1)
id_pts2 = np.argsort (proj_pts2)
def fist(pts_src, pts_dst):
rot = np.eye (3,3,dtype=np.float32)
trans = np.zeros (2, dtype=np.float32)
scaling = 1
for iter in range(10):
center1 = np.zeros (2, dtype=np.float32)
center2 = np.zeros (2, dtype=np.float32)
landmarks_2D = np.array([
[ 0.000213256, 0.106454 ], #17
[ 0.0752622, 0.038915 ], #18
[ 0.18113, 0.0187482 ], #19
[ 0.29077, 0.0344891 ], #20
[ 0.393397, 0.0773906 ], #21
[ 0.586856, 0.0773906 ], #22
[ 0.689483, 0.0344891 ], #23
[ 0.799124, 0.0187482 ], #24
[ 0.904991, 0.038915 ], #25
[ 0.98004, 0.106454 ], #26
[ 0.490127, 0.203352 ], #27
[ 0.490127, 0.307009 ], #28
[ 0.490127, 0.409805 ], #29
[ 0.490127, 0.515625 ], #30
[ 0.36688, 0.587326 ], #31
[ 0.426036, 0.609345 ], #32
[ 0.490127, 0.628106 ], #33
[ 0.554217, 0.609345 ], #34
[ 0.613373, 0.587326 ], #35
[ 0.121737, 0.216423 ], #36
[ 0.187122, 0.178758 ], #37
[ 0.265825, 0.179852 ], #38
[ 0.334606, 0.231733 ], #39
[ 0.260918, 0.245099 ], #40
[ 0.182743, 0.244077 ], #41
[ 0.645647, 0.231733 ], #42
[ 0.714428, 0.179852 ], #43
[ 0.793132, 0.178758 ], #44
[ 0.858516, 0.216423 ], #45
[ 0.79751, 0.244077 ], #46
[ 0.719335, 0.245099 ], #47
[ 0.254149, 0.780233 ], #48
[ 0.340985, 0.745405 ], #49
[ 0.428858, 0.727388 ], #50
[ 0.490127, 0.742578 ], #51
[ 0.551395, 0.727388 ], #52
[ 0.639268, 0.745405 ], #53
[ 0.726104, 0.780233 ], #54
[ 0.642159, 0.864805 ], #55
[ 0.556721, 0.902192 ], #56
[ 0.490127, 0.909281 ], #57
[ 0.423532, 0.902192 ], #58
[ 0.338094, 0.864805 ], #59
[ 0.290379, 0.784792 ], #60
[ 0.428096, 0.778746 ], #61
[ 0.490127, 0.785343 ], #62
[ 0.552157, 0.778746 ], #63
[ 0.689874, 0.784792 ], #64
[ 0.553364, 0.824182 ], #65
[ 0.490127, 0.831803 ], #66
[ 0.42689 , 0.824182 ] #67
], dtype=np.float32)
"""
( .Config()
.sample_host('src_samples', path)
.index_generator('i1', 'src_samples' )
.batch(16)
.warp_params('w1', ...)
.branch( (.Branch()
.load_sample('src_samples', 'i1')
)
)
)
"""
def _compute_fans(shape, data_format='channels_last'):
"""Computes the number of input and output units for a weight shape.
# Arguments
shape: Integer shape tuple.
data_format: Image data format to use for convolution kernels.
Note that all kernels in Keras are standardized on the
`channels_last` ordering (even when inputs are set
to `channels_first`).
# Returns
A tuple of scalars, `(fan_in, fan_out)`.
# Raises
ValueError: in case of invalid `data_format` argument.
"""
if len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
elif len(shape) in {3, 4, 5}:
# Assuming convolution kernels (1D, 2D or 3D).
# TH kernel shape: (depth, input_depth, ...)
# TF kernel shape: (..., input_depth, depth)
if data_format == 'channels_first':
receptive_field_size = np.prod(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
elif data_format == 'channels_last':
receptive_field_size = np.prod(shape[:-2])
fan_in = shape[-2] * receptive_field_size
fan_out = shape[-1] * receptive_field_size
else:
raise ValueError('Invalid data_format: ' + data_format)
else:
# No specific assumptions.
fan_in = np.sqrt(np.prod(shape))
fan_out = np.sqrt(np.prod(shape))
return fan_in, fan_out
def _create_basis(filters, size, floatx, eps_std):
if size == 1:
return np.random.normal(0.0, eps_std, (filters, size))
nbb = filters // size + 1
li = []
for i in range(nbb):
a = np.random.normal(0.0, 1.0, (size, size))
a = _symmetrize(a)
u, _, v = np.linalg.svd(a)
li.extend(u.T.tolist())
p = np.array(li[:filters], dtype=floatx)
return p
def _symmetrize(a):
return a + a.T - np.diag(a.diagonal())
def _scale_filters(filters, variance):
c_var = np.var(filters)
p = np.sqrt(variance / c_var)
return filters * p
def CAGenerateWeights ( shape, floatx, data_format, eps_std=0.05, seed=None ):
if seed is not None:
np.random.seed(seed)
fan_in, fan_out = _compute_fans(shape, data_format)
variance = 2 / fan_in
rank = len(shape)
if rank == 3:
row, stack_size, filters_size = shape
transpose_dimensions = (2, 1, 0)
kernel_shape = (row,)
correct_ifft = lambda shape, s=[None]: np.fft.irfft(shape, s[0])
correct_fft = np.fft.rfft
elif rank == 4:
row, column, stack_size, filters_size = shape
transpose_dimensions = (2, 3, 1, 0)
kernel_shape = (row, column)
correct_ifft = np.fft.irfft2
correct_fft = np.fft.rfft2
elif rank == 5:
x, y, z, stack_size, filters_size = shape
transpose_dimensions = (3, 4, 0, 1, 2)
kernel_shape = (x, y, z)
correct_fft = np.fft.rfftn
correct_ifft = np.fft.irfftn
else:
raise ValueError('rank unsupported')
kernel_fourier_shape = correct_fft(np.zeros(kernel_shape)).shape
init = []
for i in range(filters_size):
basis = _create_basis(stack_size, np.prod(kernel_fourier_shape), floatx, eps_std)
basis = basis.reshape((stack_size,) + kernel_fourier_shape)
filters = [correct_ifft(x, kernel_shape)
+ np.random.normal(0, eps_std, kernel_shape)
for x in basis]
init.append(filters)
# Format of array is now: filters, stack, row, column
init = np.array(init)
init = _scale_filters(init, variance)
return init.transpose(transpose_dimensions)
import scipy
from ctypes import *
from core.joblib import Subprocessor
class CTComputerSubprocessor(Subprocessor):
class Cli(Subprocessor.Cli):
def process_data(self, data):
idx, src_path, dst_path = data
src_path = Path(src_path)
dst_path = Path(dst_path)
src_uint8 = cv2_imread(src_path)
dst_uint8 = cv2_imread(dst_path)
src_dflimg = DFLIMG.load(src_path)
dst_dflimg = DFLIMG.load(dst_path)
if src_dflimg is None or dst_dflimg is None:
return idx, [0,0,0,0,0,0]
src_uint8 = src_uint8*LandmarksProcessor.get_image_hull_mask( src_uint8.shape, src_dflimg.get_landmarks() )
dst_uint8 = dst_uint8*LandmarksProcessor.get_image_hull_mask( dst_uint8.shape, dst_dflimg.get_landmarks() )
src = src_uint8.astype(np.float32) / 255.0
dst = dst_uint8.astype(np.float32) / 255.0
src_rct = imagelib.reinhard_color_transfer(src_uint8, dst_uint8).astype(np.float32) / 255.0
src_lct = np.clip( imagelib.linear_color_transfer (src, dst), 0.0, 1.0 )
src_mkl = imagelib.color_transfer_mkl (src, dst)
src_idt = imagelib.color_transfer_idt (src, dst)
src_sot = imagelib.color_transfer_sot (src, dst)
dst_mean = np.mean(dst, axis=(0,1) )
src_mean = np.mean(src, axis=(0,1) )
src_rct_mean = np.mean(src_rct, axis=(0,1) )
src_lct_mean = np.mean(src_lct, axis=(0,1) )
src_mkl_mean = np.mean(src_mkl, axis=(0,1) )
src_idt_mean = np.mean(src_idt, axis=(0,1) )
src_sot_mean = np.mean(src_sot, axis=(0,1) )
dst_std = np.sqrt ( np.var(dst, axis=(0,1) ) + 1e-5 )
src_std = np.sqrt ( np.var(src, axis=(0,1) ) + 1e-5 )
src_rct_std = np.sqrt ( np.var(src_rct, axis=(0,1) ) + 1e-5 )
src_lct_std = np.sqrt ( np.var(src_lct, axis=(0,1) ) + 1e-5 )
src_mkl_std = np.sqrt ( np.var(src_mkl, axis=(0,1) ) + 1e-5 )
src_idt_std = np.sqrt ( np.var(src_idt, axis=(0,1) ) + 1e-5 )
src_sot_std = np.sqrt ( np.var(src_sot, axis=(0,1) ) + 1e-5 )
def_mean_sum = np.sum( np.square(src_mean-dst_mean) )
rct_mean_sum = np.sum( np.square(src_rct_mean-dst_mean) )
lct_mean_sum = np.sum( np.square(src_lct_mean-dst_mean) )
mkl_mean_sum = np.sum( np.square(src_mkl_mean-dst_mean) )
idt_mean_sum = np.sum( np.square(src_idt_mean-dst_mean) )
sot_mean_sum = np.sum( np.square(src_sot_mean-dst_mean) )
def_std_sum = np.sum( np.square(src_std-dst_std) )
rct_std_sum = np.sum( np.square(src_rct_std-dst_std) )
lct_std_sum = np.sum( np.square(src_lct_std-dst_std) )
mkl_std_sum = np.sum( np.square(src_mkl_std-dst_std) )
idt_std_sum = np.sum( np.square(src_idt_std-dst_std) )
sot_std_sum = np.sum( np.square(src_sot_std-dst_std) )
return idx, [def_mean_sum+def_std_sum,
rct_mean_sum+rct_std_sum,
lct_mean_sum+lct_std_sum,
mkl_mean_sum+mkl_std_sum,
idt_mean_sum+idt_std_sum,
sot_mean_sum+sot_std_sum
]
def __init__(self, src_paths, dst_paths ):
self.src_paths = src_paths
self.src_paths_idxs = [*range(len(self.src_paths))]
self.dst_paths = dst_paths
self.result = [None]*len(self.src_paths)
super().__init__('CTComputerSubprocessor', CTComputerSubprocessor.Cli, 60)
def process_info_generator(self):
for i in range(multiprocessing.cpu_count()):
yield 'CPU%d' % (i), {}, {}
def on_clients_initialized(self):
io.progress_bar ("Computing", len (self.src_paths_idxs))
def on_clients_finalized(self):
io.progress_bar_close()
def get_data(self, host_dict):
if len (self.src_paths_idxs) > 0:
idx = self.src_paths_idxs.pop(0)
src_path = self.src_paths [idx]
dst_path = self.dst_paths [np.random.randint(len(self.dst_paths))]
return idx, src_path, dst_path
return None
#override
def on_data_return (self, host_dict, data):
self.src_paths_idxs.insert(0, data[0])
#override
def on_result (self, host_dict, data, result):
idx, data = result
self.result[idx] = data
io.progress_bar_inc(1)
#override
def get_result(self):
return {0:'none',
1:'rct',
2:'lct',
3:'mkl',
4:'idt',
5:'sot'
}[np.argmin(np.mean(np.array(self.result), 0))]
from samplelib import *
from skimage.transform import rescale
#np.seterr(divide='ignore', invalid='ignore')
def mls_affine_deformation_1pt(p, q, v, alpha=1):
''' Calculate the affine deformation of one point.
This function is used to test the algorithm.
'''
ctrls = p.shape[0]
np.seterr(divide='ignore')
w = 1.0 / np.sum((p - v) ** 2, axis=1) ** alpha
w[w == np.inf] = 2**31-1
pstar = np.sum(p.T * w, axis=1) / np.sum(w)
qstar = np.sum(q.T * w, axis=1) / np.sum(w)
phat = p - pstar
qhat = q - qstar
reshaped_phat1 = phat.reshape(ctrls, 2, 1)
reshaped_phat2 = phat.reshape(ctrls, 1, 2)
reshaped_w = w.reshape(ctrls, 1, 1)
pTwp = np.sum(reshaped_phat1 * reshaped_w * reshaped_phat2, axis=0)
try:
inv_pTwp = np.linalg.inv(pTwp)
except np.linalg.linalg.LinAlgError:
if np.linalg.det(pTwp) < 1e-8:
new_v = v + qstar - pstar
return new_v
else:
raise
mul_left = v - pstar
mul_right = np.sum(reshaped_phat1 * reshaped_w * qhat[:, np.newaxis, :], axis=0)
new_v = np.dot(np.dot(mul_left, inv_pTwp), mul_right) + qstar
return new_v
def mls_affine_deformation(image, p, q, alpha=1.0, density=1.0):
''' Affine deformation
### Params:
* image - ndarray: original image
* p - ndarray: an array with size [n, 2], original control points
* q - ndarray: an array with size [n, 2], final control points
* alpha - float: parameter used by weights
* density - float: density of the grids
### Return:
A deformed image.
'''
height = image.shape[0]
width = image.shape[1]
# Change (x, y) to (row, col)
q = q[:, [1, 0]]
p = p[:, [1, 0]]
# Make grids on the original image
gridX = np.linspace(0, width, num=int(width*density), endpoint=False)
gridY = np.linspace(0, height, num=int(height*density), endpoint=False)
vy, vx = np.meshgrid(gridX, gridY)
grow = vx.shape[0] # grid rows
gcol = vx.shape[1] # grid cols
ctrls = p.shape[0] # control points
# Precompute