forked from Azure-Samples/cognitive-services-quickstart-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk_quickstart.js
More file actions
304 lines (262 loc) · 12 KB
/
sdk_quickstart.js
File metadata and controls
304 lines (262 loc) · 12 KB
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
'use strict';
const msRest = require("@azure/ms-rest-js");
const Face = require("@azure/cognitiveservices-face");
const uuid = require("uuid/v4");
key = "PASTE_YOUR_FACE_SUBSCRIPTION_KEY_HERE";
endpoint = "PASTE_YOUR_FACE_ENDPOINT_HERE";
// <credentials>
const credentials = new msRest.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': key } });
const client = new Face.FaceClient(credentials, endpoint);
// </credentials>
// <globals>
const image_base_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/";
const person_group_id = uuid();
// </globals>
// <helpers>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// </helpers>
// <detect>
async function DetectFaceExtract() {
console.log("========DETECT FACES========");
console.log();
// Create a list of images
const image_file_names = [
"detection1.jpg", // single female with glasses
// "detection2.jpg", // (optional: single man)
// "detection3.jpg", // (optional: single male construction worker)
// "detection4.jpg", // (optional: 3 people at cafe, 1 is blurred)
"detection5.jpg", // family, woman child man
"detection6.jpg" // elderly couple, male female
];
// NOTE await does not work properly in for, forEach, and while loops. Use Array.map and Promise.all instead.
await Promise.all (image_file_names.map (async function (image_file_name) {
let detected_faces = await client.face.detectWithUrl(image_base_url + image_file_name,
{
returnFaceAttributes: ["Accessories","Age","Blur","Emotion","Exposure","FacialHair","Glasses","Hair","HeadPose","Makeup","Noise","Occlusion","Smile","QualityForRecognition"],
// We specify detection model 1 because we are retrieving attributes.
detectionModel: "detection_01",
recognitionModel: "recognition_03"
});
console.log (detected_faces.length + " face(s) detected from image " + image_file_name + ".");
console.log("Face attributes for face(s) in " + image_file_name + ":");
// Parse and print all attributes of each detected face.
detected_faces.forEach (async function (face) {
// Get the bounding box of the face
console.log("Bounding box:\n Left: " + face.faceRectangle.left + "\n Top: " + face.faceRectangle.top + "\n Width: " + face.faceRectangle.width + "\n Height: " + face.faceRectangle.height);
// Get the accessories of the face
let accessories = face.faceAttributes.accessories.join();
if (0 === accessories.length) {
console.log ("No accessories detected.");
}
else {
console.log ("Accessories: " + accessories);
}
// Get face other attributes
console.log("Age: " + face.faceAttributes.age);
console.log("Blur: " + face.faceAttributes.blur.blurLevel);
// Get emotion on the face
let emotions = "";
let emotion_threshold = 0.0;
if (face.faceAttributes.emotion.anger > emotion_threshold) { emotions += "anger, "; }
if (face.faceAttributes.emotion.contempt > emotion_threshold) { emotions += "contempt, "; }
if (face.faceAttributes.emotion.disgust > emotion_threshold) { emotions += "disgust, "; }
if (face.faceAttributes.emotion.fear > emotion_threshold) { emotions += "fear, "; }
if (face.faceAttributes.emotion.happiness > emotion_threshold) { emotions += "happiness, "; }
if (face.faceAttributes.emotion.neutral > emotion_threshold) { emotions += "neutral, "; }
if (face.faceAttributes.emotion.sadness > emotion_threshold) { emotions += "sadness, "; }
if (face.faceAttributes.emotion.surprise > emotion_threshold) { emotions += "surprise, "; }
if (emotions.length > 0) {
console.log ("Emotions: " + emotions.slice (0, -2));
}
else {
console.log ("No emotions detected.");
}
// Get more face attributes
console.log("Exposure: " + face.faceAttributes.exposure.exposureLevel);
if (face.faceAttributes.facialHair.moustache + face.faceAttributes.facialHair.beard + face.faceAttributes.facialHair.sideburns > 0) {
console.log("FacialHair: Yes");
}
else {
console.log("FacialHair: No");
}
console.log("Glasses: " + face.faceAttributes.glasses);
// Get hair color
var color = "";
if (face.faceAttributes.hair.hairColor.length === 0) {
if (face.faceAttributes.hair.invisible) { color = "Invisible"; } else { color = "Bald"; }
}
else {
color = "Unknown";
var highest_confidence = 0.0;
face.faceAttributes.hair.hairColor.forEach (function (hair_color) {
if (hair_color.confidence > highest_confidence) {
highest_confidence = hair_color.confidence;
color = hair_color.color;
}
});
}
console.log("Hair: " + color);
// Get more attributes
console.log("Head pose:");
console.log(" Pitch: " + face.faceAttributes.headPose.pitch);
console.log(" Roll: " + face.faceAttributes.headPose.roll);
console.log(" Yaw: " + face.faceAttributes.headPose.yaw);
console.log("Makeup: " + ((face.faceAttributes.makeup.eyeMakeup || face.faceAttributes.makeup.lipMakeup) ? "Yes" : "No"));
console.log("Noise: " + face.faceAttributes.noise.noiseLevel);
console.log("Occlusion:");
console.log(" Eye occluded: " + (face.faceAttributes.occlusion.eyeOccluded ? "Yes" : "No"));
console.log(" Forehead occluded: " + (face.faceAttributes.occlusion.foreheadOccluded ? "Yes" : "No"));
console.log(" Mouth occluded: " + (face.faceAttributes.occlusion.mouthOccluded ? "Yes" : "No"));
console.log("Smile: " + face.faceAttributes.smile);
console.log("QualityForRecognition: " + face.faceAttributes.qualityForRecognition)
console.log();
});
}));
}
// </detect>
// <recognize>
async function DetectFaceRecognize(url) {
// Detect faces from image URL. Since only recognizing, use the recognition model 4.
// We use detection model 3 because we are only retrieving the qualityForRecognition attribute.
// Result faces with quality for recognition lower than "medium" are filtered out.
let detected_faces = await client.face.detectWithUrl(url,
{
returnFaceId: true,
detectionModel: "detection_03",
recognitionModel: "recognition_04",
returnFaceAttributes: ["QualityForRecognition"]
});
return detected_faces.filter(face => face.faceAttributes.qualityForRecognition == 'high' || face.faceAttributes.qualityForRecognition == 'medium');
}
// </recognize>
async function FindSimilar() {
console.log("========FIND SIMILAR========");
console.log();
// <snippet_loadfaces>
const source_image_file_name = "findsimilar.jpg";
const target_image_file_names = [
"Family1-Dad1.jpg",
"Family1-Daughter1.jpg",
"Family1-Mom1.jpg",
"Family1-Son1.jpg",
"Family2-Lady1.jpg",
"Family2-Man1.jpg",
"Family3-Lady1.jpg",
"Family3-Man1.jpg"
];
let target_face_ids = (await Promise.all (target_image_file_names.map (async function (target_image_file_name) {
// Detect faces from target image url.
var faces = await DetectFaceRecognize(image_base_url + target_image_file_name);
console.log(faces.length + " face(s) detected from image: " + target_image_file_name + ".");
return faces.map (function (face) { return face.faceId });;
}))).flat();
// Detect faces from source image url.
let detected_faces = await DetectFaceRecognize(image_base_url + source_image_file_name);
// </snippet_loadfaces>
// <find_similar>
// Find a similar face(s) in the list of IDs. Comapring only the first in list for testing purposes.
let results = await client.face.findSimilar(detected_faces[0].faceId, { faceIds : target_face_ids });
results.forEach (function (result) {
console.log("Faces from: " + source_image_file_name + " and ID: " + result.faceId + " are similar with confidence: " + result.confidence + ".");
});
console.log();
// </find_similar>
}
// <add_faces>
async function AddFacesToPersonGroup(person_dictionary, person_group_id) {
console.log ("Adding faces to person group...");
// The similar faces will be grouped into a single person group person.
await Promise.all (Object.keys(person_dictionary).map (async function (key) {
const value = person_dictionary[key];
// Wait briefly so we do not exceed rate limits.
await sleep (1000);
let person = await client.personGroupPerson.create(person_group_id, { name : key });
console.log("Create a person group person: " + key + ".");
// Add faces to the person group person.
await Promise.all (value.map (async function (similar_image) {
// Check if the image is of sufficent quality for recognition.
let sufficientQuality = true;
let detected_faces = await client.face.detectWithUrl(image_base_url + similar_image,
{
returnFaceAttributes: ["QualityForRecognition"],
detectionModel: "detection_03",
recognitionModel: "recognition_03"
});
detected_faces.forEach(detected_face => {
if (detected_face.faceAttributes.qualityForRecognition != 'high'){
sufficientQuality = false;
}
});
// Quality is sufficent, add to group.
if (sufficientQuality){
console.log("Add face to the person group person: (" + key + ") from image: " + similar_image + ".");
await client.personGroupPerson.addFaceFromUrl(person_group_id, person.personId, image_base_url + similar_image);
}
}));
}));
console.log ("Done adding faces to person group.");
}
// </add_faces>
// <wait_for_training>
async function WaitForPersonGroupTraining(person_group_id) {
// Wait so we do not exceed rate limits.
console.log ("Waiting 10 seconds...");
await sleep (10000);
let result = await client.personGroup.getTrainingStatus(person_group_id);
console.log("Training status: " + result.status + ".");
if (result.status !== "succeeded") {
await WaitForPersonGroupTraining(person_group_id);
}
}
// </wait_for_training>
/* NOTE This function might not work with the free tier of the Face service
because it might exceed the rate limits. If that happens, try inserting calls
to sleep() between calls to the Face service.
*/
// <identify>
async function IdentifyInPersonGroup() {
console.log("========IDENTIFY FACES========");
console.log();
// Create a dictionary for all your images, grouping similar ones under the same key.
const person_dictionary = {
"Family1-Dad" : ["Family1-Dad1.jpg", "Family1-Dad2.jpg"],
"Family1-Mom" : ["Family1-Mom1.jpg", "Family1-Mom2.jpg"],
"Family1-Son" : ["Family1-Son1.jpg", "Family1-Son2.jpg"],
"Family1-Daughter" : ["Family1-Daughter1.jpg", "Family1-Daughter2.jpg"],
"Family2-Lady" : ["Family2-Lady1.jpg", "Family2-Lady2.jpg"],
"Family2-Man" : ["Family2-Man1.jpg", "Family2-Man2.jpg"]
};
// A group photo that includes some of the persons you seek to identify from your dictionary.
let source_image_file_name = "identification1.jpg";
// Create a person group.
console.log("Creating a person group with ID: " + person_group_id);
await client.personGroup.create(person_group_id, { name : person_group_id, recognitionModel : "recognition_04" });
await AddFacesToPersonGroup(person_dictionary, person_group_id);
// Start to train the person group.
console.log();
console.log("Training person group: " + person_group_id + ".");
await client.personGroup.train(person_group_id);
await WaitForPersonGroupTraining(person_group_id);
console.log();
// Detect faces from source image url and only take those with sufficient quality for recognition.
let face_ids = (await DetectFaceRecognize(image_base_url + source_image_file_name)).map (face => face.faceId);
// Identify the faces in a person group.
let results = await client.face.identify(face_ids, { personGroupId : person_group_id});
await Promise.all (results.map (async function (result) {
let person = await client.personGroupPerson.get(person_group_id, result.candidates[0].personId);
console.log("Person: " + person.name + " is identified for face in: " + source_image_file_name + " with ID: " + result.faceId + ". Confidence: " + result.candidates[0].confidence + ".");
}));
console.log();
}
// </identify>
// <main>
async function main() {
await DetectFaceExtract();
await FindSimilar();
await IdentifyInPersonGroup();
console.log ("Done.");
}
main();
// </main>