yolov9-web / index.js
Xenova's picture
Xenova HF staff
Update index.js
180a7d9 verified
raw
history blame
2.79 kB
import { env, AutoProcessor, AutoModel, RawImage } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.15.1';
// Since we will download the model from the Hugging Face Hub, we can skip the local model check
env.allowLocalModels = false;
// Reference the elements that we will need
const status = document.getElementById('status');
const fileUpload = document.getElementById('upload');
const imageContainer = document.getElementById('container');
const example = document.getElementById('example');
const EXAMPLE_URL = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/city-streets.jpg';
// Create a new object detection pipeline
status.textContent = 'Loading model...';
const processor = await AutoProcessor.from_pretrained('Xenova/yolov9-c');
// Testing
processor.feature_extractor.size = { width: 128, height: 128 }
const model = await AutoModel.from_pretrained('Xenova/yolov9-c', {
quantized: false,
});
status.textContent = 'Ready';
example.addEventListener('click', (e) => {
e.preventDefault();
detect(EXAMPLE_URL);
});
fileUpload.addEventListener('change', function (e) {
const file = e.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
// Set up a callback when the file is loaded
reader.onload = e2 => detect(e2.target.result);
reader.readAsDataURL(file);
});
// Detect objects in the image
async function detect(img) {
imageContainer.innerHTML = '';
imageContainer.style.backgroundImage = `url(${img})`;
status.textContent = 'Analysing...';
const image = await RawImage.fromURL(img);
const { pixel_values } = await processor(image);
const { outputs } = await model({images: pixel_values});
status.textContent = '';
outputs.tolist().forEach(renderBox);
}
// Render a bounding box and label on the image
function renderBox([xmin, ymin, xmax, ymax, score, id]) {
console.log([xmin, ymin, xmax, ymax, score, id])
// Generate a random color for the box
const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0);
// Draw the box
const boxElement = document.createElement('div');
boxElement.className = 'bounding-box';
Object.assign(boxElement.style, {
borderColor: color,
left: 100 * xmin / 640 + '%',
top: 100 * ymin / 640 + '%',
width: 100 * (xmax - xmin) / 640 + '%',
height: 100 * (ymax - ymin) / 640 + '%',
})
// Draw label
const labelElement = document.createElement('span');
labelElement.textContent = model.config.id2label[id];
labelElement.className = 'bounding-box-label';
labelElement.style.backgroundColor = color;
boxElement.appendChild(labelElement);
imageContainer.appendChild(boxElement);
}