toNetInput.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { __awaiter, __generator } from "tslib";
  2. import { isTensor3D, isTensor4D } from '../utils';
  3. import { awaitMediaLoaded } from './awaitMediaLoaded';
  4. import { isMediaElement } from './isMediaElement';
  5. import { NetInput } from './NetInput';
  6. import { resolveInput } from './resolveInput';
  7. /**
  8. * Validates the input to make sure, they are valid net inputs and awaits all media elements
  9. * to be finished loading.
  10. *
  11. * @param input The input, which can be a media element or an array of different media elements.
  12. * @returns A NetInput instance, which can be passed into one of the neural networks.
  13. */
  14. export function toNetInput(inputs) {
  15. return __awaiter(this, void 0, void 0, function () {
  16. var inputArgArray, getIdxHint, inputArray;
  17. return __generator(this, function (_a) {
  18. switch (_a.label) {
  19. case 0:
  20. if (inputs instanceof NetInput) {
  21. return [2 /*return*/, inputs];
  22. }
  23. inputArgArray = Array.isArray(inputs)
  24. ? inputs
  25. : [inputs];
  26. if (!inputArgArray.length) {
  27. throw new Error('toNetInput - empty array passed as input');
  28. }
  29. getIdxHint = function (idx) { return Array.isArray(inputs) ? " at input index " + idx + ":" : ''; };
  30. inputArray = inputArgArray.map(resolveInput);
  31. inputArray.forEach(function (input, i) {
  32. if (!isMediaElement(input) && !isTensor3D(input) && !isTensor4D(input)) {
  33. if (typeof inputArgArray[i] === 'string') {
  34. throw new Error("toNetInput -" + getIdxHint(i) + " string passed, but could not resolve HTMLElement for element id " + inputArgArray[i]);
  35. }
  36. throw new Error("toNetInput -" + getIdxHint(i) + " expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id");
  37. }
  38. if (isTensor4D(input)) {
  39. // if tf.Tensor4D is passed in the input array, the batch size has to be 1
  40. var batchSize = input.shape[0];
  41. if (batchSize !== 1) {
  42. throw new Error("toNetInput -" + getIdxHint(i) + " tf.Tensor4D with batchSize " + batchSize + " passed, but not supported in input array");
  43. }
  44. }
  45. });
  46. // wait for all media elements being loaded
  47. return [4 /*yield*/, Promise.all(inputArray.map(function (input) { return isMediaElement(input) && awaitMediaLoaded(input); }))];
  48. case 1:
  49. // wait for all media elements being loaded
  50. _a.sent();
  51. return [2 /*return*/, new NetInput(inputArray, Array.isArray(inputs))];
  52. }
  53. });
  54. });
  55. }
  56. //# sourceMappingURL=toNetInput.js.map