Skip to content
Related Articles

Related Articles

Improve Article

Tensorflow.js tf.browser.toPixels() Function

  • Last Updated : 24 May, 2021

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.

The tf.browser.toPixels() function is used to convert a tensor to an image in the browser.

Syntax:

tf.browser.toPixels(img, Canvas);

Parameters:

  • img (tf.Tensor2D|tf.Tensor3D|TypedArray|Array): A rank-2 tensor with shape [height, width], or a rank-3 tensor of shape [height, width, numChannels]. 
  • Canvas [optional] (HTMLCanvasElement): The canvas to draw to.

Return Value: It returns a promise that resolves when the render is complete.



Example 1: In this example, we are creating a tensor and calling the tf.browser.toPixels() function with the tensor.

Javascript




import * as tf from "@tensorflow/tfjs"
const tensonA = tf.randomUniform([400, 400, 3]);
  
tf.browser.toPixels(tensorA).then(() => { 
    console.log("tf.browser.toPixels() called");
});

Output:

tf.browser.toPixels() called

Example 2: In this example, we are creating a tensor and grabbing the canvas reference, and calling the tf.browser.toPixels() function with the tensor and the canvas reference.

Javascript




const tensorA = tf.randomUniform([400, 400, 3]); 
  
const canvasA = document.getElementById("CanvasHTML"); 
  
tf.browser.toPixels(tensorA, canvasA).then(() => { 
  tensorA.dispose();
  console.log(
    "Make sure we cleaned up"
    tf.memory().numTensors
  );
});

Output:

Make sure we cleaned up 2

Reference: https://js.tensorflow.org/api/latest/#browser.toPixels

My Personal Notes arrow_drop_up
Recommended Articles
Page :