MrSinan commited on
Commit
ea5352f
·
1 Parent(s): bd371e6

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +755 -0
app.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """app.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1m1tEVpwK3Jv6qCMlrE_XjWg3rC5XZi_g
8
+ """
9
+
10
+ # example of face detection with mtcnn
11
+ from matplotlib import pyplot
12
+ from PIL import Image
13
+ from numpy import asarray
14
+ from mtcnn.mtcnn import MTCNN
15
+ import cv2
16
+ from mask_the_face import *
17
+ import numpy as np
18
+
19
+ import cv2
20
+ from tensorflow.keras.regularizers import l2
21
+ import pathlib
22
+ import tensorflow
23
+ from tensorflow import keras
24
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense,Dropout,BatchNormalization
25
+ import tensorflow.keras
26
+ import pathlib
27
+ import tensorflow as tf
28
+ from tensorflow import keras
29
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
30
+ import tensorflow.keras.utils as utils
31
+ from tensorflow.keras.optimizers import Adam as adam
32
+ from tensorflow.keras.optimizers import SGD
33
+ from tensorflow.keras.optimizers import RMSprop
34
+ from tensorflow.keras.optimizers import Adagrad
35
+ from tensorflow.keras.callbacks import EarlyStopping ,ModelCheckpoint
36
+ import tensorflow as tf
37
+ from tensorflow.keras import Model
38
+ import matplotlib.pyplot as plt
39
+ import numpy as np
40
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, GlobalAveragePooling2D, Dropout, Input
41
+ # import keras_tuner as kt
42
+ from tensorflow.keras.applications import InceptionResNetV2
43
+ from tensorflow.keras import layers
44
+ from tensorflow.keras.applications.inception_resnet_v2 import preprocess_input
45
+ from matplotlib import pyplot
46
+
47
+ from numpy import asarray
48
+ import copy
49
+ import random
50
+ # from mtcnn.mtcnn import MTCNN
51
+ import glob
52
+ import gradio as gr
53
+
54
+ from __future__ import print_function, division
55
+ from tensorflow.keras.regularizers import l2
56
+ from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply, GaussianNoise
57
+ from tensorflow.keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D
58
+ from tensorflow.keras.layers import MaxPooling2D
59
+ from tensorflow.keras.layers import LeakyReLU
60
+ from tensorflow.keras.layers import UpSampling2D, Conv2D
61
+ from tensorflow.keras.models import Sequential, Model
62
+ from tensorflow.keras.optimizers import Adam
63
+ from tensorflow.keras import losses
64
+ from tensorflow.keras.utils import to_categorical
65
+ import tensorflow.keras.backend as K
66
+ from tensorflow.keras.utils import plot_model
67
+ import matplotlib.pyplot as plt
68
+ import shutil
69
+ import numpy as np
70
+ from tensorflow.keras.applications import EfficientNetB0
71
+ from tensorflow.keras.applications import VGG16
72
+
73
+ def ssim_l1_loss(gt, y_pred, max_val=2.0, l1_weight=1.0):
74
+ """
75
+ Computes SSIM loss with L1 normalization
76
+ @param gt: Ground truth image
77
+ @param y_pred: Predicted image
78
+ @param max_val: Maximal SSIM value
79
+ @param l1_weight: Weight of L1 normalization
80
+ @return: SSIM L1 loss
81
+ """
82
+ ssim_loss = 1 - tf.reduce_mean(tf.image.ssim(gt, y_pred, max_val=max_val))
83
+ l1 = tf.keras.metrics.mean_absolute_error(gt, y_pred)
84
+ return ssim_loss + tf.cast(l1 * l1_weight, tf.float32)
85
+
86
+ class GAN():
87
+ def __init__(self,Xpointers,Ypointers,valX,valY,BigBatchSize,BinaryEnabled=False,BigBatchEnable=False,loading=True,printModel=False):
88
+ self.Xpoint= Xpointers
89
+ self.Ypoint= Ypointers
90
+ self.X=''
91
+ self.Y=''
92
+ self.Binary=''
93
+ self.DataSize=BigBatchSize
94
+ self.genEnable=BigBatchEnable
95
+ self.loading=loading
96
+ self.PrintOut=printModel
97
+ if self.loading:
98
+ self.valX=self.get_all_images(valX)
99
+ self.valY=self.get_all_images(valY)
100
+ self.BestValLoss=1000
101
+ self.BinaryEnabled=BinaryEnabled
102
+ if self.loading:
103
+ if self.BinaryEnabled:
104
+ self.Binary=self.GetBinary(self.valY,self.valX)
105
+ self.ChangeToGreen('val')
106
+ optimizer = Adam(0.0010,)
107
+
108
+ # # Build and compile the discriminator
109
+
110
+ self.discriminator_glo = self.build_discriminator()
111
+ self.discriminator_glo.compile(loss='binary_crossentropy',
112
+ optimizer=optimizer,
113
+ metrics=['accuracy'])
114
+ self.discriminator_loc = self.build_local_discriminator()
115
+ self.discriminator_loc.compile(loss='binary_crossentropy',
116
+ optimizer=optimizer,
117
+ metrics=['accuracy'])
118
+
119
+
120
+ self.generator,self.predictor = self.build_generator()
121
+
122
+
123
+
124
+ GenOut = self.generator.output
125
+
126
+
127
+
128
+ valid = self.discriminator_glo(GenOut[0])
129
+ self.discriminator_glo.trainable = False
130
+
131
+ valid2 = self.discriminator_loc(GenOut)
132
+ self.discriminator_loc.trainable = False
133
+
134
+ self.combined = Model(self.generator.input , [self.generator.output[0], valid,valid2])
135
+ self.combined.compile(loss=[ssim_l1_loss, 'binary_crossentropy','binary_crossentropy'],
136
+ loss_weights=[0.35, 0.50,1],
137
+ optimizer=optimizer)
138
+ if self.PrintOut:
139
+ self.generator.summary()
140
+ self.discriminator_loc.summary()
141
+ self.discriminator_glo.summary()
142
+ self.combined.summary()
143
+
144
+ if self.loading:
145
+ self.getBigBatch()
146
+
147
+ def GetBinary(self,Org,Masked):
148
+ allBinary=[]
149
+ for i,x in enumerate(Masked):
150
+
151
+ diff = cv2.absdiff(Org[i], Masked[i])
152
+ gray=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
153
+ _, diff2 = cv2.threshold(gray, 9, 255, cv2.THRESH_BINARY)
154
+ img_median = cv2.medianBlur(diff2, 3)
155
+ img_median = img_median/255
156
+ allBinary.append(img_median)
157
+ return np.array(allBinary)
158
+
159
+
160
+ def get_all_images(self,classes):
161
+
162
+ allImages=[]
163
+
164
+
165
+ for i,sample in enumerate(classes[:]):
166
+
167
+ org_img = cv2.imread(sample)
168
+ #org_img = org_img.astype('float32')
169
+ org_img = cv2.resize(org_img, (256, 256))
170
+ org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)
171
+ # org_img= org_img/127.5 - 1
172
+ # np.append(allImages, org_img)
173
+ allImages.append(org_img)
174
+
175
+
176
+ return np.array(allImages)
177
+
178
+ def ChangeToGreen(self,data='train'):
179
+ if data=='train':
180
+ for i,x in enumerate(self.X):
181
+ self.X[i][self.Binary[i]!=0]=(1,255,1)
182
+ else:
183
+ for i,x in enumerate(self.valX):
184
+ self.valX[i][self.Binary[i]!=0]=(1,255,1)
185
+
186
+ def getBigBatch(self):
187
+ del self.X
188
+ del self.Y
189
+ del self.Binary
190
+ if self.genEnable:
191
+ idx = np.random.randint(0, self.Xpoint.shape[0], self.DataSize)
192
+ currentX=self.Xpoint[idx]
193
+ currentY=self.Ypoint[idx]
194
+ self.X=self.get_all_images(currentX)
195
+ self.Y=self.get_all_images(currentY)
196
+ else:
197
+ self.X=self.get_all_images(self.Xpoint)
198
+ self.Y=self.get_all_images(self.Ypoint)
199
+ if self.BinaryEnabled:
200
+
201
+ self.Binary=self.GetBinary(self.Y,self.X)
202
+ self.ChangeToGreen('train')
203
+ self.Binary=self.Binary.reshape(self.Binary.shape[0],256,256,1)
204
+
205
+
206
+
207
+ def downsample(self,filters, size, apply_batchnorm=True):
208
+
209
+
210
+ result = tf.keras.Sequential()
211
+ result.add(
212
+ tf.keras.layers.Conv2D(filters, size, strides=2, padding='same',))
213
+ result.add(tf.keras.layers.ReLU())
214
+ result.add(
215
+ tf.keras.layers.Conv2D(filters, size, padding='same',))
216
+ result.add(tf.keras.layers.ReLU())
217
+
218
+ if apply_batchnorm:
219
+ result.add(tf.keras.layers.BatchNormalization())
220
+
221
+ return result
222
+
223
+
224
+
225
+
226
+ def upsample(self,filters, size, apply_dropout=False):
227
+
228
+
229
+ result = tf.keras.Sequential()
230
+ result.add(
231
+ tf.keras.layers.Conv2DTranspose(filters, size, strides=2,
232
+ padding='same'))
233
+ result.add(tf.keras.layers.ReLU())
234
+ result.add(
235
+ tf.keras.layers.Conv2DTranspose(filters, size,
236
+ padding='same'))
237
+
238
+
239
+
240
+
241
+ result.add(tf.keras.layers.ReLU())
242
+ result.add(tf.keras.layers.BatchNormalization())
243
+ if apply_dropout:
244
+ result.add(tf.keras.layers.Dropout(0.2))
245
+ return result
246
+
247
+
248
+
249
+ def build_generator(self):
250
+ inputs = tf.keras.layers.Input(shape=[256, 256, 3])
251
+ binary= tf.keras.layers.Input(shape=[256, 256, 1])
252
+ down_stack = [
253
+ self.downsample(128, 3, apply_batchnorm=False), # (batch_size, 128, 128, 64)
254
+ self.downsample(256, 3), # (batch_size, 64, 64, 128)
255
+ self.downsample(256, 3), # (batch_size, 64, 64, 128)
256
+ self.downsample(256, 3), # (batch_size, 64, 64, 128)
257
+ self.downsample(256, 3), # (batch_size, 32, 32, 256)
258
+ self.downsample(512, 3), # (batch_size, 32, 32, 256)
259
+ self.downsample(512, 3), # (batch_size, 8, 8, 512)
260
+ ]
261
+
262
+ up_stack = [
263
+ self.upsample(512, 3, apply_dropout=True), # (batch_size, 8, 8, 1024)
264
+ self.upsample(512, 3), # (batch_size, 64, 64, 256)
265
+ self.upsample(256, 3,apply_dropout=True), # (batch_size, 64, 64, 256)
266
+ self.upsample(256, 3), # (batch_size, 64, 64, 256)
267
+ self.upsample(256, 3,), # (batch_size, 64, 64, 256)
268
+ self.upsample(256, 3), # (batch_size, 64, 64, 256)
269
+ self.upsample(128, 3,), # (batch_size, 128, 128, 128)
270
+ ]
271
+ down_stack2 = [
272
+ self.downsample(128, 5, apply_batchnorm=False), # (batch_size, 128, 128, 64)
273
+ self.downsample(128, 5), # (batch_size, 64, 64, 128)
274
+ self.downsample(256, 5), # (batch_size, 32, 32, 256)
275
+ self.downsample(256, 5), # (batch_size, 32, 32, 256)
276
+ self.downsample(256, 5), # (batch_size, 32, 32, 256)
277
+ self.downsample(512, 5), # (batch_size, 8, 8, 512)
278
+ ]
279
+
280
+
281
+ up_stack2 = [
282
+ self.upsample(512, 5, apply_dropout=True), # (batch_size, 8, 8, 1024)
283
+ self.upsample(256, 5), # (batch_size, 64, 64, 256)
284
+ self.upsample(256, 5,apply_dropout=True), # (batch_size, 64, 64, 256)
285
+ self.upsample(256, 5), # (batch_size, 64, 64, 256)
286
+ self.upsample(128, 5,), # (batch_size, 64, 64, 256)
287
+ self.upsample(128, 5), # (batch_size, 128, 128, 128)
288
+ ]
289
+
290
+
291
+ initializer = tf.random_normal_initializer(0., 0.02)
292
+ last = tf.keras.layers.Conv2DTranspose(3, 3,
293
+ strides=2,
294
+ padding='same',
295
+ name='GenOut',
296
+ activation='tanh') # (batch_size, 256, 256, 3)
297
+ last2 = tf.keras.layers.Conv2DTranspose(3, 3,
298
+ strides=2,
299
+ padding='same',
300
+ name='GenOut2',
301
+ activation='tanh') # (batch_size, 256, 256, 3)
302
+
303
+ x = inputs
304
+
305
+ # Downsampling through the model
306
+ skips = []
307
+ for down in down_stack:
308
+ x = down(x)
309
+ skips.append(x)
310
+
311
+ skips = reversed(skips[:-1])
312
+
313
+ # Upsampling and establishing the skip connections
314
+ for up, skip in zip(up_stack, skips):
315
+ x = up(x)
316
+ x = tf.keras.layers.Concatenate()([x, skip])
317
+
318
+ x = last(x)
319
+
320
+
321
+ y = inputs
322
+
323
+ # Downsampling through the model
324
+ skips = []
325
+ for down in down_stack2:
326
+ y = down(y)
327
+ skips.append(y)
328
+
329
+ skips = reversed(skips[:-1])
330
+
331
+ # Upsampling and establishing the skip connections
332
+ for up, skip in zip(up_stack2, skips):
333
+ y= up(y)
334
+ y = tf.keras.layers.Concatenate()([y, skip])
335
+
336
+ y = last2(y)
337
+
338
+ z= tf.keras.layers.Average()([x,y])
339
+ model1=tf.keras.Model(inputs=[inputs,binary], outputs=[z,binary])
340
+ model2=tf.keras.Model(inputs=inputs, outputs=z)
341
+ return model1,model2
342
+
343
+
344
+
345
+
346
+
347
+ def build_discriminator(self):
348
+ inputs = Input(shape=[256, 256, 3])
349
+
350
+ facenetmodel = Flatten()
351
+ # facenetmodel.load_weights('/content/drive/MyDrive/facenet_keras_weights.h5')
352
+ # for layer in facenetmodel.layers[:-50]:
353
+ # layer.trainable = False
354
+
355
+ # Augment data.
356
+ augmented = keras.Sequential([layers.Resizing(160, 160),],name="data_augmentation",)(inputs)
357
+ # This is 'bootstrapping' a new top_model onto the pretrained layers.
358
+ top_model = facenetmodel(augmented)
359
+ top_model = Dropout(0.5)(top_model)
360
+ top_model = BatchNormalization()(top_model)
361
+ # top_model = Flatten(name="flatten")(top_model)
362
+
363
+ output_layer = Dense(1, activation='sigmoid')(top_model)
364
+
365
+
366
+
367
+
368
+
369
+ return Model(inputs=inputs, outputs=output_layer,name='Discriminator')
370
+
371
+ def build_local_discriminator(self):
372
+ img = Input(shape=[256, 256, 3])
373
+ binary = Input(shape=[256, 256, 1])
374
+ bitAND=tf.keras.layers.Lambda(lambda x: tf.math.multiply(x[0], x[1]))([img,binary])
375
+ facenetmodel = Flatten()
376
+ # facenetmodel.load_weights('/content/drive/MyDrive/facenet_keras_weights.h5')
377
+ # for layer in facenetmodel.layers[:-50]:
378
+ # layer.trainable = False
379
+
380
+ # Augment data.
381
+ augmented = keras.Sequential([layers.Resizing(160, 160),],name="data_augmentation",)(bitAND)
382
+ # This is 'bootstrapping' a new top_model onto the pretrained layers.
383
+ top_model = facenetmodel(augmented)
384
+ top_model = Dropout(0.5)(top_model)
385
+ top_model = BatchNormalization()(top_model)
386
+ # top_model = Flatten(name="flatten")(top_model)
387
+
388
+ output_layer = Dense(1, activation='sigmoid')(top_model)
389
+
390
+
391
+
392
+
393
+
394
+ return Model(inputs=[img,binary], outputs=output_layer,name='Discriminator_local')
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+ def train(self,epochs,batch_size,imagesSavePath,modelPath, sample_interval=50,BigBatchInterval=1000,modelInterval=50):
403
+
404
+
405
+
406
+ xVal=self.valX/127.5 - 1
407
+ yVal=self.valY/127.5 - 1
408
+ # Adversarial ground truths
409
+ valid = np.ones((batch_size, 1))
410
+ fake = np.zeros((batch_size, 1))
411
+ valid = np.ones((batch_size, 1))
412
+ for epoch in range(epochs):
413
+
414
+
415
+
416
+ # Select a random batch of images
417
+ idx = np.random.randint(0, self.X.shape[0], batch_size)
418
+
419
+ masked_imgs = self.X[idx]
420
+ org_imgs= self.Y[idx]
421
+
422
+ masked_imgs = masked_imgs /127.5 - 1.
423
+ org_imgs= org_imgs /127.5 - 1.
424
+ if self.BinaryEnabled:
425
+ binary= self.Binary[idx]
426
+ org_local= tf.math.multiply(org_imgs, binary)
427
+
428
+ gen_missing = self.generator.predict([masked_imgs,binary])
429
+
430
+ # Train the discriminator
431
+ d_loss_real_glo = self.discriminator_glo.train_on_batch(org_imgs, valid)
432
+ d_loss_fake_glo = self.discriminator_glo.train_on_batch(gen_missing[0], fake)
433
+ d_loss_glo = 0.5 * np.add(d_loss_real_glo, d_loss_fake_glo)
434
+
435
+ d_loss_real_loc = self.discriminator_loc.train_on_batch([org_imgs,binary], valid)
436
+ d_loss_fake_loc = self.discriminator_loc.train_on_batch(gen_missing, fake)
437
+ d_loss_loc = 0.5 * np.add(d_loss_real_loc, d_loss_fake_loc)
438
+
439
+
440
+ # ---------------------
441
+ # Train Generator
442
+ # ---------------------
443
+ # self.combined.layers[-1].trainable = False
444
+ g_loss = self.combined.train_on_batch([masked_imgs,binary], [org_imgs, valid,valid])
445
+
446
+ validx = np.random.randint(0, 500, 3)
447
+ val_pred = self.predictor.predict(xVal[validx])
448
+ val_loss=ssim_l1_loss(yVal[validx].astype('float32'),val_pred)
449
+ val_loss=np.average(val_loss)
450
+ # Plot the progress
451
+ print ("%d [G loss: %f,mse:%f] [val_loss:%f]" % (epoch, g_loss[0], g_loss[1],val_loss))
452
+
453
+
454
+
455
+
456
+
457
+ # Plot the progress
458
+
459
+ if epoch!=0:
460
+
461
+ if epoch % 100 == 0:
462
+
463
+ self.combined.save_weights('/content/drive/MyDrive/combinedModel_loc12.h5')
464
+ # If at save interval => save generator weights
465
+ # if epoch!=0:
466
+ # if epoch % modelInterval == 0:
467
+ # if val_loss<self.BestValLoss:
468
+ # self.generator.save_weights(modelPath+'GeneratorWeights_local5.h5')
469
+ # self.BestValLoss=val_loss
470
+
471
+
472
+ # If at save interval => save generated image samples
473
+ if epoch % sample_interval == 0:
474
+ idx = np.random.randint(0, self.X.shape[0], 6)
475
+ val_idx = np.random.randint(0, 499, 2)
476
+ val_reals= self.valY[val_idx]
477
+ val_imgs = self.valX[val_idx]
478
+ reals= self.Y[idx]
479
+ imgs = self.X[idx]
480
+
481
+ self.sample_images(epoch, imgs,reals,imagesSavePath,val_reals,val_imgs)
482
+
483
+
484
+ #Big Batch Gen
485
+ if self.genEnable:
486
+ if epoch!=0:
487
+ if epoch % BigBatchInterval == 0:
488
+ self.getBigBatch()
489
+
490
+ def sample_images(self, epoch, imgs,reals,savepath,val_reals,val_imgs):
491
+ r, c = 3, 8
492
+
493
+ imgs=imgs/127.5 -1.
494
+ val_imgs=val_imgs/127.5 -1.
495
+ gen_missing = self.predictor.predict(imgs)
496
+ val_missing = self.predictor.predict(val_imgs)
497
+ imgs = 0.5 * imgs + 0.5
498
+ val_imgs = 0.5 * val_imgs + 0.5
499
+ # reals= 0.5* reals +0.5
500
+ gen_missing=0.5*gen_missing+0.5
501
+ val_missing=0.5*val_missing+0.5
502
+
503
+ imgs=np.concatenate((imgs,val_imgs), axis=0)
504
+ gen_missing=np.concatenate((gen_missing,val_missing), axis=0)
505
+ reals=np.concatenate((reals,val_reals), axis=0)
506
+ fig, axs = plt.subplots(r, c,figsize=(50,50))
507
+ for i in range(c):
508
+ axs[0,i].imshow(imgs[i, :,:])
509
+ axs[0,i].axis('off')
510
+ axs[1,i].imshow(reals[i, :,:])
511
+ axs[1,i].axis('off')
512
+
513
+ axs[2,i].imshow(gen_missing[i, :,:])
514
+ axs[2,i].axis('off')
515
+ fig.savefig(savepath+"%d.png" % epoch)
516
+ plt.close()
517
+
518
+ GAN_Model = GAN(Xpointers=None,Ypointers=None,valX=None,valY=None,
519
+ BigBatchSize=50,BigBatchEnable=True,BinaryEnabled=True,loading=False)
520
+
521
+ GAN_Model.predictor.load_weights('DemoPredictor.h5')
522
+
523
+ def extract_face(photo, required_size=(256, 256)):
524
+ # load image from file
525
+ pixels = photo
526
+ print(pixels.shape)
527
+ maxH=(pixels.shape[0])
528
+ maxW=(pixels.shape[1])
529
+ if (pixels.shape[-1])>3 or (pixels.shape[-1])<3:
530
+ image = Image.fromarray(pixels)
531
+ return image
532
+ incr=150
533
+ # create the detector, using default weights
534
+ detector = MTCNN()
535
+ # detect faces in the image
536
+ results = detector.detect_faces(pixels)
537
+ if not results:
538
+ image = Image.fromarray(pixels)
539
+ image = image.resize(required_size)
540
+ return image
541
+ # extract the bounding box from the first face
542
+ x1, y1, width, height = results[0]['box']
543
+ x2, y2 = x1 + width, y1 + height
544
+ if y1-incr<=0:
545
+ y1=0
546
+ else :
547
+ y1=y1-incr
548
+ if x1-incr<=0:
549
+ x1=0
550
+ else :
551
+ x1=x1-incr
552
+
553
+ if y2+incr>=maxH:
554
+ y2=maxH
555
+ else :
556
+ y2=y2+incr
557
+ if x2+incr>=maxW:
558
+ x2=maxW
559
+ else :
560
+ x2=x2+incr
561
+ # extract the face
562
+ face = pixels[y1:int(y2), int(x1):int(x2)]
563
+ # resize pixels to the model size
564
+ image = Image.fromarray(face)
565
+ image = image.resize(required_size)
566
+
567
+ return image
568
+
569
+ def GetBinary_test(Org,Masked):
570
+ allBinary=[]
571
+ for i,x in enumerate(Masked):
572
+
573
+ diff = cv2.absdiff(Org, Masked)
574
+ gray=cv2.cvtColor(diff,cv2.COLOR_RGB2GRAY)
575
+ _, diff2 = cv2.threshold(gray, 9, 255, cv2.THRESH_BINARY)
576
+ img_median = cv2.medianBlur(diff2, 3)
577
+ img_median = img_median/255
578
+ allBinary.append(img_median)
579
+ return np.array(allBinary)
580
+ def ChangeToGreen_test(X,Binary):
581
+ X[Binary[0]!=0]=(1,255,1)
582
+
583
+ def predictImage_masked(GANmodel,groundTruth,masked):
584
+ TestX=masked.copy()
585
+ Testy=groundTruth.copy()
586
+
587
+ Binary=GetBinary_test(Testy,TestX)
588
+ ChangeToGreen_test(TestX,Binary)
589
+
590
+ imgs=TestX/127.5 -1.
591
+ Testy=Testy/255
592
+
593
+ gen_missing = GANmodel.predictor.predict(imgs[None,...])
594
+
595
+ gen_missing=0.5*gen_missing+0.5
596
+ psnr2 = tf.image.psnr(Testy.astype('float32'),gen_missing, max_val=1.0)
597
+ ssim=tf.image.ssim(Testy.astype('float32'), gen_missing, max_val=1)
598
+ Mssim=np.average(ssim)
599
+ Mpsnr=np.average(psnr2)
600
+ I = gen_missing*255 # or any coefficient
601
+ I = I.astype(np.uint8)
602
+ I = cv2.normalize(I, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
603
+ return (I,Mpsnr,Mssim)
604
+
605
+ def grid_display(list_of_images, list_of_titles=[], no_of_columns=2, figsize=(10,10)):
606
+
607
+ fig = plt.figure(figsize=figsize)
608
+ column = 0
609
+ for i in range(len(list_of_images)):
610
+ column += 1
611
+ # check for end of column and create a new figure
612
+ if column == no_of_columns+1:
613
+ fig = plt.figure(figsize=figsize)
614
+ column = 1
615
+ fig.add_subplot(1, no_of_columns, column)
616
+ plt.imshow(list_of_images[i])
617
+ plt.axis('off')
618
+ if len(list_of_titles) >= len(list_of_images):
619
+ plt.title(list_of_titles[i])
620
+
621
+ # paths = r"C:\Users\MrSin\Downloads\images\*.jpg"
622
+ # import glob
623
+
624
+ # for filepath in glob.iglob(paths):
625
+ # print(filepath)
626
+ # org_img = cv2.imread(filepath)
627
+
628
+ def ExecutePipline(img):
629
+ im = Image.fromarray(img.astype('uint8'), 'RGB')
630
+ org_img=np.array(im)
631
+ # plt.imshow(org_img)
632
+ errorPNG=cv2.imread('error.jpg',)
633
+ errorPNG=errorPNG[...,::-1]
634
+ img2=extract_face(org_img)
635
+
636
+
637
+ cropped = np.array(img2)
638
+
639
+ open_cv_image = cropped[:, :, ::-1].copy()
640
+ masked1=maskThisImages(open_cv_image)
641
+ if len(masked1)==0:
642
+ return np.zeros((256,256,3)),errorPNG,np.zeros((256,256,3))
643
+ masked2=cv2.cvtColor(masked1,cv2.COLOR_BGR2RGB)
644
+ # output1 = masked2*255 # or any coefficient
645
+ # output1 = output1.astype(np.uint8)
646
+ # output1 = cv2.normalize(output1, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
647
+ # plt.imshow(output1)
648
+ # output1= Image.fromarray(output1)
649
+
650
+ results,psnr,ssim=predictImage_masked(GAN_Model,cropped,masked2)
651
+
652
+ return cropped,masked2,results[0] #,
653
+
654
+ # paths = r"C:\Users\MrSin\Downloads\images\*.jpg"
655
+ # import glob
656
+
657
+ # for filepath in glob.iglob(paths):
658
+ # print(filepath)
659
+ # org_img = cv2.imread(filepath)
660
+ # org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)
661
+
662
+ # img=extract_face(org_img)
663
+
664
+ # cropped = np.array(img)
665
+ # #output 1^
666
+ # open_cv_image = cropped[:, :, ::-1].copy()
667
+ # masked=maskThisImages(open_cv_image)
668
+ # cv2.imwrite('mytestmasked.jpg',masked)
669
+ # masked=cv2.cvtColor(masked,cv2.COLOR_BGR2RGB)
670
+ # #output 2^
671
+ # print(masked.shape)
672
+ # results,psnr,ssim=predictImage_masked_model2(GAN_Model,cropped,masked)
673
+ # displayResult = np.array(results[0])
674
+ # #output 2 results[0]^
675
+ # titles = ["groundtruth",
676
+ # "Masked",
677
+ # "Generated", ]
678
+ # images = [cropped,masked,results[0]]
679
+ # grid_display(images, titles, 3, (15,15))
680
+
681
+ # titles = ["groundtruth",
682
+ # "Masked",
683
+ # "Generated", ]
684
+ # org_img = cv2.imread('mytestmasked.jpg')
685
+ # org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)
686
+ # results=predictImageOnly(GAN_Model,org_img)
687
+ # images = [cropped,masked,results[0]]
688
+ # grid_display(images, titles, 3, (15,15))
689
+
690
+
691
+
692
+ # imagein = gr.Image()
693
+ # maskedOut = gr.Image(type='numpy',label='Masked (Model-input)')
694
+ # crop = gr.Image(type='numpy',label='cropped')
695
+ # genOut= gr.Image(type='numpy',label='Unmasked Output')
696
+
697
+ # gr.Interface(
698
+ # ExecutePipline,
699
+ # inputs=imagein,
700
+ # outputs=[crop,maskedOut,genOut],
701
+ # title="Face Un-Masking",
702
+ # description="Compare 2 state-of-the-art machine learning models",).launch(share=True)
703
+
704
+
705
+
706
+ with gr.Blocks() as demo:
707
+ gr.HTML(
708
+ """
709
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
710
+ <div
711
+ style="
712
+ display: inline-flex;
713
+ align-items: center;
714
+ gap: 0.8rem;
715
+ font-size: 1.75rem;
716
+ "
717
+ >
718
+
719
+ <h1 style="font-weight: 900; margin-bottom: 7px;">
720
+ Face Un-Masking
721
+ </h1>
722
+ </div>
723
+ <p style="margin-bottom: 10px; font-size: 94%">
724
+ Stable Diffusion is a state of the art text-to-image model that generates
725
+ images from text.<br>For faster generation and forthcoming API
726
+ access you can try
727
+
728
+ </p>
729
+ </div>
730
+ """
731
+ )
732
+ with gr.Row():
733
+ with gr.Column():
734
+ imagein = gr.Image(label='Input',interactive=True)
735
+
736
+ with gr.Column():
737
+ gr.Examples(['1.jpg','2.jpg','3.jpg'],inputs=imagein)
738
+ with gr.Row():
739
+
740
+ image_button = gr.Button("Submit")
741
+
742
+
743
+
744
+
745
+ with gr.Row():
746
+ with gr.Column():
747
+ crop = gr.Image(type='numpy',label='Groundtruth(cropped)',)
748
+ with gr.Column():
749
+ maskedOut = gr.Image(type='numpy',label='Masked (Model-input)')
750
+ with gr.Column():
751
+ genOut= gr.Image(type='numpy',label='Unmasked Output')
752
+
753
+ gr.Markdown("<p style='text-align: center'>Made with 🖤 by Mohammed & Aseel </p>")
754
+ image_button.click(fn=ExecutePipline,inputs=imagein,outputs=[crop,maskedOut,genOut])
755
+ demo.launch()