Certainly! Below is the JavaScript code that replicates the functionality of your Python script using JavaScript, Mediapipe's JavaScript API, and TensorFlow.js. This code processes a video file, extracts pose landmarks using Mediapipe, and runs a classification using a TensorFlow.js model converted from your TFLite model.
Note: You'll need to convert your TFLite model to TensorFlow.js format using the tensorflowjs_converter tool. Instructions are provided below.
HTML File (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pose Classification</title>
<!-- Mediapipe Pose -->
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.min.js"></script>
<!-- TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.9.0/dist/tf.min.js"></script>
</head>
<body>
<video id="video" width="640" height="480" controls></video>
<canvas id="canvas" width="640" height="480" style="display:none;"></canvas>
<script src="script.js"></script>
</body>
</html>
JavaScript File (script.js):
const videoElement = document.getElementById('video');
const canvasElement = document.getElementById('canvas');
const canvasCtx = canvasElement.getContext('2d');
let model;
async function setupCamera() {
// The user can select the video file
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'video/*';
fileInput.onchange = () => {
const file = fileInput.files[0];
const url = URL.createObjectURL(file);
videoElement.src = url;
videoElement.play();
};
document.body.appendChild(fileInput);
fileInput.click();
return new Promise((resolve) => {
videoElement.onloadedmetadata = () => {
resolve(videoElement);
};
});
}
async function main() {
await setupCamera();
const pose = new Pose({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/pose/${file}`;
}
});
pose.setOptions({
selfieMode: false,
modelComplexity: 1,
enableSegmentation: false,
smoothLandmarks: true,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
});
pose.onResults(onResults);
// Load the converted tf.js model
model = await tf.loadLayersModel('model.json'); // Make sure to host model.json and associated weight files
videoElement.onplay = () => {
function detectionLoop() {
if (videoElement.paused || videoElement.ended) {
return;
}
pose.send({ image: videoElement });
requestAnimationFrame(detectionLoop);
}
detectionLoop();
};
}
async function onResults(results) {
// Draw the results on the canvas (optional)
canvasCtx.save();
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.drawImage(results.image, 0, 0, canvasElement.width, canvasElement.height);
if (results.poseLandmarks) {
drawConnectors(canvasCtx, results.poseLandmarks, POSE_CONNECTIONS,
{ color: '#00FF00', lineWidth: 4 });
drawLandmarks(canvasCtx, results.poseLandmarks,
{ color: '#FF0000', lineWidth: 2 });
}
canvasCtx.restore();
try {
// Extract pose landmarks
const poseLandmarks = results.poseLandmarks;
if (!poseLandmarks) {
return;
}
// Get pose landmarks as an array
let poseRow = [];
for (let landmark of poseLandmarks) {
poseRow.push(landmark.x);
poseRow.push(landmark.y);
poseRow.push(landmark.z);
poseRow.push(landmark.visibility || 0); // Handle undefined visibility
}
// Convert to Float32Array
let inputData = new Float32Array(poseRow);
// Reshape to match model input shape
inputData = tf.tensor(inputData).reshape([1, poseRow.length]);
// Check if the input shape matches the model's expected shape
const inputShape = model.inputs[0].shape;
if (inputData.shape[1] !== inputShape[1]) {
console.error(`Input shape mismatch. Expected ${inputShape[1]} features, got ${inputData.shape[1]}.`);
return;
}
// Run inference
const outputData = model.predict(inputData);
// Get output tensor data
const bodyLanguageProb = outputData.dataSync();
const bodyLanguageClass = bodyLanguageProb.indexOf(Math.max(...bodyLanguageProb));
// Print results to console
console.log(`Class: ${bodyLanguageClass}, Probability: ${bodyLanguageProb}`);
// Dispose tensors
inputData.dispose();
outputData.dispose();
} catch (e) {
console.error(`Error: ${e}`);
}
}
main();
Instructions to Convert Your TFLite Model to TensorFlow.js Format:
To use your TFLite model in TensorFlow.js, you'll need to convert it to the TensorFlow.js Layers format. Follow these steps:
-
Install TensorFlow.js Converter:
pip install tensorflowjs
-
Convert the TFLite Model:
Navigate to the directory containing your model.tflite file and run:
tensorflowjs_converter --input_format=tflite --output_format=keras_saved_model model.tflite converted_model
-
Convert the Keras Model to TensorFlow.js Format:
tensorflowjs_converter --input_format=keras_saved_model --output_format=tfjs_layers_model converted_model model_web
-
Host Your Model Files:
Place the model.json and corresponding .bin weight files in a directory that can be accessed by your JavaScript code (e.g., the same directory as your index.html).
-
Update the Model Path in the Code:
Ensure that the tf.loadLayersModel function points to the correct path of your model.json file:
model = await tf.loadLayersModel('model_web/model.json');
Explanation of the Code:
-
Video Setup:
The code prompts the user to select a video file from their system. It then plays the video and processes each frame.
-
Mediapipe Pose:
Mediapipe's Pose solution is initialized and configured to process the video frames and extract pose landmarks.
-
Model Loading:
The TensorFlow.js model converted from your TFLite model is loaded using tf.loadLayersModel.
-
Processing Each Frame:
For each frame, the code:
- Extracts the pose landmarks.
- Flattens and formats the landmarks to match the model's expected input shape.
- Runs inference using the loaded model.
- Logs the classification result and probability to the console.
-
Drawing on Canvas:
Optionally, the code draws the pose landmarks and connections on a canvas overlaying the video (you can display the canvas by removing style="display:none;" from the canvas element).
Note:
-
Environment Restrictions:
This code is intended to run in a web browser environment due to the use of DOM elements (video and canvas) and Mediapipe's JavaScript API.
-
Node.js Considerations:
If you need to run this code in a Node.js environment, you'll need to use Node.js-compatible libraries for video processing and possibly adapt Mediapipe and TensorFlow.js accordingly.
-
Model Compatibility:
Ensure your model's input shape matches the pose landmark array's size. Adjust the preprocessing steps if necessary to align with how your model was trained.
Let me know if you need further assistance or modifications!