CoolFace
Apppublic

eaglelandsonce/JSObjectIDExample

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
index.js73 linesDownload Raw Back to root
1import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.6.0';2 3// Since we will download the model from the Hugging Face Hub, we can skip the local model check4env.allowLocalModels = false;5 6// Reference the elements that we will need7const status = document.getElementById('status');8const fileUpload = document.getElementById('file-upload');9const imageContainer = document.getElementById('image-container');10 11// Create a new object detection pipeline12status.textContent = 'Loading model...';13const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');14status.textContent = 'Ready';15 16fileUpload.addEventListener('change', function (e) {17    const file = e.target.files[0];18    if (!file) {19        return;20    }21 22    const reader = new FileReader();23 24    // Set up a callback when the file is loaded25    reader.onload = function (e2) {26        imageContainer.innerHTML = '';27        const image = document.createElement('img');28        image.src = e2.target.result;29        imageContainer.appendChild(image);30        detect(image);31    };32    reader.readAsDataURL(file);33});34 35 36// Detect objects in the image37async function detect(img) {38    status.textContent = 'Analysing...';39    const output = await detector(img.src, {40        threshold: 0.5,41        percentage: true,42    });43    status.textContent = '';44    output.forEach(renderBox);45}46 47// Render a bounding box and label on the image48function renderBox({ box, label }) {49    const { xmax, xmin, ymax, ymin } = box;50 51    // Generate a random color for the box52    const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0);53 54    // Draw the box55    const boxElement = document.createElement('div');56    boxElement.className = 'bounding-box';57    Object.assign(boxElement.style, {58        borderColor: color,59        left: 100 * xmin + '%',60        top: 100 * ymin + '%',61        width: 100 * (xmax - xmin) + '%',62        height: 100 * (ymax - ymin) + '%',63    })64 65    // Draw label66    const labelElement = document.createElement('span');67    labelElement.textContent = label;68    labelElement.className = 'bounding-box-label';69    labelElement.style.backgroundColor = color;70 71    boxElement.appendChild(labelElement);72    imageContainer.appendChild(boxElement);73}