|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Created on Fri Sep 24 09:45:38 2021 |
| 4 | +
|
| 5 | +@author: sumitgoyal |
| 6 | +""" |
| 7 | +import face_recognition |
| 8 | +import os |
| 9 | +import cv2 |
| 10 | +import random |
| 11 | +import scipy.io |
| 12 | +import numpy as np |
| 13 | +import matplotlib.pyplot as plt |
| 14 | +from numpy import pi, exp, sqrt |
| 15 | +from keras.applications.resnet50 import ResNet50 |
| 16 | +from keras.applications.resnet50 import preprocess_input |
| 17 | +from keras.applications.vgg16 import VGG16 |
| 18 | +from keras.applications.vgg16 import preprocess_input |
| 19 | +from keras.models import Model |
| 20 | +from keras.callbacks import ModelCheckpoint |
| 21 | +from keras.backend.tensorflow_backend import set_session |
| 22 | +import tensorflow as tf |
| 23 | +from keras import callbacks |
| 24 | +config = tf.ConfigProto() |
| 25 | +config.gpu_options.allow_growth = True |
| 26 | +#config.gpu_options.per_process_gpu_memory_fraction = 0.3 |
| 27 | +set_session(tf.Session(config=config)) |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | +from keras.layers import MaxPool2D,BatchNormalization,Conv2D,Activation,UpSampling2D,Concatenate |
| 32 | +s, k = 500, 500 |
| 33 | +probs = [exp(-z*z/(2*s*s))/sqrt(2*pi*s*s) for z in range(-k,k+1)] |
| 34 | +kernel = np.outer(probs, probs) |
| 35 | +kernel = kernel-np.min(kernel) |
| 36 | +maxc = np.max(kernel) |
| 37 | +kernel = kernel/maxc |
| 38 | +kernel[kernel<.50]=0 |
| 39 | + |
| 40 | +base_dir = 'faces/' |
| 41 | +dims = (224,344) |
| 42 | +validation_split = .10 |
| 43 | +thres = .5 |
| 44 | +if os.path.exists(base_dir)==False: |
| 45 | + print("Face Dataset is not available in current directory") |
| 46 | + raise SystemExit |
| 47 | +images_path = [] |
| 48 | +for dirpath, dname, filename in os.walk(base_dir): |
| 49 | + for fname in filename: |
| 50 | + if fname.endswith(".jpg"): |
| 51 | + images_path.append(os.path.join(dirpath, fname)) |
| 52 | +mat = scipy.io.loadmat(os.path.join(base_dir, 'ImageData.mat')) |
| 53 | + |
| 54 | +data = [] |
| 55 | + |
| 56 | +for i,path in enumerate(images_path): |
| 57 | + img = cv2.imread(path) |
| 58 | + mask = np.zeros((img.shape[0],img.shape[1]),dtype='float32') |
| 59 | + label = mat['SubDir_Data'][:,i] |
| 60 | + xmin = int(np.min([label[0],label[2],label[4],label[6]])) |
| 61 | + xmax = int(np.max([label[0],label[2],label[4],label[6]])) |
| 62 | + ymin = int(np.min([label[1],label[3],label[5],label[7]])) |
| 63 | + ymax = int(np.max([label[1],label[3],label[5],label[7]])) |
| 64 | + mask[ymin:ymax,xmin:xmax] = cv2.resize(kernel,(xmax-xmin,ymax-ymin)) |
| 65 | + img = cv2.resize(img,dims) |
| 66 | + mask = cv2.resize(mask,dims) |
| 67 | + |
| 68 | + data.append([img,mask]) |
| 69 | + |
| 70 | + |
| 71 | +random.seed(0) |
| 72 | +random.shuffle(data) |
| 73 | + |
| 74 | +nTotal = len(data) |
| 75 | +nValidation = int(validation_split*nTotal) |
| 76 | +nTraining = nTotal-nValidation |
| 77 | +train_X = [] |
| 78 | +train_Y = [] |
| 79 | +for dat in data[:nTraining]: |
| 80 | + train_X.append(dat[0]) |
| 81 | + train_Y.append(dat[1]) |
| 82 | +Val_X = [] |
| 83 | +Val_Y = [] |
| 84 | +for dat in data[nTraining:]: |
| 85 | + Val_X.append(dat[0]) |
| 86 | + Val_Y.append(dat[1]) |
| 87 | + |
| 88 | +train_X1 = preprocess_input(np.array(train_X).astype('float32')) |
| 89 | +Val_X1 = preprocess_input(np.array(Val_X).astype('float32')) |
| 90 | + |
| 91 | +train_Y1 = np.expand_dims(np.array(train_Y),axis=-1) |
| 92 | +Val_Y1 = np.expand_dims(np.array(Val_Y),axis=-1) |
| 93 | + |
| 94 | +def getModelBaseResnet(): |
| 95 | + |
| 96 | + base_model = ResNet50(include_top=False) |
| 97 | + |
| 98 | + x = UpSampling2D()(base_model.layers[44].output) |
| 99 | + x = Concatenate()([x,base_model.layers[38].output]) |
| 100 | + |
| 101 | + x = Conv2D(128,(1,1),padding='same')(x) |
| 102 | + x = BatchNormalization()(x) |
| 103 | + x = Activation('relu')(x) |
| 104 | + |
| 105 | + x = Conv2D(64,(3,3),padding='same')(x) |
| 106 | + x = BatchNormalization()(x) |
| 107 | + x = Activation('relu')(x) |
| 108 | + |
| 109 | + x = UpSampling2D()(x) |
| 110 | + x = Concatenate()([x,base_model.layers[4].output]) |
| 111 | + |
| 112 | + x = Conv2D(64,(1,1),padding='same')(x) |
| 113 | + x = BatchNormalization()(x) |
| 114 | + x = Activation('relu')(x) |
| 115 | + |
| 116 | + x = Conv2D(32,(3,3),padding='same')(x) |
| 117 | + x = BatchNormalization()(x) |
| 118 | + x = Activation('relu')(x) |
| 119 | + |
| 120 | + x = UpSampling2D()(x) |
| 121 | + |
| 122 | + x = Conv2D(16,(3,3),padding='same')(x) |
| 123 | + x = BatchNormalization()(x) |
| 124 | + x = Activation('relu')(x) |
| 125 | + |
| 126 | + x = Conv2D(1,(3,3),padding='same',activation='sigmoid')(x) |
| 127 | + |
| 128 | + |
| 129 | + model = Model(base_model.layers[0].output,x) |
| 130 | + for i in range(45): |
| 131 | + model.layers[i].trainable = True |
| 132 | + model.summary() |
| 133 | + return model |
| 134 | +def getModelBaseVgg(): |
| 135 | + |
| 136 | + base_model = VGG16(include_top=False) |
| 137 | + |
| 138 | + x = UpSampling2D()(base_model.layers[11].output) |
| 139 | + x = Concatenate()([x,base_model.layers[6].output]) |
| 140 | + |
| 141 | + x = Conv2D(128,(1,1),padding='same')(x) |
| 142 | + x = BatchNormalization()(x) |
| 143 | + x = Activation('relu')(x) |
| 144 | + |
| 145 | + x = Conv2D(64,(3,3),padding='same')(x) |
| 146 | + x = BatchNormalization()(x) |
| 147 | + x = Activation('relu')(x) |
| 148 | + |
| 149 | + x = UpSampling2D()(x) |
| 150 | + x = Concatenate()([x,base_model.layers[3].output]) |
| 151 | + |
| 152 | + x = Conv2D(64,(1,1),padding='same')(x) |
| 153 | + x = BatchNormalization()(x) |
| 154 | + x = Activation('relu')(x) |
| 155 | + |
| 156 | + x = Conv2D(32,(3,3),padding='same')(x) |
| 157 | + x = BatchNormalization()(x) |
| 158 | + x = Activation('relu')(x) |
| 159 | + |
| 160 | + x = UpSampling2D()(x) |
| 161 | + |
| 162 | + x = Conv2D(16,(3,3),padding='same')(x) |
| 163 | + x = BatchNormalization()(x) |
| 164 | + x = Activation('relu')(x) |
| 165 | + |
| 166 | + x = Conv2D(1,(3,3),padding='same',activation='sigmoid')(x) |
| 167 | + |
| 168 | + |
| 169 | + model = Model(base_model.layers[0].output,x) |
| 170 | + for i in range(12): |
| 171 | + model.layers[i].trainable = True |
| 172 | + model.summary() |
| 173 | + return model |
| 174 | +model = getModelBaseResnet() |
| 175 | +#model = getModelBaseVgg() |
| 176 | + |
| 177 | + |
| 178 | +model.load_weights("FaceDetection_resnet_100.h5") |
| 179 | + |
| 180 | + |
| 181 | +score_train = model.predict(train_X1) |
| 182 | +score_train[score_train<thres] = 0 |
| 183 | +score_train[score_train>=thres] = 1 |
| 184 | + |
| 185 | + |
| 186 | +sift = cv2.SIFT() |
| 187 | +bf = cv2.BFMatcher() |
| 188 | + |
| 189 | +key_features = [] |
| 190 | + |
| 191 | +for i in range(nTraining): |
| 192 | + nLabels, labels, stats, centroids = cv2.connectedComponentsWithStats(score_train[i].astype(np.uint8), connectivity=4) |
| 193 | + for k in range(1,nLabels): |
| 194 | + size = stats[k, cv2.CC_STAT_AREA] |
| 195 | + if size>100: |
| 196 | + x, y = stats[k, cv2.CC_STAT_LEFT], stats[k, cv2.CC_STAT_TOP] |
| 197 | + w, h = stats[k, cv2.CC_STAT_WIDTH], stats[k, cv2.CC_STAT_HEIGHT] |
| 198 | + img = cv2.cvtColor(train_X[i][y:y+h,x:x+w],cv2.COLOR_BGR2GRAY) |
| 199 | + |
| 200 | + kp1, des1 = sift.detectAndCompute(img,None) |
| 201 | + if des1 is None: |
| 202 | + print(i) |
| 203 | + bConsider = False |
| 204 | + avg = [] |
| 205 | + maxx = [] |
| 206 | + for des in key_features: |
| 207 | + scores = [] |
| 208 | + for d in des: |
| 209 | + des2,kp2,img2 = d |
| 210 | + matches = bf.knnMatch(des1,des2, k=2) |
| 211 | + good = [] |
| 212 | + for m,n in matches: |
| 213 | + if m.distance < 0.8*n.distance: |
| 214 | + good.append([m]) |
| 215 | + if len(matches)==0: |
| 216 | + scores.append(0.0) |
| 217 | + else: |
| 218 | + scores.append(len(good)/len(matches)) |
| 219 | + |
| 220 | + |
| 221 | + avg_score = np.average(scores) |
| 222 | + max_score = np.max(scores) |
| 223 | + |
| 224 | + |
| 225 | + avg.append(avg_score) |
| 226 | + maxx.append(max_score) |
| 227 | + if len(avg)>0: |
| 228 | + armax_avg = np.argmax(maxx) |
| 229 | + if maxx[armax_avg]>=.20: |
| 230 | + bConsider = True |
| 231 | + key_features[armax_avg].append((des1,kp1,img)) |
| 232 | + if bConsider == False: |
| 233 | + key_features.append([(des1,kp1,img)]) |
| 234 | + print(len(key_features),i) |
| 235 | + |
| 236 | +for cat in range(len(key_features)): |
| 237 | + print(cat) |
| 238 | + rows = (len(key_features[cat])/3)+1 |
| 239 | + fig = plt.figure(figsize=(rows, 3)) |
| 240 | + |
| 241 | + for i in range(len(key_features[cat])): |
| 242 | + fig.add_subplot(rows, 3, i+1) |
| 243 | + plt.imshow(key_features[cat][i][2]) |
| 244 | +# ============================================================================= |
| 245 | +# plt.imshow(key_features[cat][i][2]) |
| 246 | +# plt.show() |
| 247 | +# ============================================================================= |
| 248 | + |
| 249 | + |
| 250 | + |
0 commit comments