perborgen commited on
Commit
c7a8428
·
1 Parent(s): a8eab52

Create index.js

Browse files
Files changed (1) hide show
  1. index.js +63 -0
index.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/[email protected]';
2
+ env.allowLocalModels = false;
3
+ import { generateRandomColor, removeElements, getScaledCoordinates } from './utils.js'
4
+ const statusParagraph = document.getElementById("status");
5
+ const fileUploadElement = document.getElementById('file-upload');
6
+ const imageContainer = document.getElementById("image-container");
7
+
8
+ fileUploadElement.addEventListener('change', function(e) {
9
+ const file = e.target.files[0];
10
+ const fr = new FileReader();
11
+ fr.onload = onFileReaderLoad;
12
+ fr.readAsDataURL(file);
13
+ });
14
+
15
+ function onFileReaderLoad(e) {
16
+ removeElements("bounding-box-label");
17
+ removeElements("bounding-box");
18
+ const base64String = e.target.result;
19
+ const imageEl = document.createElement('img')
20
+ imageEl.src = base64String;
21
+ imageContainer.appendChild(imageEl);
22
+ runModel(imageEl);
23
+ };
24
+
25
+ async function runModel(imageEl) {
26
+ statusParagraph.textContent = "Loading model..."
27
+ const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
28
+ statusParagraph.textContent = "Analysing ..."
29
+ const output = await detector(imageEl.src, { threshold: 0.5 });
30
+ statusParagraph.textContent = ""
31
+ output.forEach(object => {
32
+ renderBox(object, imageEl)
33
+ })
34
+ }
35
+
36
+ function renderBox(data, imageEl) {
37
+ const { box, label} = data;
38
+ const {xmax, xmin, ymax, ymin } = getScaledCoordinates(box, imageEl)
39
+ const color = generateRandomColor();
40
+
41
+ // Calculate the width and height of the bounding box
42
+ const boxWidth = xmax - xmin;
43
+ const boxHeight = ymax - ymin;
44
+
45
+ // Draw the box
46
+ const boundingBoxElement = document.createElement("div");
47
+ boundingBoxElement.className = "bounding-box";
48
+ boundingBoxElement.style.border = `2px solid ${color}`
49
+ boundingBoxElement.style.left = xmin + "px";
50
+ boundingBoxElement.style.top = ymin + "px";
51
+ boundingBoxElement.style.width = boxWidth + "px";
52
+ boundingBoxElement.style.height = boxHeight + "px";
53
+ imageContainer.appendChild(boundingBoxElement);
54
+
55
+ // Draw the label
56
+ let labelSpan = document.createElement('span');
57
+ labelSpan.textContent = label;
58
+ labelSpan.className = "bounding-box-label";
59
+ labelSpan.style.backgroundColor = color;
60
+ labelSpan.style.left = xmin + "px";
61
+ labelSpan.style.top = (ymin - 12) + "px";
62
+ imageContainer.appendChild(labelSpan);
63
+ }