DETR-DEMO / static /script.js
cvarandas's picture
first commit - demo
53a413a
Raw
History Blame Contribute Delete
2.4 kB
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);
}
});