-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (56 loc) · 2.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { pipeline } from "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.8.0";
// Reference the elements that we will need
const status = document.getElementById("status");
const image = document.getElementById("image");
const detectObjectsButton = document.getElementById('detect-objects')
const imageContainer = document.getElementById('image-container')
const input = document.querySelector('#img-file')
input.addEventListener('change', (e) => {
image.src = URL.createObjectURL(e.target.files[0])
if(imageContainer.children.length > 1) {
const children = imageContainer.querySelectorAll('.bounding-box')
children.forEach(el => imageContainer.removeChild(el))
}
})
status.textContent = "Loading model...";
const detector = await pipeline("object-detection", "Xenova/yolos-tiny");
// Enable Object Detection
detectObjectsButton.addEventListener("click", detectAndDrawObjects);
detectObjectsButton.disabled = false;
status.textContent = "Ready";
// Load model and create a new object detection pipeline
async function detectAndDrawObjects() {
status.textContent = "Detecting Objects...";
const detectedObjet = await detector(image.src, {
threshold: 0.5,
percentage: true,
});
status.textContent = 'Drawing...'
detectedObjet.forEach((object) => {
drawObjectBox(object)
});
status.textContent = "Done!";
}
function drawObjectBox(detectedObject) {
const { label, score, box } = detectedObject
const { xmax, xmin, ymax, ymin } = box
// Generate a random color for the box
const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0)
// Draw the box
const boxElement = document.createElement('div')
boxElement.className = 'bounding-box'
Object.assign(boxElement.style, {
borderColor: color,
left: 100 * xmin + '%',
top: 100 * ymin + '%',
width: 100 * (xmax - xmin) + '%',
height: 100 * (ymax - ymin) + '%',
})
// Draw label
const labelElement = document.createElement('span')
labelElement.textContent = `${label}: ${Math.floor(score * 100)}%`
labelElement.className = 'bounding-box-label'
labelElement.style.backgroundColor = color
boxElement.appendChild(labelElement)
imageContainer.appendChild(boxElement)
}