Prince-1 commited on
Commit
d157f08
·
verified ·
1 Parent(s): 17e2002

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 25. Face Recognition/.ipynb_checkpoints/25.0 Face Extraction from Video - Build Dataset-checkpoint.ipynb +93 -0
  2. 25. Face Recognition/.ipynb_checkpoints/25.1 Face Recognition - Friends Characters - Train and Test-checkpoint.ipynb +536 -0
  3. 25. Face Recognition/.ipynb_checkpoints/25.2 Face Recogition - Matching Faces-checkpoint.ipynb +0 -0
  4. 25. Face Recognition/.ipynb_checkpoints/25.3 Face Recogition - One Shot Learning-checkpoint.ipynb +406 -0
  5. 25. Face Recognition/.ipynb_checkpoints/Face Recogition - Matching Faces-checkpoint.ipynb +6 -0
  6. 25. Face Recognition/.ipynb_checkpoints/Face Recogition - One Shot Learning-checkpoint.ipynb +0 -0
  7. 25. Face Recognition/Haarcascades/haarcascade_frontalface_default.xml +0 -0
  8. 25. Face Recognition/faces/validation/Chandler/1005_0.jpg +0 -0
  9. 25. Face Recognition/faces/validation/Chandler/1009_0.jpg +0 -0
  10. 25. Face Recognition/faces/validation/Chandler/100_0.jpg +0 -0
  11. 25. Face Recognition/faces/validation/Chandler/1010_0.jpg +0 -0
  12. 25. Face Recognition/faces/validation/Chandler/1011_0.jpg +0 -0
  13. 25. Face Recognition/faces/validation/Chandler/1012_0.jpg +0 -0
  14. 25. Face Recognition/faces/validation/Chandler/1013_0.jpg +0 -0
  15. 25. Face Recognition/faces/validation/Chandler/1018_0.jpg +0 -0
  16. 25. Face Recognition/faces/validation/Chandler/1019_0.jpg +0 -0
  17. 25. Face Recognition/faces/validation/Chandler/101_0.jpg +0 -0
  18. 25. Face Recognition/faces/validation/Chandler/1022_0.jpg +0 -0
  19. 25. Face Recognition/faces/validation/Chandler/1023_0.jpg +0 -0
  20. 25. Face Recognition/faces/validation/Chandler/1024_0.jpg +0 -0
  21. 25. Face Recognition/faces/validation/Chandler/1025_0.jpg +0 -0
  22. 25. Face Recognition/faces/validation/Chandler/1026_0.jpg +0 -0
  23. 25. Face Recognition/faces/validation/Chandler/1027_0.jpg +0 -0
  24. 25. Face Recognition/faces/validation/Chandler/1028_0.jpg +0 -0
  25. 25. Face Recognition/faces/validation/Chandler/1029_0.jpg +0 -0
  26. 25. Face Recognition/faces/validation/Chandler/102_0.jpg +0 -0
  27. 25. Face Recognition/faces/validation/Chandler/1032_0.jpg +0 -0
  28. 25. Face Recognition/faces/validation/Chandler/1034_0.jpg +0 -0
  29. 25. Face Recognition/faces/validation/Chandler/1035_0.jpg +0 -0
  30. 25. Face Recognition/faces/validation/Chandler/1037_0.jpg +0 -0
  31. 25. Face Recognition/faces/validation/Chandler/1038_0.jpg +0 -0
  32. 25. Face Recognition/faces/validation/Chandler/103_0.jpg +0 -0
  33. 25. Face Recognition/faces/validation/Chandler/1040_0.jpg +0 -0
  34. 25. Face Recognition/faces/validation/Chandler/1042_0.jpg +0 -0
  35. 25. Face Recognition/faces/validation/Chandler/1043_0.jpg +0 -0
  36. 25. Face Recognition/faces/validation/Chandler/104_0.jpg +0 -0
  37. 25. Face Recognition/faces/validation/Chandler/1051_0.jpg +0 -0
  38. 25. Face Recognition/faces/validation/Chandler/1060_0.jpg +0 -0
  39. 25. Face Recognition/faces/validation/Chandler/1061_0.jpg +0 -0
  40. 25. Face Recognition/faces/validation/Chandler/1063_0.jpg +0 -0
  41. 25. Face Recognition/faces/validation/Chandler/1064_0.jpg +0 -0
  42. 25. Face Recognition/faces/validation/Chandler/1065_0.jpg +0 -0
  43. 25. Face Recognition/faces/validation/Chandler/1067_0.jpg +0 -0
  44. 25. Face Recognition/faces/validation/Chandler/1071_0.jpg +0 -0
  45. 25. Face Recognition/faces/validation/Chandler/1074_0.jpg +0 -0
  46. 25. Face Recognition/faces/validation/Chandler/1076_0.jpg +0 -0
  47. 25. Face Recognition/faces/validation/Chandler/1077_0.jpg +0 -0
  48. 25. Face Recognition/faces/validation/Chandler/1078_0.jpg +0 -0
  49. 25. Face Recognition/faces/validation/Chandler/107_0.jpg +0 -0
  50. 25. Face Recognition/friends/Chandler.jpg +0 -0
25. Face Recognition/.ipynb_checkpoints/25.0 Face Extraction from Video - Build Dataset-checkpoint.ipynb ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "### Extracting the faces from a video"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": null,
13
+ "metadata": {},
14
+ "outputs": [],
15
+ "source": [
16
+ "from os import listdir\n",
17
+ "from os.path import isfile, join\n",
18
+ "import os\n",
19
+ "import cv2\n",
20
+ "import dlib\n",
21
+ "import numpy as np\n",
22
+ "\n",
23
+ "# Define Image Path Here\n",
24
+ "image_path = \"./images/\"\n",
25
+ "\n",
26
+ "def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,\n",
27
+ " font_scale=0.8, thickness=1):\n",
28
+ " size = cv2.getTextSize(label, font, font_scale, thickness)[0]\n",
29
+ " x, y = point\n",
30
+ " cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)\n",
31
+ " cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness, lineType=cv2.LINE_AA)\n",
32
+ " \n",
33
+ "detector = dlib.get_frontal_face_detector()\n",
34
+ "\n",
35
+ "# Initialize Webcam\n",
36
+ "cap = cv2.VideoCapture('testfriends.mp4')\n",
37
+ "img_size = 64\n",
38
+ "margin = 0.2\n",
39
+ "frame_count = 0\n",
40
+ "\n",
41
+ "while True:\n",
42
+ " ret, frame = cap.read()\n",
43
+ " frame_count += 1\n",
44
+ " print(frame_count) \n",
45
+ " \n",
46
+ " input_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
47
+ " img_h, img_w, _ = np.shape(input_img)\n",
48
+ " detected = detector(frame, 1)\n",
49
+ " faces = []\n",
50
+ " \n",
51
+ " if len(detected) > 0:\n",
52
+ " for i, d in enumerate(detected):\n",
53
+ " x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()\n",
54
+ " xw1 = max(int(x1 - margin * w), 0)\n",
55
+ " yw1 = max(int(y1 - margin * h), 0)\n",
56
+ " xw2 = min(int(x2 + margin * w), img_w - 1)\n",
57
+ " yw2 = min(int(y2 + margin * h), img_h - 1)\n",
58
+ " face = frame[yw1:yw2 + 1, xw1:xw2 + 1, :]\n",
59
+ " file_name = \"./faces/\"+str(frame_count)+\"_\"+str(i)+\".jpg\"\n",
60
+ " cv2.imwrite(file_name, face)\n",
61
+ " cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)\n",
62
+ "\n",
63
+ " cv2.imshow(\"Face Detector\", frame)\n",
64
+ " if cv2.waitKey(1) == 13: #13 is the Enter Key\n",
65
+ " break\n",
66
+ "\n",
67
+ "cap.release()\n",
68
+ "cv2.destroyAllWindows() "
69
+ ]
70
+ }
71
+ ],
72
+ "metadata": {
73
+ "kernelspec": {
74
+ "display_name": "Python 3",
75
+ "language": "python",
76
+ "name": "python3"
77
+ },
78
+ "language_info": {
79
+ "codemirror_mode": {
80
+ "name": "ipython",
81
+ "version": 3
82
+ },
83
+ "file_extension": ".py",
84
+ "mimetype": "text/x-python",
85
+ "name": "python",
86
+ "nbconvert_exporter": "python",
87
+ "pygments_lexer": "ipython3",
88
+ "version": "3.7.4"
89
+ }
90
+ },
91
+ "nbformat": 4,
92
+ "nbformat_minor": 2
93
+ }
25. Face Recognition/.ipynb_checkpoints/25.1 Face Recognition - Friends Characters - Train and Test-checkpoint.ipynb ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Basic Deep Learning Face Recogntion\n",
8
+ "## Building a Friends TV Show Character Identifier"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "metadata": {},
14
+ "source": [
15
+ "## The learning objective of this lesson (25.1) is the create a 'dumb' face classifer using our LittleVGG model. We are simply training it with 100s of pictures of each Friends Character, and testing our model using a Test Video. \n",
16
+ "\n",
17
+ "## You will see how this is an in-effective way to do Face Recognition, why?\n",
18
+ "## Because a traditional N"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {},
24
+ "source": [
25
+ "### Let's train our model\n",
26
+ "I've created a dataset with the faces of 4 Friends characters taken from a handful of different scenes."
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": 33,
32
+ "metadata": {},
33
+ "outputs": [
34
+ {
35
+ "name": "stdout",
36
+ "output_type": "stream",
37
+ "text": [
38
+ "Found 2663 images belonging to 4 classes.\n",
39
+ "Found 955 images belonging to 4 classes.\n"
40
+ ]
41
+ }
42
+ ],
43
+ "source": [
44
+ "from __future__ import print_function\n",
45
+ "import keras\n",
46
+ "from keras.preprocessing.image import ImageDataGenerator\n",
47
+ "from keras.models import Sequential\n",
48
+ "from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization\n",
49
+ "from keras.layers import Conv2D, MaxPooling2D\n",
50
+ "from keras.preprocessing.image import ImageDataGenerator\n",
51
+ "import os\n",
52
+ "\n",
53
+ "num_classes = 4\n",
54
+ "img_rows, img_cols = 48, 48\n",
55
+ "batch_size = 16\n",
56
+ "\n",
57
+ "train_data_dir = './faces/train'\n",
58
+ "validation_data_dir = './faces/validation'\n",
59
+ "\n",
60
+ "# Let's use some data augmentaiton \n",
61
+ "train_datagen = ImageDataGenerator(\n",
62
+ " rescale=1./255,\n",
63
+ " rotation_range=30,\n",
64
+ " shear_range=0.3,\n",
65
+ " zoom_range=0.3,\n",
66
+ " width_shift_range=0.4,\n",
67
+ " height_shift_range=0.4,\n",
68
+ " horizontal_flip=True,\n",
69
+ " fill_mode='nearest')\n",
70
+ " \n",
71
+ "validation_datagen = ImageDataGenerator(rescale=1./255)\n",
72
+ " \n",
73
+ "train_generator = train_datagen.flow_from_directory(\n",
74
+ " train_data_dir,\n",
75
+ " target_size=(img_rows, img_cols),\n",
76
+ " batch_size=batch_size,\n",
77
+ " class_mode='categorical',\n",
78
+ " shuffle=True)\n",
79
+ " \n",
80
+ "validation_generator = validation_datagen.flow_from_directory(\n",
81
+ " validation_data_dir,\n",
82
+ " target_size=(img_rows, img_cols),\n",
83
+ " batch_size=batch_size,\n",
84
+ " class_mode='categorical',\n",
85
+ " shuffle=True)"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": 37,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "#Our Keras imports\n",
95
+ "from keras.models import Sequential\n",
96
+ "from keras.layers.normalization import BatchNormalization\n",
97
+ "from keras.layers.convolutional import Conv2D, MaxPooling2D\n",
98
+ "from keras.layers.advanced_activations import ELU\n",
99
+ "from keras.layers.core import Activation, Flatten, Dropout, Dense"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "markdown",
104
+ "metadata": {},
105
+ "source": [
106
+ "### Creating a simple VGG based model for Face Recognition"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": 35,
112
+ "metadata": {},
113
+ "outputs": [
114
+ {
115
+ "name": "stdout",
116
+ "output_type": "stream",
117
+ "text": [
118
+ "_________________________________________________________________\n",
119
+ "Layer (type) Output Shape Param # \n",
120
+ "=================================================================\n",
121
+ "conv2d_25 (Conv2D) (None, 48, 48, 32) 896 \n",
122
+ "_________________________________________________________________\n",
123
+ "activation_34 (Activation) (None, 48, 48, 32) 0 \n",
124
+ "_________________________________________________________________\n",
125
+ "batch_normalization_31 (Batc (None, 48, 48, 32) 128 \n",
126
+ "_________________________________________________________________\n",
127
+ "conv2d_26 (Conv2D) (None, 48, 48, 32) 9248 \n",
128
+ "_________________________________________________________________\n",
129
+ "activation_35 (Activation) (None, 48, 48, 32) 0 \n",
130
+ "_________________________________________________________________\n",
131
+ "batch_normalization_32 (Batc (None, 48, 48, 32) 128 \n",
132
+ "_________________________________________________________________\n",
133
+ "max_pooling2d_13 (MaxPooling (None, 24, 24, 32) 0 \n",
134
+ "_________________________________________________________________\n",
135
+ "dropout_19 (Dropout) (None, 24, 24, 32) 0 \n",
136
+ "_________________________________________________________________\n",
137
+ "conv2d_27 (Conv2D) (None, 24, 24, 64) 18496 \n",
138
+ "_________________________________________________________________\n",
139
+ "activation_36 (Activation) (None, 24, 24, 64) 0 \n",
140
+ "_________________________________________________________________\n",
141
+ "batch_normalization_33 (Batc (None, 24, 24, 64) 256 \n",
142
+ "_________________________________________________________________\n",
143
+ "conv2d_28 (Conv2D) (None, 24, 24, 64) 36928 \n",
144
+ "_________________________________________________________________\n",
145
+ "activation_37 (Activation) (None, 24, 24, 64) 0 \n",
146
+ "_________________________________________________________________\n",
147
+ "batch_normalization_34 (Batc (None, 24, 24, 64) 256 \n",
148
+ "_________________________________________________________________\n",
149
+ "max_pooling2d_14 (MaxPooling (None, 12, 12, 64) 0 \n",
150
+ "_________________________________________________________________\n",
151
+ "dropout_20 (Dropout) (None, 12, 12, 64) 0 \n",
152
+ "_________________________________________________________________\n",
153
+ "conv2d_29 (Conv2D) (None, 12, 12, 128) 73856 \n",
154
+ "_________________________________________________________________\n",
155
+ "activation_38 (Activation) (None, 12, 12, 128) 0 \n",
156
+ "_________________________________________________________________\n",
157
+ "batch_normalization_35 (Batc (None, 12, 12, 128) 512 \n",
158
+ "_________________________________________________________________\n",
159
+ "conv2d_30 (Conv2D) (None, 12, 12, 128) 147584 \n",
160
+ "_________________________________________________________________\n",
161
+ "activation_39 (Activation) (None, 12, 12, 128) 0 \n",
162
+ "_________________________________________________________________\n",
163
+ "batch_normalization_36 (Batc (None, 12, 12, 128) 512 \n",
164
+ "_________________________________________________________________\n",
165
+ "max_pooling2d_15 (MaxPooling (None, 6, 6, 128) 0 \n",
166
+ "_________________________________________________________________\n",
167
+ "dropout_21 (Dropout) (None, 6, 6, 128) 0 \n",
168
+ "_________________________________________________________________\n",
169
+ "conv2d_31 (Conv2D) (None, 6, 6, 256) 295168 \n",
170
+ "_________________________________________________________________\n",
171
+ "activation_40 (Activation) (None, 6, 6, 256) 0 \n",
172
+ "_________________________________________________________________\n",
173
+ "batch_normalization_37 (Batc (None, 6, 6, 256) 1024 \n",
174
+ "_________________________________________________________________\n",
175
+ "conv2d_32 (Conv2D) (None, 6, 6, 256) 590080 \n",
176
+ "_________________________________________________________________\n",
177
+ "activation_41 (Activation) (None, 6, 6, 256) 0 \n",
178
+ "_________________________________________________________________\n",
179
+ "batch_normalization_38 (Batc (None, 6, 6, 256) 1024 \n",
180
+ "_________________________________________________________________\n",
181
+ "max_pooling2d_16 (MaxPooling (None, 3, 3, 256) 0 \n",
182
+ "_________________________________________________________________\n",
183
+ "dropout_22 (Dropout) (None, 3, 3, 256) 0 \n",
184
+ "_________________________________________________________________\n",
185
+ "flatten_4 (Flatten) (None, 2304) 0 \n",
186
+ "_________________________________________________________________\n",
187
+ "dense_10 (Dense) (None, 64) 147520 \n",
188
+ "_________________________________________________________________\n",
189
+ "activation_42 (Activation) (None, 64) 0 \n",
190
+ "_________________________________________________________________\n",
191
+ "batch_normalization_39 (Batc (None, 64) 256 \n",
192
+ "_________________________________________________________________\n",
193
+ "dropout_23 (Dropout) (None, 64) 0 \n",
194
+ "_________________________________________________________________\n",
195
+ "dense_11 (Dense) (None, 64) 4160 \n",
196
+ "_________________________________________________________________\n",
197
+ "activation_43 (Activation) (None, 64) 0 \n",
198
+ "_________________________________________________________________\n",
199
+ "batch_normalization_40 (Batc (None, 64) 256 \n",
200
+ "_________________________________________________________________\n",
201
+ "dropout_24 (Dropout) (None, 64) 0 \n",
202
+ "_________________________________________________________________\n",
203
+ "dense_12 (Dense) (None, 4) 260 \n",
204
+ "_________________________________________________________________\n",
205
+ "activation_44 (Activation) (None, 4) 0 \n",
206
+ "=================================================================\n",
207
+ "Total params: 1,328,548\n",
208
+ "Trainable params: 1,326,372\n",
209
+ "Non-trainable params: 2,176\n",
210
+ "_________________________________________________________________\n",
211
+ "None\n"
212
+ ]
213
+ }
214
+ ],
215
+ "source": [
216
+ "model = Sequential()\n",
217
+ "\n",
218
+ "model.add(Conv2D(32, (3, 3), padding = 'same', kernel_initializer=\"he_normal\",\n",
219
+ " input_shape = (img_rows, img_cols, 3)))\n",
220
+ "model.add(Activation('elu'))\n",
221
+ "model.add(BatchNormalization())\n",
222
+ "model.add(Conv2D(32, (3, 3), padding = \"same\", kernel_initializer=\"he_normal\", \n",
223
+ " input_shape = (img_rows, img_cols, 3)))\n",
224
+ "model.add(Activation('elu'))\n",
225
+ "model.add(BatchNormalization())\n",
226
+ "model.add(MaxPooling2D(pool_size=(2, 2)))\n",
227
+ "model.add(Dropout(0.2))\n",
228
+ "\n",
229
+ "# Block #2: second CONV => RELU => CONV => RELU => POOL\n",
230
+ "# layer set\n",
231
+ "model.add(Conv2D(64, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
232
+ "model.add(Activation('elu'))\n",
233
+ "model.add(BatchNormalization())\n",
234
+ "model.add(Conv2D(64, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
235
+ "model.add(Activation('elu'))\n",
236
+ "model.add(BatchNormalization())\n",
237
+ "model.add(MaxPooling2D(pool_size=(2, 2)))\n",
238
+ "model.add(Dropout(0.2))\n",
239
+ "\n",
240
+ "# Block #3: third CONV => RELU => CONV => RELU => POOL\n",
241
+ "# layer set\n",
242
+ "model.add(Conv2D(128, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
243
+ "model.add(Activation('elu'))\n",
244
+ "model.add(BatchNormalization())\n",
245
+ "model.add(Conv2D(128, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
246
+ "model.add(Activation('elu'))\n",
247
+ "model.add(BatchNormalization())\n",
248
+ "model.add(MaxPooling2D(pool_size=(2, 2)))\n",
249
+ "model.add(Dropout(0.2))\n",
250
+ "\n",
251
+ "# Block #4: third CONV => RELU => CONV => RELU => POOL\n",
252
+ "# layer set\n",
253
+ "model.add(Conv2D(256, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
254
+ "model.add(Activation('elu'))\n",
255
+ "model.add(BatchNormalization())\n",
256
+ "model.add(Conv2D(256, (3, 3), padding=\"same\", kernel_initializer=\"he_normal\"))\n",
257
+ "model.add(Activation('elu'))\n",
258
+ "model.add(BatchNormalization())\n",
259
+ "model.add(MaxPooling2D(pool_size=(2, 2)))\n",
260
+ "model.add(Dropout(0.2))\n",
261
+ "\n",
262
+ "# Block #5: first set of FC => RELU layers\n",
263
+ "model.add(Flatten())\n",
264
+ "model.add(Dense(64, kernel_initializer=\"he_normal\"))\n",
265
+ "model.add(Activation('elu'))\n",
266
+ "model.add(BatchNormalization())\n",
267
+ "model.add(Dropout(0.5))\n",
268
+ "\n",
269
+ "# Block #6: second set of FC => RELU layers\n",
270
+ "model.add(Dense(64, kernel_initializer=\"he_normal\"))\n",
271
+ "model.add(Activation('elu'))\n",
272
+ "model.add(BatchNormalization())\n",
273
+ "model.add(Dropout(0.5))\n",
274
+ "\n",
275
+ "# Block #7: softmax classifier\n",
276
+ "model.add(Dense(num_classes, kernel_initializer=\"he_normal\"))\n",
277
+ "model.add(Activation(\"softmax\"))\n",
278
+ "\n",
279
+ "print(model.summary())"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "markdown",
284
+ "metadata": {},
285
+ "source": [
286
+ "### Training our Model"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "execution_count": 36,
292
+ "metadata": {},
293
+ "outputs": [
294
+ {
295
+ "name": "stdout",
296
+ "output_type": "stream",
297
+ "text": [
298
+ "Epoch 1/10\n",
299
+ "166/166 [==============================] - 76s 457ms/step - loss: 1.1153 - acc: 0.5700 - val_loss: 1.4428 - val_acc: 0.4841\n",
300
+ "\n",
301
+ "Epoch 00001: val_loss improved from inf to 1.44279, saving model to /home/deeplearningcv/DeepLearningCV/Trained Models/face_recognition_friends_vgg.h5\n",
302
+ "Epoch 2/10\n",
303
+ "166/166 [==============================] - 67s 403ms/step - loss: 0.7034 - acc: 0.7343 - val_loss: 3.7705 - val_acc: 0.2705\n",
304
+ "\n",
305
+ "Epoch 00002: val_loss did not improve from 1.44279\n",
306
+ "Epoch 3/10\n",
307
+ "166/166 [==============================] - 62s 373ms/step - loss: 0.6037 - acc: 0.7690 - val_loss: 0.9403 - val_acc: 0.6912\n",
308
+ "\n",
309
+ "Epoch 00003: val_loss improved from 1.44279 to 0.94025, saving model to /home/deeplearningcv/DeepLearningCV/Trained Models/face_recognition_friends_vgg.h5\n",
310
+ "Epoch 4/10\n",
311
+ "166/166 [==============================] - 62s 373ms/step - loss: 0.5432 - acc: 0.7988 - val_loss: 1.3018 - val_acc: 0.5548\n",
312
+ "\n",
313
+ "Epoch 00004: val_loss did not improve from 0.94025\n",
314
+ "Epoch 5/10\n",
315
+ "166/166 [==============================] - 69s 414ms/step - loss: 0.4715 - acc: 0.8301 - val_loss: 3.8879 - val_acc: 0.1534\n",
316
+ "\n",
317
+ "Epoch 00005: val_loss did not improve from 0.94025\n",
318
+ "Epoch 6/10\n",
319
+ "166/166 [==============================] - 77s 467ms/step - loss: 0.4233 - acc: 0.8524 - val_loss: 0.6878 - val_acc: 0.7093\n",
320
+ "\n",
321
+ "Epoch 00006: val_loss improved from 0.94025 to 0.68784, saving model to /home/deeplearningcv/DeepLearningCV/Trained Models/face_recognition_friends_vgg.h5\n",
322
+ "Epoch 7/10\n",
323
+ "166/166 [==============================] - 71s 429ms/step - loss: 0.4130 - acc: 0.8636 - val_loss: 3.3402 - val_acc: 0.2971\n",
324
+ "\n",
325
+ "Epoch 00007: val_loss did not improve from 0.68784\n",
326
+ "Epoch 8/10\n",
327
+ "166/166 [==============================] - 79s 477ms/step - loss: 0.3821 - acc: 0.8748 - val_loss: 2.6729 - val_acc: 0.6283\n",
328
+ "\n",
329
+ "Epoch 00008: val_loss did not improve from 0.68784\n",
330
+ "Epoch 9/10\n",
331
+ "166/166 [==============================] - 86s 519ms/step - loss: 0.3622 - acc: 0.8709 - val_loss: 1.5067 - val_acc: 0.5197\n",
332
+ "Restoring model weights from the end of the best epoch\n",
333
+ "\n",
334
+ "Epoch 00009: val_loss did not improve from 0.68784\n",
335
+ "\n",
336
+ "Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.0019999999552965165.\n",
337
+ "Epoch 00009: early stopping\n"
338
+ ]
339
+ }
340
+ ],
341
+ "source": [
342
+ "from keras.optimizers import RMSprop, SGD, Adam\n",
343
+ "from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n",
344
+ "\n",
345
+ " \n",
346
+ "checkpoint = ModelCheckpoint(\"/home/deeplearningcv/DeepLearningCV/Trained Models/face_recognition_friends_vgg.h5\",\n",
347
+ " monitor=\"val_loss\",\n",
348
+ " mode=\"min\",\n",
349
+ " save_best_only = True,\n",
350
+ " verbose=1)\n",
351
+ "\n",
352
+ "earlystop = EarlyStopping(monitor = 'val_loss', \n",
353
+ " min_delta = 0, \n",
354
+ " patience = 3,\n",
355
+ " verbose = 1,\n",
356
+ " restore_best_weights = True)\n",
357
+ "\n",
358
+ "reduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.2, patience = 3, verbose = 1, min_delta = 0.0001)\n",
359
+ "\n",
360
+ "# we put our call backs into a callback list\n",
361
+ "callbacks = [earlystop, checkpoint, reduce_lr]\n",
362
+ "\n",
363
+ "# We use a very small learning rate \n",
364
+ "model.compile(loss = 'categorical_crossentropy',\n",
365
+ " optimizer = Adam(lr=0.01),\n",
366
+ " metrics = ['accuracy'])\n",
367
+ "\n",
368
+ "nb_train_samples = 2663\n",
369
+ "nb_validation_samples = 955\n",
370
+ "epochs = 10\n",
371
+ "\n",
372
+ "history = model.fit_generator(\n",
373
+ " train_generator,\n",
374
+ " steps_per_epoch = nb_train_samples // batch_size,\n",
375
+ " epochs = epochs,\n",
376
+ " callbacks = callbacks,\n",
377
+ " validation_data = validation_generator,\n",
378
+ " validation_steps = nb_validation_samples // batch_size)"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "markdown",
383
+ "metadata": {},
384
+ "source": [
385
+ "#### Getting our Class Labels"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "execution_count": 39,
391
+ "metadata": {},
392
+ "outputs": [
393
+ {
394
+ "data": {
395
+ "text/plain": [
396
+ "{0: 'Chandler', 1: 'Joey', 2: 'Pheobe', 3: 'Rachel'}"
397
+ ]
398
+ },
399
+ "execution_count": 39,
400
+ "metadata": {},
401
+ "output_type": "execute_result"
402
+ }
403
+ ],
404
+ "source": [
405
+ "class_labels = validation_generator.class_indices\n",
406
+ "class_labels = {v: k for k, v in class_labels.items()}\n",
407
+ "classes = list(class_labels.values())\n",
408
+ "class_labels"
409
+ ]
410
+ },
411
+ {
412
+ "cell_type": "code",
413
+ "execution_count": null,
414
+ "metadata": {},
415
+ "outputs": [],
416
+ "source": [
417
+ "# Load our model\n",
418
+ "from keras.models import load_model\n",
419
+ "\n",
420
+ "classifier = load_model('/home/deeplearningcv/DeepLearningCV/Trained Models/face_recognition_friends_vgg.h5')"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "markdown",
425
+ "metadata": {},
426
+ "source": [
427
+ "### Testing our model on some real video"
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "code",
432
+ "execution_count": 43,
433
+ "metadata": {},
434
+ "outputs": [],
435
+ "source": [
436
+ "from os import listdir\n",
437
+ "from os.path import isfile, join\n",
438
+ "import os\n",
439
+ "import cv2\n",
440
+ "import numpy as np\n",
441
+ "\n",
442
+ "\n",
443
+ "face_classes = {0: 'Chandler', 1: 'Joey', 2: 'Pheobe', 3: 'Rachel'}\n",
444
+ "\n",
445
+ "def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,\n",
446
+ " font_scale=0.8, thickness=1):\n",
447
+ " size = cv2.getTextSize(label, font, font_scale, thickness)[0]\n",
448
+ " x, y = point\n",
449
+ " cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)\n",
450
+ " cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness, lineType=cv2.LINE_AA)\n",
451
+ " \n",
452
+ "margin = 0.2\n",
453
+ "# load model and weights\n",
454
+ "img_size = 64\n",
455
+ "\n",
456
+ "detector = dlib.get_frontal_face_detector()\n",
457
+ "\n",
458
+ "cap = cv2.VideoCapture('testfriends.mp4')\n",
459
+ "\n",
460
+ "while True:\n",
461
+ " ret, frame = cap.read()\n",
462
+ " frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation = cv2.INTER_LINEAR)\n",
463
+ " preprocessed_faces = [] \n",
464
+ " \n",
465
+ " input_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
466
+ " img_h, img_w, _ = np.shape(input_img)\n",
467
+ " detected = detector(frame, 1)\n",
468
+ " faces = np.empty((len(detected), img_size, img_size, 3))\n",
469
+ " \n",
470
+ " preprocessed_faces_emo = []\n",
471
+ " if len(detected) > 0:\n",
472
+ " for i, d in enumerate(detected):\n",
473
+ " x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()\n",
474
+ " xw1 = max(int(x1 - margin * w), 0)\n",
475
+ " yw1 = max(int(y1 - margin * h), 0)\n",
476
+ " xw2 = min(int(x2 + margin * w), img_w - 1)\n",
477
+ " yw2 = min(int(y2 + margin * h), img_h - 1)\n",
478
+ " cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)\n",
479
+ " # cv2.rectangle(img, (xw1, yw1), (xw2, yw2), (255, 0, 0), 2)\n",
480
+ " #faces[i, :, :, :] = cv2.resize(frame[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))\n",
481
+ " face = frame[yw1:yw2 + 1, xw1:xw2 + 1, :]\n",
482
+ " face = cv2.resize(face, (48, 48), interpolation = cv2.INTER_AREA)\n",
483
+ " face = face.astype(\"float\") / 255.0\n",
484
+ " face = img_to_array(face)\n",
485
+ " face = np.expand_dims(face, axis=0)\n",
486
+ " preprocessed_faces.append(face)\n",
487
+ "\n",
488
+ " # make a prediction for Emotion \n",
489
+ " face_labels = []\n",
490
+ " for i, d in enumerate(detected):\n",
491
+ " preds = classifier.predict(preprocessed_faces[i])[0]\n",
492
+ " face_labels.append(face_classes[preds.argmax()])\n",
493
+ " \n",
494
+ " # draw results\n",
495
+ " for i, d in enumerate(detected):\n",
496
+ " label = \"{}\".format(face_labels[i])\n",
497
+ " draw_label(frame, (d.left(), d.top()), label)\n",
498
+ "\n",
499
+ " cv2.imshow(\"Friend Character Identifier\", frame)\n",
500
+ " if cv2.waitKey(1) == 13: #13 is the Enter Key\n",
501
+ " break\n",
502
+ "\n",
503
+ "cap.release()\n",
504
+ "cv2.destroyAllWindows() "
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "code",
509
+ "execution_count": null,
510
+ "metadata": {},
511
+ "outputs": [],
512
+ "source": []
513
+ }
514
+ ],
515
+ "metadata": {
516
+ "kernelspec": {
517
+ "display_name": "Python 3",
518
+ "language": "python",
519
+ "name": "python3"
520
+ },
521
+ "language_info": {
522
+ "codemirror_mode": {
523
+ "name": "ipython",
524
+ "version": 3
525
+ },
526
+ "file_extension": ".py",
527
+ "mimetype": "text/x-python",
528
+ "name": "python",
529
+ "nbconvert_exporter": "python",
530
+ "pygments_lexer": "ipython3",
531
+ "version": "3.6.6"
532
+ }
533
+ },
534
+ "nbformat": 4,
535
+ "nbformat_minor": 2
536
+ }
25. Face Recognition/.ipynb_checkpoints/25.2 Face Recogition - Matching Faces-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
25. Face Recognition/.ipynb_checkpoints/25.3 Face Recogition - One Shot Learning-checkpoint.ipynb ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## 1. Extract faces from pictures of people \n",
8
+ "### Instrutions:\n",
9
+ "- Place photos of people (one face visible) in the folder called \"./people\"\n",
10
+ "- Replace my photo titled \"Rajeev.jpg\" with a piture of your face for testing on a webcam\n",
11
+ "- Faces are extracted using the haarcascade_frontalface_default detector model\n",
12
+ "- Extracted faces are placed in the folder called \"./group_of_faces\"\n",
13
+ "#### We are extracting the faces needed for our one-shot learning model, it will load 5 extracted faces"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": 1,
19
+ "metadata": {},
20
+ "outputs": [
21
+ {
22
+ "name": "stdout",
23
+ "output_type": "stream",
24
+ "text": [
25
+ "Collected image names\n"
26
+ ]
27
+ }
28
+ ],
29
+ "source": [
30
+ "# The code below extracts faces from images and places them in the folder\n",
31
+ "from os import listdir\n",
32
+ "from os.path import isfile, join\n",
33
+ "import cv2\n",
34
+ "\n",
35
+ "# Loading out HAARCascade Face Detector \n",
36
+ "face_detector = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')\n",
37
+ "\n",
38
+ "# Directory of image of persons we'll be extracting faces frommy\n",
39
+ "mypath = \"./people/\"\n",
40
+ "image_file_names = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n",
41
+ "print(\"Collected image names\")\n",
42
+ "\n",
43
+ "for image_name in image_file_names:\n",
44
+ " person_image = cv2.imread(mypath+image_name)\n",
45
+ " face_info = face_detector.detectMultiScale(person_image, 1.3, 5)\n",
46
+ " for (x,y,w,h) in face_info:\n",
47
+ " face = person_image[y:y+h, x:x+w]\n",
48
+ " roi = cv2.resize(face, (128, 128), interpolation = cv2.INTER_CUBIC)\n",
49
+ " path = \"./group_of_faces/\" + \"face_\" + image_name \n",
50
+ " cv2.imwrite(path, roi)\n",
51
+ " cv2.imshow(\"face\", roi)\n",
52
+ " \n",
53
+ " cv2.waitKey(0)\n",
54
+ "cv2.destroyAllWindows()"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "markdown",
59
+ "metadata": {},
60
+ "source": [
61
+ "## 2. Load our VGGFaceModel \n",
62
+ "- This block of code defines the VGGFace model (which we use later) and loads the model"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": 3,
68
+ "metadata": {},
69
+ "outputs": [
70
+ {
71
+ "name": "stdout",
72
+ "output_type": "stream",
73
+ "text": [
74
+ "Model Loaded\n"
75
+ ]
76
+ }
77
+ ],
78
+ "source": [
79
+ "#author Sefik Ilkin Serengil\n",
80
+ "#you can find the documentation of this code from the following link: https://sefiks.com/2018/08/06/deep-face-recognition-with-keras/\n",
81
+ "\n",
82
+ "import numpy as np\n",
83
+ "import cv2\n",
84
+ "\n",
85
+ "from tensorflow.keras.models import Model, Sequential\n",
86
+ "from tensorflow.keras.layers import Input, Convolution2D, ZeroPadding2D, MaxPooling2D, Flatten, Dense, Dropout, Activation\n",
87
+ "from PIL import Image\n",
88
+ "from tensorflow.keras.preprocessing.image import load_img, save_img, img_to_array\n",
89
+ "from tensorflow.keras.applications.imagenet_utils import preprocess_input\n",
90
+ "from tensorflow.keras.preprocessing import image\n",
91
+ "import matplotlib.pyplot as plt\n",
92
+ "from os import listdir\n",
93
+ "\n",
94
+ "def preprocess_image(image_path):\n",
95
+ " \"\"\"Loads image from path and resizes it\"\"\"\n",
96
+ " img = load_img(image_path, target_size=(224, 224))\n",
97
+ " img = img_to_array(img)\n",
98
+ " img = np.expand_dims(img, axis=0)\n",
99
+ " img = preprocess_input(img)\n",
100
+ " return img\n",
101
+ "\n",
102
+ "model = Sequential()\n",
103
+ "model.add(ZeroPadding2D((1,1),input_shape=(224,224, 3)))\n",
104
+ "model.add(Convolution2D(64, (3, 3), activation='relu'))\n",
105
+ "model.add(ZeroPadding2D((1,1)))\n",
106
+ "model.add(Convolution2D(64, (3, 3), activation='relu'))\n",
107
+ "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
108
+ "\n",
109
+ "model.add(ZeroPadding2D((1,1)))\n",
110
+ "model.add(Convolution2D(128, (3, 3), activation='relu'))\n",
111
+ "model.add(ZeroPadding2D((1,1)))\n",
112
+ "model.add(Convolution2D(128, (3, 3), activation='relu'))\n",
113
+ "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
114
+ "\n",
115
+ "model.add(ZeroPadding2D((1,1)))\n",
116
+ "model.add(Convolution2D(256, (3, 3), activation='relu'))\n",
117
+ "model.add(ZeroPadding2D((1,1)))\n",
118
+ "model.add(Convolution2D(256, (3, 3), activation='relu'))\n",
119
+ "model.add(ZeroPadding2D((1,1)))\n",
120
+ "model.add(Convolution2D(256, (3, 3), activation='relu'))\n",
121
+ "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
122
+ "\n",
123
+ "model.add(ZeroPadding2D((1,1)))\n",
124
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
125
+ "model.add(ZeroPadding2D((1,1)))\n",
126
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
127
+ "model.add(ZeroPadding2D((1,1)))\n",
128
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
129
+ "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
130
+ "\n",
131
+ "model.add(ZeroPadding2D((1,1)))\n",
132
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
133
+ "model.add(ZeroPadding2D((1,1)))\n",
134
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
135
+ "model.add(ZeroPadding2D((1,1)))\n",
136
+ "model.add(Convolution2D(512, (3, 3), activation='relu'))\n",
137
+ "model.add(MaxPooling2D((2,2), strides=(2,2)))\n",
138
+ "\n",
139
+ "model.add(Convolution2D(4096, (7, 7), activation='relu'))\n",
140
+ "model.add(Dropout(0.5))\n",
141
+ "model.add(Convolution2D(4096, (1, 1), activation='relu'))\n",
142
+ "model.add(Dropout(0.5))\n",
143
+ "model.add(Convolution2D(2622, (1, 1)))\n",
144
+ "model.add(Flatten())\n",
145
+ "model.add(Activation('softmax'))\n",
146
+ "\n",
147
+ "#you can download pretrained weights from https://drive.google.com/file/d/1CPSeum3HpopfomUEK1gybeuIVoeJT_Eo/view?usp=sharing\n",
148
+ "from tensorflow.keras.models import model_from_json\n",
149
+ "model.load_weights('vgg_face_weights.h5')\n",
150
+ "\n",
151
+ "vgg_face_descriptor = Model(inputs=model.layers[0].input, outputs=model.layers[-2].output)\n",
152
+ "\n",
153
+ "model = vgg_face_descriptor\n",
154
+ "\n",
155
+ " \n",
156
+ "print(\"Model Loaded\")"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "## 3. Test model using your Webcam\n",
164
+ "This code looks up the faces you extracted in the \"group_of_faces\" folder and uses the similarity (Cosine Similarity) to detect which faces is most similar to the one being extracted with your webcam."
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "execution_count": 4,
170
+ "metadata": {},
171
+ "outputs": [
172
+ {
173
+ "name": "stdout",
174
+ "output_type": "stream",
175
+ "text": [
176
+ "Face representations retrieved successfully\n"
177
+ ]
178
+ }
179
+ ],
180
+ "source": [
181
+ "#points to your extracted faces\n",
182
+ "people_pictures = \"./group_of_faces/\"\n",
183
+ "\n",
184
+ "all_people_faces = dict()\n",
185
+ "\n",
186
+ "for file in listdir(people_pictures):\n",
187
+ " person_face, extension = file.split(\".\")\n",
188
+ " all_people_faces[person_face] = model.predict(preprocess_image('./group_of_faces/%s.jpg' % (person_face)))[0,:]\n",
189
+ "\n",
190
+ "print(\"Face representations retrieved successfully\")\n",
191
+ "\n",
192
+ "def findCosineSimilarity(source_representation, test_representation):\n",
193
+ " a = np.matmul(np.transpose(source_representation), test_representation)\n",
194
+ " b = np.sum(np.multiply(source_representation, source_representation))\n",
195
+ " c = np.sum(np.multiply(test_representation, test_representation))\n",
196
+ " return 1 - (a / (np.sqrt(b) * np.sqrt(c)))\n",
197
+ "\n",
198
+ "#Open Webcam\n",
199
+ "cap = cv2.VideoCapture(0) \n",
200
+ "\n",
201
+ "while(True):\n",
202
+ " ret, img = cap.read()\n",
203
+ " faces = face_detector.detectMultiScale(img, 1.3, 5)\n",
204
+ "\n",
205
+ " for (x,y,w,h) in faces:\n",
206
+ " if w > 100: #Adjust accordingly if your webcam resoluation is higher\n",
207
+ " cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #draw rectangle to main image\n",
208
+ " detected_face = img[int(y):int(y+h), int(x):int(x+w)] #crop detected face\n",
209
+ " detected_face = cv2.resize(detected_face, (224, 224)) #resize to 224x224\n",
210
+ "\n",
211
+ " img_pixels = image.img_to_array(detected_face)\n",
212
+ " img_pixels = np.expand_dims(img_pixels, axis = 0)\n",
213
+ " img_pixels /= 255\n",
214
+ "\n",
215
+ " captured_representation = model.predict(img_pixels)[0,:]\n",
216
+ "\n",
217
+ " found = 0\n",
218
+ " for i in all_people_faces:\n",
219
+ " person_name = i\n",
220
+ " representation = all_people_faces[i]\n",
221
+ "\n",
222
+ " similarity = findCosineSimilarity(representation, captured_representation)\n",
223
+ " if(similarity < 0.30):\n",
224
+ " cv2.putText(img, person_name[5:], (int(x+w+15), int(y-12)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n",
225
+ " found = 1\n",
226
+ " break\n",
227
+ "\n",
228
+ " #connect face and text\n",
229
+ " cv2.line(img,(int((x+x+w)/2),y+15),(x+w,y-20),(255, 0, 0),1)\n",
230
+ " cv2.line(img,(x+w,y-20),(x+w+10,y-20),(255, 0, 0),1)\n",
231
+ "\n",
232
+ " if(found == 0): #if found image is not in our people database\n",
233
+ " cv2.putText(img, 'unknown', (int(x+w+15), int(y-12)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n",
234
+ "\n",
235
+ " cv2.imshow('img',img)\n",
236
+ "\n",
237
+ " if cv2.waitKey(1) == 13: #13 is the Enter Key\n",
238
+ " break\n",
239
+ " \n",
240
+ "cap.release()\n",
241
+ "cv2.destroyAllWindows()"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "markdown",
246
+ "metadata": {},
247
+ "source": [
248
+ "## Test on a video\n",
249
+ "### Since we're using the Friends TV Series characters, let's extract the faces from the images I placed in the \"./friends\" folder"
250
+ ]
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "execution_count": 5,
255
+ "metadata": {},
256
+ "outputs": [
257
+ {
258
+ "name": "stdout",
259
+ "output_type": "stream",
260
+ "text": [
261
+ "Collected image names\n"
262
+ ]
263
+ }
264
+ ],
265
+ "source": [
266
+ "from os import listdir\n",
267
+ "from os.path import isfile, join\n",
268
+ "import cv2\n",
269
+ "\n",
270
+ "# Loading out HAARCascade Face Detector \n",
271
+ "face_detector = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')\n",
272
+ "\n",
273
+ "# Directory of image of persons we'll be extracting faces frommy\n",
274
+ "mypath = \"./friends/\"\n",
275
+ "image_file_names = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n",
276
+ "print(\"Collected image names\")\n",
277
+ "\n",
278
+ "for image_name in image_file_names:\n",
279
+ " person_image = cv2.imread(mypath+image_name)\n",
280
+ " face_info = face_detector.detectMultiScale(person_image, 1.3, 5)\n",
281
+ " for (x,y,w,h) in face_info:\n",
282
+ " face = person_image[y:y+h, x:x+w]\n",
283
+ " roi = cv2.resize(face, (128, 128), interpolation = cv2.INTER_CUBIC)\n",
284
+ " path = \"./friends_faces/\" + \"face_\" + image_name \n",
285
+ " cv2.imwrite(path, roi)\n",
286
+ " cv2.imshow(\"face\", roi)\n",
287
+ " \n",
288
+ " cv2.waitKey(0)\n",
289
+ "cv2.destroyAllWindows()"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "markdown",
294
+ "metadata": {},
295
+ "source": [
296
+ "### Again, we load our faces from the \"friends_faces\" directory and we run our face classifier model our test video"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "execution_count": 10,
302
+ "metadata": {},
303
+ "outputs": [
304
+ {
305
+ "name": "stdout",
306
+ "output_type": "stream",
307
+ "text": [
308
+ "Face representations retrieved successfully\n"
309
+ ]
310
+ }
311
+ ],
312
+ "source": [
313
+ "#points to your extracted faces\n",
314
+ "people_pictures = \"./friends_faces/\"\n",
315
+ "\n",
316
+ "all_people_faces = dict()\n",
317
+ "\n",
318
+ "for file in listdir(people_pictures):\n",
319
+ " person_face, extension = file.split(\".\")\n",
320
+ " all_people_faces[person_face] = model.predict(preprocess_image('./friends_faces/%s.jpg' % (person_face)))[0,:]\n",
321
+ "\n",
322
+ "print(\"Face representations retrieved successfully\")\n",
323
+ "\n",
324
+ "def findCosineSimilarity(source_representation, test_representation):\n",
325
+ " a = np.matmul(np.transpose(source_representation), test_representation)\n",
326
+ " b = np.sum(np.multiply(source_representation, source_representation))\n",
327
+ " c = np.sum(np.multiply(test_representation, test_representation))\n",
328
+ " return 1 - (a / (np.sqrt(b) * np.sqrt(c)))\n",
329
+ "\n",
330
+ "cap = cv2.VideoCapture('testfriends.mp4')\n",
331
+ "\n",
332
+ "while(True):\n",
333
+ " ret, img = cap.read()\n",
334
+ " img = cv2.resize(img, (320, 180)) # Re-size video to as smaller size to improve face detection speed\n",
335
+ " faces = face_detector.detectMultiScale(img, 1.3, 5)\n",
336
+ "\n",
337
+ " for (x,y,w,h) in faces:\n",
338
+ " if w > 13: \n",
339
+ " cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #draw rectangle to main image\n",
340
+ "\n",
341
+ " detected_face = img[int(y):int(y+h), int(x):int(x+w)] #crop detected face\n",
342
+ " detected_face = cv2.resize(detected_face, (224, 224)) #resize to 224x224\n",
343
+ "\n",
344
+ " img_pixels = image.img_to_array(detected_face)\n",
345
+ " img_pixels = np.expand_dims(img_pixels, axis = 0)\n",
346
+ " img_pixels /= 255\n",
347
+ "\n",
348
+ " captured_representation = model.predict(img_pixels)[0,:]\n",
349
+ "\n",
350
+ " found = 0\n",
351
+ " for i in all_people_faces:\n",
352
+ " person_name = i\n",
353
+ " representation = all_people_faces[i]\n",
354
+ "\n",
355
+ " similarity = findCosineSimilarity(representation, captured_representation)\n",
356
+ " if(similarity < 0.30):\n",
357
+ " cv2.putText(img, person_name[5:], (int(x+w+15), int(y-12)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n",
358
+ " found = 1\n",
359
+ " break\n",
360
+ "\n",
361
+ " #connect face and text\n",
362
+ " cv2.line(img,(int((x+x+w)/2),y+15),(x+w,y-20),(255, 0, 0),1)\n",
363
+ " cv2.line(img,(x+w,y-20),(x+w+10,y-20),(255, 0, 0),1)\n",
364
+ "\n",
365
+ " if(found == 0): #if found image is not in our people database\n",
366
+ " cv2.putText(img, 'unknown', (int(x+w+15), int(y-12)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n",
367
+ "\n",
368
+ " cv2.imshow('img',img)\n",
369
+ " if cv2.waitKey(1) == 13: #13 is the Enter Key\n",
370
+ " break\n",
371
+ "\n",
372
+ "#kill open cv things\n",
373
+ "cap.release()\n",
374
+ "cv2.destroyAllWindows()"
375
+ ]
376
+ },
377
+ {
378
+ "cell_type": "code",
379
+ "execution_count": null,
380
+ "metadata": {},
381
+ "outputs": [],
382
+ "source": []
383
+ }
384
+ ],
385
+ "metadata": {
386
+ "kernelspec": {
387
+ "display_name": "Python 3",
388
+ "language": "python",
389
+ "name": "python3"
390
+ },
391
+ "language_info": {
392
+ "codemirror_mode": {
393
+ "name": "ipython",
394
+ "version": 3
395
+ },
396
+ "file_extension": ".py",
397
+ "mimetype": "text/x-python",
398
+ "name": "python",
399
+ "nbconvert_exporter": "python",
400
+ "pygments_lexer": "ipython3",
401
+ "version": "3.7.4"
402
+ }
403
+ },
404
+ "nbformat": 4,
405
+ "nbformat_minor": 2
406
+ }
25. Face Recognition/.ipynb_checkpoints/Face Recogition - Matching Faces-checkpoint.ipynb ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [],
3
+ "metadata": {},
4
+ "nbformat": 4,
5
+ "nbformat_minor": 2
6
+ }
25. Face Recognition/.ipynb_checkpoints/Face Recogition - One Shot Learning-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
25. Face Recognition/Haarcascades/haarcascade_frontalface_default.xml ADDED
The diff for this file is too large to render. See raw diff
 
25. Face Recognition/faces/validation/Chandler/1005_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1009_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/100_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1010_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1011_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1012_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1013_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1018_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1019_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/101_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1022_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1023_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1024_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1025_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1026_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1027_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1028_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1029_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/102_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1032_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1034_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1035_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1037_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1038_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/103_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1040_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1042_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1043_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/104_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1051_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1060_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1061_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1063_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1064_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1065_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1067_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1071_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1074_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1076_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1077_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/1078_0.jpg ADDED
25. Face Recognition/faces/validation/Chandler/107_0.jpg ADDED
25. Face Recognition/friends/Chandler.jpg ADDED