Nekshay commited on
Commit
2883555
·
verified ·
1 Parent(s): 2f5d812

Create onnx.js

Browse files
Files changed (1) hide show
  1. onnx.js +123 -0
onnx.js ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useRef, useState } from 'react';
2
+ import Webcam from 'react-webcam';
3
+ import * as ort from 'onnxruntime-web';
4
+
5
+ function ObjectDetection() {
6
+ const [results, setResults] = useState([]);
7
+ const [loading, setLoading] = useState(false);
8
+ const webcamRef = useRef(null);
9
+
10
+ const runInference = async () => {
11
+ if (!webcamRef.current) return;
12
+ setLoading(true);
13
+
14
+ try {
15
+ // Capture image from webcam
16
+ const imageSrc = webcamRef.current.getScreenshot();
17
+
18
+ // Load the ONNX model
19
+ const model = await ort.InferenceSession.create('./model.onnx');
20
+
21
+ // Preprocess the image
22
+ const inputTensor = await preprocessImage(imageSrc);
23
+
24
+ // Define model input
25
+ const feeds = { input: inputTensor };
26
+
27
+ // Run inference
28
+ const output = await model.run(feeds);
29
+
30
+ // Postprocess the output
31
+ const detections = postprocessOutput(output);
32
+ setResults(detections);
33
+ } catch (error) {
34
+ console.error('Error running inference:', error);
35
+ }
36
+
37
+ setLoading(false);
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
+ const inputTensor = new Float32Array(imageData.data.length / 4 * 3);
58
+
59
+ // Normalize pixel values and prepare input tensor
60
+ for (let i = 0, j = 0; i < imageData.data.length; i += 4) {
61
+ inputTensor[j++] = imageData.data[i] / 255; // R
62
+ inputTensor[j++] = imageData.data[i + 1] / 255; // G
63
+ inputTensor[j++] = imageData.data[i + 2] / 255; // B
64
+ }
65
+
66
+ return new ort.Tensor('float32', inputTensor, [1, 3, modelInputHeight, modelInputWidth]);
67
+ };
68
+
69
+ const postprocessOutput = (output) => {
70
+ const boxes = output['boxes'].data; // Replace 'boxes' with your model's output name
71
+ const scores = output['scores'].data; // Replace 'scores' with your model's output name
72
+ const classes = output['classes'].data; // Replace 'classes' with your model's output name
73
+
74
+ const detections = [];
75
+ for (let i = 0; i < scores.length; i++) {
76
+ if (scores[i] > 0.5) { // Confidence threshold
77
+ detections.push({
78
+ box: boxes.slice(i * 4, i * 4 + 4),
79
+ score: scores[i],
80
+ class: classes[i],
81
+ });
82
+ }
83
+ }
84
+
85
+ return detections;
86
+ };
87
+
88
+ return React.createElement(
89
+ 'div',
90
+ null,
91
+ React.createElement('h1', null, 'Object Detection with Webcam'),
92
+ React.createElement(Webcam, {
93
+ audio: false,
94
+ ref: webcamRef,
95
+ screenshotFormat: 'image/jpeg',
96
+ width: 300,
97
+ height: 300,
98
+ }),
99
+ React.createElement(
100
+ 'button',
101
+ { onClick: runInference, disabled: loading },
102
+ loading ? 'Detecting...' : 'Capture & Detect'
103
+ ),
104
+ React.createElement(
105
+ 'div',
106
+ null,
107
+ React.createElement('h2', null, 'Results:'),
108
+ React.createElement(
109
+ 'ul',
110
+ null,
111
+ results.map((result, index) =>
112
+ React.createElement(
113
+ 'li',
114
+ { key: index },
115
+ `Class: ${result.class}, Score: ${result.score.toFixed(2)}, Box: ${result.box.join(', ')}`
116
+ )
117
+ )
118
+ )
119
+ )
120
+ );
121
+ }
122
+
123
+ export default ObjectDetection;