Skip to content

Instantly share code, notes, and snippets.

@depuits
Last active October 7, 2020 06:34
Show Gist options
  • Save depuits/000cbc6c8bbf064a710e95ae062bf91b to your computer and use it in GitHub Desktop.
Save depuits/000cbc6c8bbf064a710e95ae062bf91b to your computer and use it in GitHub Desktop.
Web page for sending an image to a DOODS server and rendering the output on the image. (Run as local file or make sure its served over the same protocol, http/https)
<!DOCTYPE html>
<html>
<body>
<p>DOODS url:</p>
<input type="text" value="http://127.0.0.1:8080/detect" id="doodsUrlInput" />
<p>Select an image:</p>
<input type="file" onchange="proccessImage(event)" />
<p>Canvas:</p>
<p><small id="resultText"></small></p>
<canvas id="resultCanvas" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// helper to get dimensions of an image
const loadImage = file => new Promise((resolve, reject) => {
const img = new Image();
// the following handler will fire after the successful loading of the image
img.onload = () => {
resolve(img);
};
// and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
img.onerror = () => {
reject('There was some problem with the image.');
};
img.src = URL.createObjectURL(file);
});
// here's how to use the helper
const proccessImage = async ({ target: { files } }) => {
const [file] = files;
try {
resultText.innerText = 'Analyzing.';
const img = await loadImage(file);
const { naturalWidth: width, naturalHeight: height } = img;
const canvasWidth = 1024;
const aspect = height / width;
const c = document.getElementById("resultCanvas");
c.width = canvasWidth;
c.height = canvasWidth * aspect;
const ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0, c.width, c.height);
const dataUrl = c.toDataURL();
const metaIndex = dataUrl.indexOf(',');
const base64 = dataUrl.substring(metaIndex + 1);
const requestUrl = doodsUrlInput.value;
const requestData = {
detector_name: "default",
data: base64,
detect: {
"*": 50
}
};
const result = await fetch(requestUrl, {
method:"POST",
body: JSON.stringify(requestData)
});
const data = await result.json();
if (data.detections) {
resultText.innerText = `${data.detections.length} objects detected.`;
for (var i = 0; i < data.detections.length; ++i) {
let det = data.detections[i];
let x = c.width * det.left;
let y = c.height * det.top;
let w = c.width * (det.right - det.left);
let h = c.height * (det.bottom - det.top);
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.fillStyle = "red";
ctx.font = "24px Verdana";
ctx.strokeRect(x, y, w, h);
ctx.fillText(`${det.label} (${det.confidence})`, x + 5, y + 30);
}
} else {
resultText.innerText = 'No objects detected.';
}
} catch(error) {
console.error(error);
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment