Spaces:
Sleeping
Sleeping
let canvas; | |
let ctx; | |
document.addEventListener("DOMContentLoaded", () => { | |
canvas = document.getElementById("drawingCanvas"); | |
ctx = canvas.getContext("2d"); | |
let isDrawing = false; | |
canvas.addEventListener("mousedown", () => isDrawing = true); | |
canvas.addEventListener("mouseup", () => isDrawing = false); | |
canvas.addEventListener("mousemove", draw); | |
function draw(event) { | |
if (!isDrawing) return; | |
ctx.fillStyle = "black"; | |
ctx.fillRect(event.offsetX, event.offsetY, 20, 20); | |
} | |
}); | |
function clearCanvas() { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
document.getElementById("result").innerText = ""; | |
} | |
// Inverting the images as the training images had a black background with white text, | |
// opposite of what we get from the canvas | |
function invertCanvasColors(inputCanvas) { | |
const tempCanvas = document.createElement("canvas"); | |
const tempCtx = tempCanvas.getContext("2d"); | |
// Set the size of the temporary canvas to match the original canvas | |
tempCanvas.width = inputCanvas.width; | |
tempCanvas.height = inputCanvas.height; | |
// Draw the original canvas onto the temporary canvas | |
tempCtx.drawImage(inputCanvas, 0, 0); | |
// Get the pixel data of the image | |
const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height); | |
const data = imageData.data; | |
// Invert each pixel's RGB values | |
for (let i = 0; i < data.length; i += 4) { | |
data[i] = 255 - data[i]; // Red channel | |
data[i + 1] = 255 - data[i + 1]; // Green channel | |
data[i + 2] = 255 - data[i + 2]; // Blue channel | |
} | |
tempCtx.putImageData(imageData, 0, 0); | |
return tempCanvas; | |
} | |
function sendToServer() { | |
const invertedCanvas = invertCanvasColors(canvas); | |
let image = invertedCanvas.toDataURL("image/png"); | |
let blob = dataURItoBlob(image); | |
let formData = new FormData(); | |
formData.append("image", blob, "drawing.png"); | |
fetch("https://ramachandrankulothungan-digit-doodle-recognition.hf.space/predict", { | |
method: "POST", | |
body: formData | |
}) | |
.then(response => response.json()) | |
.then(data => document.getElementById("result").innerText = "Prediction: " + data.prediction) | |
.catch(error => console.error("Error:", error)); | |
} | |
function dataURItoBlob(dataURI) { | |
let byteString = atob(dataURI.split(",")[1]); | |
let arrayBuffer = new ArrayBuffer(byteString.length); | |
let uint8Array = new Uint8Array(arrayBuffer); | |
for (let i = 0; i < byteString.length; i++) { | |
uint8Array[i] = byteString.charCodeAt(i); | |
} | |
return new Blob([uint8Array], { type: "image/png" }); | |
} | |