|
| 1 | +const classes = ['amy', 'bernadette', 'howard', 'leonard', 'penny', 'raj', 'sheldon', 'stuart'] |
| 2 | + |
| 3 | +function getFaceImageUri(className, idx) { |
| 4 | + return `images/${className}/${className}${idx}.png` |
| 5 | +} |
| 6 | + |
| 7 | +function renderFaceImageSelectList(selectListId, onChange, initialValue) { |
| 8 | + const indices = [1, 2, 3, 4, 5] |
| 9 | + function renderChildren(select) { |
| 10 | + classes.forEach(className => { |
| 11 | + const optgroup = document.createElement('optgroup') |
| 12 | + optgroup.label = className |
| 13 | + select.appendChild(optgroup) |
| 14 | + indices.forEach(imageIdx => |
| 15 | + renderOption( |
| 16 | + optgroup, |
| 17 | + `${className} ${imageIdx}`, |
| 18 | + getFaceImageUri(className, imageIdx) |
| 19 | + ) |
| 20 | + ) |
| 21 | + }) |
| 22 | + } |
| 23 | + |
| 24 | + renderSelectList( |
| 25 | + selectListId, |
| 26 | + onChange, |
| 27 | + getFaceImageUri(initialValue.className, initialValue.imageIdx), |
| 28 | + renderChildren |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +// fetch first image of each class and compute their descriptors |
| 33 | +async function initBbtFaceDescriptors(net, numImagesForTraining = 1) { |
| 34 | + const maxAvailableImagesPerClass = 5 |
| 35 | + numImagesForTraining = Math.min(numImagesForTraining, maxAvailableImagesPerClass) |
| 36 | + return Promise.all(classes.map( |
| 37 | + async className => { |
| 38 | + const descriptors = [] |
| 39 | + for (let i = 1; i < (numImagesForTraining + 1); i++) { |
| 40 | + const img = await faceapi.fetchImage(getFaceImageUri(className, i)) |
| 41 | + descriptors.push(await faceapi.computeFaceDescriptor(img)) |
| 42 | + } |
| 43 | + return { |
| 44 | + descriptors, |
| 45 | + className |
| 46 | + } |
| 47 | + } |
| 48 | + )) |
| 49 | +} |
| 50 | + |
| 51 | +function getBestMatch(descriptorsByClass, queryDescriptor) { |
| 52 | + function computeMeanDistance(descriptorsOfClass) { |
| 53 | + return faceapi.round( |
| 54 | + descriptorsOfClass |
| 55 | + .map(d => faceapi.euclideanDistance(d, queryDescriptor)) |
| 56 | + .reduce((d1, d2) => d1 + d2, 0) |
| 57 | + / (descriptorsOfClass.length || 1) |
| 58 | + ) |
| 59 | + } |
| 60 | + return descriptorsByClass |
| 61 | + .map( |
| 62 | + ({ descriptors, className }) => ({ |
| 63 | + distance: computeMeanDistance(descriptors), |
| 64 | + className |
| 65 | + }) |
| 66 | + ) |
| 67 | + .reduce((best, curr) => best.distance < curr.distance ? best : curr) |
| 68 | +} |
| 69 | + |
0 commit comments