Open In App

Tensorflow.js tf.browser.toPixels() Function

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:



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.




import * as tf from "@tensorflow/tfjs"
const tensorA = 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.




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

Article Tags :