MCPcopy Index your code
hub / github.com/tensorflow/tfjs / fromPixels

Function fromPixels

tfjs-backend-webgl/src/kernels/FromPixels.ts:36–89  ·  view source on GitHub ↗
(args: {
  inputs: FromPixelsInputs,
  backend: MathBackendWebGL,
  attrs: FromPixelsAttrs
})

Source from the content-addressed store, hash-verified

34let willReadFrequently = env().getBool('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU');
35
36function fromPixels(args: {
37 inputs: FromPixelsInputs,
38 backend: MathBackendWebGL,
39 attrs: FromPixelsAttrs
40}): TensorInfo {
41 const {inputs, backend, attrs} = args;
42 let {pixels} = inputs;
43 const {numChannels} = attrs;
44
45 const isVideo = typeof (HTMLVideoElement) !== 'undefined' &&
46 pixels instanceof HTMLVideoElement;
47 const isImage = typeof (HTMLImageElement) !== 'undefined' &&
48 pixels instanceof HTMLImageElement;
49 const [width, height] = isVideo ?
50 [
51 (pixels as HTMLVideoElement).videoWidth,
52 (pixels as HTMLVideoElement).videoHeight
53 ] :
54 [pixels.width, pixels.height];
55
56 const texShape: [number, number] = [height, width];
57 const outShape = [height, width, numChannels];
58
59 if (isImage || isVideo) {
60 const newWillReadFrequently =
61 env().getBool('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU');
62 if (fromPixels2DContext == null ||
63 newWillReadFrequently !== willReadFrequently) {
64 willReadFrequently = newWillReadFrequently;
65 fromPixels2DContext =
66 document.createElement('canvas').getContext(
67 '2d', {willReadFrequently});
68 }
69
70 fromPixels2DContext.canvas.width = width;
71 fromPixels2DContext.canvas.height = height;
72 fromPixels2DContext.drawImage(
73 pixels as HTMLVideoElement | HTMLImageElement | ImageBitmap, 0, 0,
74 width, height);
75 pixels = fromPixels2DContext.canvas;
76 }
77
78 const tempPixelHandle = backend.makeTensorInfo(texShape, 'int32');
79 // This is a byte texture with pixels.
80 backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;
81 backend.gpgpu.uploadPixelDataToTexture(
82 backend.getTexture(tempPixelHandle.dataId), pixels as ImageData);
83 const program = env().getBool('WEBGL_PACK') ?
84 new FromPixelsPackedProgram(outShape) :
85 new FromPixelsProgram(outShape);
86 const res = backend.runWebGLProgram(program, [tempPixelHandle], 'int32');
87 backend.disposeData(tempPixelHandle.dataId);
88 return res;
89}

Callers

nothing calls this directly

Calls 9

envFunction · 0.90
getBoolMethod · 0.80
getTextureMethod · 0.80
runWebGLProgramMethod · 0.80
disposeDataMethod · 0.65
getContextMethod · 0.45
makeTensorInfoMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…