Nekshay commited on
Commit
04f0190
·
verified ·
1 Parent(s): a812b89

Update code.txt

Browse files
Files changed (1) hide show
  1. code.txt +24 -6
code.txt CHANGED
@@ -144,6 +144,7 @@ for i, label in enumerate(label_names):
144
 
145
  import React, { useState, useEffect } from "react";
146
  import * as tflite from "@tensorflow/tfjs-tflite";
 
147
 
148
  function ObjectDetector() {
149
  const [model, setModel] = useState(null);
@@ -174,13 +175,29 @@ function ObjectDetector() {
174
 
175
  const imageElement = document.getElementById("inputImage");
176
 
177
- // Prepare the image
178
- const input = tflite.toTensor(imageElement, [1, 224, 224, 3]); // Resize and convert to tensor, adjust size as per your model
179
- const output = await model.predict(input); // Run inference
180
 
181
- // Interpret the results
182
- // This part depends on the output format of your TFLite model (e.g., bounding boxes, class labels)
183
- setPredictions(output); // Adjust this based on your model's output structure
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  };
185
 
186
  return (
@@ -220,4 +237,5 @@ function ObjectDetector() {
220
  }
221
 
222
  export default ObjectDetector;
 
223
 
 
144
 
145
  import React, { useState, useEffect } from "react";
146
  import * as tflite from "@tensorflow/tfjs-tflite";
147
+ import * as tf from "@tensorflow/tfjs";
148
 
149
  function ObjectDetector() {
150
  const [model, setModel] = useState(null);
 
175
 
176
  const imageElement = document.getElementById("inputImage");
177
 
178
+ // Load the image into a tensor
179
+ const inputTensor = preprocessImage(imageElement, [1, 224, 224, 3]); // Adjust this size based on your model's expected input
 
180
 
181
+ // Run inference
182
+ const output = await model.predict(inputTensor);
183
+
184
+ // Interpret the results (adjust according to your model's output format)
185
+ const outputData = output.arraySync(); // This converts the Tensor to regular JS array, adjust based on your model's output
186
+ setPredictions(outputData); // Adjust this based on your model's output structure
187
+
188
+ // Clean up the tensor to free memory
189
+ tf.dispose([inputTensor]);
190
+ };
191
+
192
+ // Function to preprocess image (resize, normalize, and convert to tensor)
193
+ const preprocessImage = (image, inputShape) => {
194
+ const tensor = tf.browser.fromPixels(image) // Load image into a tensor
195
+ .resizeNearestNeighbor([inputShape[1], inputShape[2]]) // Resize to model's input shape
196
+ .toFloat()
197
+ .div(tf.scalar(255.0)) // Normalize pixel values to [0, 1]
198
+ .expandDims(); // Add batch dimension (1, 224, 224, 3)
199
+
200
+ return tensor;
201
  };
202
 
203
  return (
 
237
  }
238
 
239
  export default ObjectDetector;
240
+
241