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-single.js
More file actions
159 lines (125 loc) · 6.51 KB
/
sdk_quickstart-single.js
File metadata and controls
159 lines (125 loc) · 6.51 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
// <snippet_single>
'use strict';
const msRest = require("@azure/ms-rest-js");
const Face = require("@azure/cognitiveservices-face");
const { v4: uuid } = require('uuid');
const key = process.env.VISION_KEY;
const endpoint = process.env.VISION_ENDPOINT;
const credentials = new msRest.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': key } });
const client = new Face.FaceClient(credentials, endpoint);
const image_base_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/";
const person_group_id = uuid();
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
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,
{
detectionModel: "detection_03",
recognitionModel: "recognition_04",
returnFaceAttributes: ["QualityForRecognition"]
});
return detected_faces.filter(face => face.faceAttributes.qualityForRecognition == 'high' || face.faceAttributes.qualityForRecognition == 'medium');
}
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];
let person = await client.personGroupPerson.create(person_group_id, { name : key });
console.log("Create a persongroup person: " + key + ".");
// Add faces to the person group person.
await Promise.all (value.map (async function (similar_image) {
// Wait briefly so we do not exceed rate limits.
await sleep (1000);
// 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;
}
});
// Wait briefly so we do not exceed rate limits.
await sleep (1000);
// 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);
}
// Wait briefly so we do not exceed rate limits.
await sleep (1000);
}));
}));
console.log ("Done adding faces to person group.");
}
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);
}
}
/* 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.
*/
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, 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) {
try{
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 + ".");
// Verification:
let verifyResult = await client.face.verifyFaceToPerson(result.faceId, person.personId, {personGroupId : person_group_id});
console.log("Verification result between face "+ result.faceId +" and person "+ person.personId+ ": " +verifyResult.isIdentical + " with confidence: "+ verifyResult.confidence);
} catch(error) {
//console.log("no persons identified for face with ID " + result.faceId);
console.log(error.toString());
}
}));
console.log();
}
async function main() {
await IdentifyInPersonGroup();
console.log ("Done.");
}
main();
// </snippet_single>