Skip to content

Instantly share code, notes, and snippets.

@hughpearse
Last active December 31, 2022 20:05
Show Gist options
  • Save hughpearse/21e09864f1aece25e47657138c45686b to your computer and use it in GitHub Desktop.
Save hughpearse/21e09864f1aece25e47657138c45686b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Image Transform with TensorFlow.js</title>
<!-- Load TensorFlow.js library -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
</head>
<body>
<h1>Image Transform with TensorFlow.js</h1>
<!-- Load the image to be rotated -->
<img id="input-image" src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png" crossorigin="anonymous" alt="Original image">
<br>
<!-- Button to trigger image transform -->
<button id="transform-button">Transform</button>
<!-- Display the transformed image -->
<h1>Transformed Image</h1>
<canvas id="output-image"></canvas>
<!-- Script to perform the rotation -->
<script>
const transformButton = document.getElementById('transform-button');
const inputImage = document.getElementById('input-image');
const canvas = document.getElementById('output-image');
async function transform(imageData) {
// Convert the image data to a tensor
let tensor = tf.tensor4d(imageData.data, [1, inputImage.width, inputImage.height, 4]);
tensor = tf.cast(tensor, 'float32')
// Rotate the tensor by 90 degrees
const transformedTensor = tf.image.rotateWithOffset(tensor, Math.PI / 4);
// Convert the rotated tensor back to image data
// Wait for the tensor data to be processed
const transformedData = await transformedTensor.data();
return transformedData;
}
// When the button is clicked, update the image
transformButton.addEventListener('click', async () => {
// Get the canvas element
const ctx = canvas.getContext('2d');
// Set the canvas size to the size of the original image
canvas.width = inputImage.width;
canvas.height = inputImage.height;
// Draw the original image on the canvas
ctx.drawImage(inputImage, 0, 0);
// Get the image data from the canvas
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// perform transformation
const result = await transform(imageData);
// Update the image data on the canvas
imageData.data.set(result);
ctx.putImageData(imageData, 0, 0);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment