File size: 2,397 Bytes
53a413a | 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 | document.addEventListener("DOMContentLoaded", async () => {
console.log("document loaded...")
init();
})
function init() {
const img = document.querySelector("#example-img");
fetch(img.src)
.then((res) => res.blob())
.then((blob) => {
detectObjects(blob, img.naturalWidth, img.naturalHeight);
})
}
async function detectObjects(file, imgW, imgH) {
try {
const form = new FormData()
form.append('image', file)
const response = await fetch(
'/detect-image',
{
method: 'POST',
body: form,
},
)
const objectDetectionRes = await response.json()
document.querySelector("#output").innerText = JSON.stringify(objectDetectionRes, null, 2);
const container = document.querySelector("#image-container");
container.querySelectorAll(".box").forEach((el) => el.remove());
const boxes = objectDetectionRes.map((obj) => {
const w = (100 * (obj.box.xmax - obj.box.xmin)) / imgW;
const h = (100 * (obj.box.ymax - obj.box.ymin)) / imgH;
const box = document.createElement("div");
box.classList.add("box");
box.style.position = "absolute";
box.style.border = "solid 2px red";
box.style.top = (100 * obj.box.ymin) / imgH + "%";
box.style.left = (100 * obj.box.xmin) / imgW + "%";
box.style.width = w + "%";
box.style.height = h + "%";
const para = document.createElement("p");
para.classList.add("font-mono")
para.classList.add("text-base")
para.classList.add("text-white")
para.innerText = obj.label;
box.appendChild(para);
return box;
})
boxes.forEach((box) => {
container.appendChild(box);
})
} catch (e) {
document.querySelector("#output").innerText = e.message;
}
}
document.querySelector("#image-file").addEventListener("change", async (e) => {
const file = e.target.files[0];
const newImage = new Image();
newImage.src = URL.createObjectURL(file)
const img = document.querySelector("#example-img");
img.src = newImage.src;
newImage.onload = () => {
detectObjects(file, newImage.naturalWidth, newImage.naturalHeight);
}
}); |