extractFaces.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { __awaiter, __generator } from "tslib";
  2. import { FaceDetection } from '../classes/FaceDetection';
  3. import { env } from '../env';
  4. import { createCanvas } from './createCanvas';
  5. import { getContext2dOrThrow } from './getContext2dOrThrow';
  6. import { imageTensorToCanvas } from './imageTensorToCanvas';
  7. import { toNetInput } from './toNetInput';
  8. /**
  9. * Extracts the image regions containing the detected faces.
  10. *
  11. * @param input The image that face detection has been performed on.
  12. * @param detections The face detection results or face bounding boxes for that image.
  13. * @returns The Canvases of the corresponding image region for each detected face.
  14. */
  15. export function extractFaces(input, detections) {
  16. return __awaiter(this, void 0, void 0, function () {
  17. var Canvas, canvas, netInput, tensorOrCanvas, _a, ctx, boxes;
  18. return __generator(this, function (_b) {
  19. switch (_b.label) {
  20. case 0:
  21. Canvas = env.getEnv().Canvas;
  22. canvas = input;
  23. if (!!(input instanceof Canvas)) return [3 /*break*/, 5];
  24. return [4 /*yield*/, toNetInput(input)];
  25. case 1:
  26. netInput = _b.sent();
  27. if (netInput.batchSize > 1) {
  28. throw new Error('extractFaces - batchSize > 1 not supported');
  29. }
  30. tensorOrCanvas = netInput.getInput(0);
  31. if (!(tensorOrCanvas instanceof Canvas)) return [3 /*break*/, 2];
  32. _a = tensorOrCanvas;
  33. return [3 /*break*/, 4];
  34. case 2: return [4 /*yield*/, imageTensorToCanvas(tensorOrCanvas)];
  35. case 3:
  36. _a = _b.sent();
  37. _b.label = 4;
  38. case 4:
  39. canvas = _a;
  40. _b.label = 5;
  41. case 5:
  42. ctx = getContext2dOrThrow(canvas);
  43. boxes = detections.map(function (det) { return det instanceof FaceDetection
  44. ? det.forSize(canvas.width, canvas.height).box.floor()
  45. : det; })
  46. .map(function (box) { return box.clipAtImageBorders(canvas.width, canvas.height); });
  47. return [2 /*return*/, boxes.map(function (_a) {
  48. var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
  49. var faceImg = createCanvas({ width: width, height: height });
  50. getContext2dOrThrow(faceImg)
  51. .putImageData(ctx.getImageData(x, y, width, height), 0, 0);
  52. return faceImg;
  53. })];
  54. }
  55. });
  56. });
  57. }
  58. //# sourceMappingURL=extractFaces.js.map