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 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.
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Oct, 2021
Like Article
Save Article