Update onnx.js
Browse files
onnx.js
CHANGED
@@ -38,33 +38,40 @@ function ObjectDetection() {
|
|
38 |
};
|
39 |
|
40 |
const preprocessImage = async (imageSrc) => {
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
|
45 |
-
|
46 |
-
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
|
54 |
-
|
55 |
|
56 |
-
|
57 |
-
const inputTensor = new Float32Array(imageData.data.length / 4 * 3);
|
58 |
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
for (let i = 0, j = 0; i < imageData.data.length; i += 4) {
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
}
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
|
69 |
const postprocessOutput = (output) => {
|
70 |
const boxes = output['boxes'].data; // Replace 'boxes' with your model's output name
|
|
|
38 |
};
|
39 |
|
40 |
const preprocessImage = async (imageSrc) => {
|
41 |
+
const img = new Image();
|
42 |
+
img.src = imageSrc;
|
43 |
+
await new Promise((resolve) => (img.onload = resolve));
|
44 |
|
45 |
+
const canvas = document.createElement('canvas');
|
46 |
+
const context = canvas.getContext('2d');
|
47 |
|
48 |
+
// Resize to model input size
|
49 |
+
const modelInputWidth = 300; // Replace with your model's input width
|
50 |
+
const modelInputHeight = 300; // Replace with your model's input height
|
51 |
+
canvas.width = modelInputWidth;
|
52 |
+
canvas.height = modelInputHeight;
|
53 |
|
54 |
+
context.drawImage(img, 0, 0, modelInputWidth, modelInputHeight);
|
55 |
|
56 |
+
const imageData = context.getImageData(0, 0, modelInputWidth, modelInputHeight);
|
|
|
57 |
|
58 |
+
// Check the required data type
|
59 |
+
const isUint8 = true; // Set to true if your model expects uint8, false for float32
|
60 |
+
|
61 |
+
if (isUint8) {
|
62 |
+
// Create Uint8Array tensor
|
63 |
+
return new ort.Tensor('uint8', imageData.data, [1, modelInputHeight, modelInputWidth, 3]);
|
64 |
+
} else {
|
65 |
+
// Normalize to [0, 1] and create Float32Array tensor
|
66 |
+
const floatData = new Float32Array(imageData.data.length / 4 * 3);
|
67 |
for (let i = 0, j = 0; i < imageData.data.length; i += 4) {
|
68 |
+
floatData[j++] = imageData.data[i] / 255; // R
|
69 |
+
floatData[j++] = imageData.data[i + 1] / 255; // G
|
70 |
+
floatData[j++] = imageData.data[i + 2] / 255; // B
|
71 |
}
|
72 |
+
return new ort.Tensor('float32', floatData, [1, 3, modelInputHeight, modelInputWidth]);
|
73 |
+
}
|
74 |
+
};
|
75 |
|
76 |
const postprocessOutput = (output) => {
|
77 |
const boxes = output['boxes'].data; // Replace 'boxes' with your model's output name
|