Build an AI Image Detective
Build a browser app that detects objects in uploaded images with AI.
Introduction
30 Second Summary
People can glance at a photo and recognize its objects almost instantly. A computer needs a trained model to turn those pixels into useful answers.
In this project, you will build an AI Image Detective that runs entirely in your browser. It uses Transformers.js 4.3.0 with Xenova/detr-resnet-50 to run object detection over a selected photo.
What You'll Build
Inside Visual Studio Code, your finished webpage turns a selected photo into a visual map of recognized objects with labeled boxes and confidence percentages.
By the end of this project, you'll have:
- A local image preview that updates as soon as you select a photo. Choosing a second photo clears the earlier detections.
- Browser-based object detection that recognizes common objects without an API key or backend server.
- Labeled bounding boxes that highlight each detected object directly on the photo. A results panel shows its name plus confidence percentage.
- Secret Mission: A confidence slider that changes the detector's sensitivity. The Run again button refreshes the boxes and results.
Are there any prerequisites?
You need a Windows computer with an internet connection for the first library and model download. The guide covers Visual Studio Code 1.121 or newer setup.
One photo containing common objects provides your test image.
Before We Start
Before any hands-on work, lock in what your browser-based AI Image Detective will do so every later code change has a clear purpose. An in-browser AI model turns a local image into easy-to-read predictions about common objects placed directly over that image.
Set Up a Browser Preview
Your AI Image Detective starts as three local files. A reliable editor with a browser preview gives every later change an immediate test.
Visual Studio Code keeps your code beside its browser preview. This step ends when the starter heading renders in that preview.
In this step, get ready to:
- Install a supported version of Visual Studio Code on Windows.
- Create the HTML, CSS, and JavaScript files for the project.
- Render the AI Image Detective heading in the Integrated Browser.
Verify Visual Studio Code
Visual Studio Code 1.121 introduced the local HTML preview used in this project. Checking the installed version now confirms that the required preview option is available.
- Press the Windows key to open Windows search.
The Windows search field opens.
- Type Visual Studio Code into the search field.
The search results show Visual Studio Code if it is installed.
- Press Enter to open Visual Studio Code if it appears in the results.
The Visual Studio Code window opens when the editor is installed.
- Click Help in the top menu.
- Select About.
The About window shows the installed version. Choose the tab that matches what you found.
✔️ I see the required version or higher
Your editor is ready if the installed version is 1.121 or higher. You can continue with the existing installation.
ⓧ I see an older version
The installed build needs an update before it can provide the Integrated Browser workflow used here.
- Close Visual Studio Code.
- Open the official Visual Studio Code Windows setup guide.
- Download the current Windows User setup.
- Run the downloaded .exe installer.
- Complete the installer prompts using the default options.
The new installation replaces the older build for your Windows account.
- Press the Windows key.
- Type Visual Studio Code into Windows search.
- Press Enter to open the updated editor.
- Click Help.
- Select About to confirm that the version is now 1.121 or higher.
ⓧ Visual Studio Code is not installed
The Windows User setup installs Visual Studio Code for your account without requiring administrator permissions.
- Open the official Visual Studio Code Windows setup guide.
- Download the current Windows User setup.
- Run the downloaded .exe installer.
- Complete the installer prompts using the default options.
Visual Studio Code is now installed for your Windows account.
- Press the Windows key.
- Type Visual Studio Code into Windows search.
- Press Enter to open the editor.
- Click Help.
- Select About to confirm that the installed version is 1.121 or higher.
That setup hurdle is cleared. Your editor now includes the browser preview this project depends on.
Installation not completing?
Confirm that you downloaded the Windows User setup from the official Visual Studio Code site. Close every Visual Studio Code window before running the installer again.
If the About window still shows an older version, restart Visual Studio Code after the installer finishes.
Help me fix my Visual Studio Code installation on Windows.
Create the project files
A Visual Studio Code workspace keeps all files for one project together. Your workspace will be a folder named ai-image-detective on the Desktop.
- Click File in the top menu.
- Select Open Folder....
A Windows folder dialog opens.
- Select Desktop in the folder dialog.
- Click New Folder.
A field appears for the new folder name.
- Enter ai-image-detective as the folder name.
- Press Enter to create the folder.
The new ai-image-detective folder appears in the dialog.
- Select the ai-image-detective folder.
- Click Select Folder.
Visual Studio Code opens the folder as your workspace. You will see AI-IMAGE-DETECTIVE at the top of the Explorer.
- Select Yes, I trust the authors if the Workspace Trust dialog appears.
The Explorer on the left is now ready to hold the project files.
- Select the New File... button in the Explorer.
- Enter index.html as the file name.
- Press Enter to create the file.
The Explorer lists index.html. The empty file opens in the editor.
- Select the New File... button again.
- Enter style.css as the file name.
- Press Enter to create the file.
The Explorer now lists style.css beneath the project folder.
- Select the New File... button once more.
- Enter index.js as the file name.
- Press Enter to create the file.
The Explorer now shows index.html, style.css, and index.js inside ai-image-detective.
Why three files?
The HTML file defines what appears on the page. The CSS file will control its appearance.
The JavaScript file will handle image selection and AI detection. Keeping these jobs separate makes each change easier to test.
Render the starter heading
The starter HTML gives the browser a complete document to render. It also connects the empty stylesheet and JavaScript file that later steps will build on.
- Select index.html in the Explorer.
- Replace the empty file contents by pasting the code below:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Detective</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>AI Image Detective</h1>
<script type="module" src="./index.js"></script>
</body>
</html>
What does this HTML do?
- The document declaration tells the browser to use modern HTML rules.
- The head stores the page title and display settings.
- The stylesheet link connects style.css to the page.
- The h1 provides the visible AI Image Detective heading.
- The module script connects index.js to the page.
- Press Ctrl+S to save index.html.
Before you open the preview, what text do you expect the browser to display?
- Right-click index.html in the Explorer.
- Select Open in Integrated Browser.
The Integrated Browser opens inside Visual Studio Code. You will see the heading AI Image Detective on a plain page.
That is your first visible win. The browser is now rendering code from index.html inside your editor.
Preview missing the heading?
Confirm that index.html is saved inside the ai-image-detective folder. Check that the heading text sits between the opening and closing h1 tags.
If the preview option is missing, return to Help and About. Confirm that Visual Studio Code is 1.121 or higher.
Help me find out why my HTML heading is missing from the Integrated Browser.
✔️ Awesome, I've got everything!
Your three-file starter project now matches the required setup. The Integrated Browser confirms that the HTML renders successfully.
ⓧ I'd like to double check the full code
The complete index.html file should match this reference.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Detective</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>AI Image Detective</h1>
<script type="module" src="./index.js"></script>
</body>
</html>
The style.css and index.js files should both be empty.
Your browser preview loop is ready. Next, you will turn this starter page into an image uploader that displays a selected photo.
Build the Image Uploader
Your starter heading is already visible in the Visual Studio Code Integrated Browser. Now the detective needs a way to accept the photo it will inspect.
Before AI can interpret a photo, the browser must read a learner-selected file and display it reliably. This step builds that upload loop so you can see its current limit for yourself.
In this step, get ready to:
- Build the page structure for the image uploader.
- Style the upload interface.
- Connect selected images to the preview.
Build the page structure
The HTML structure gives each part of the uploader a clear purpose. The image container and results panel start hidden until the app has something useful to show.
- Switch to index.html in Visual Studio Code.
- Select the entire file.
- Replace it with this page structure:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Detective</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main class="app-card">
<p class="eyebrow">Browser-based AI</p>
<h1>AI Image Detective</h1>
<p class="intro">Choose a photo and let a machine-learning model find common objects.</p>
<label for="image-upload">Choose an image</label>
<input id="image-upload" type="file" accept="image/*">
<p id="status" class="status" aria-live="polite">Choose an image to preview.</p>
<div id="image-container" class="image-container hidden">
<img id="preview-image" class="preview-image" alt="Selected image preview">
</div>
<section id="results-panel" class="results-panel hidden">
<h2>Detected objects</h2>
<ul id="results-list"></ul>
</section>
</main>
<script type="module" src="./index.js"></script>
</body>
</html>
What does this code do?
- The app-card element groups the complete interface into one page card.
- The image-upload input accepts image files from the learner's computer.
- The status element provides updates as the app processes an image.
- The hidden class keeps the preview and results out of view at the start.
- Save index.html.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see the heading above an image file picker. The status beneath it reads Choose an image to preview.
Missing the image picker?
Confirm that you replaced the body of index.html while keeping the link to style.css and the script for index.js.
If the old heading remains on its own, save the file before refreshing. Help me compare my uploader HTML with the required structure.
✔️ Awesome, I've got everything!
Your uploader structure is in place. The preview now contains the controls and containers needed for the next changes.
ⓧ I'd like to double check the full code
- Compare your complete index.html file with this reference:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Detective</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main class="app-card">
<p class="eyebrow">Browser-based AI</p>
<h1>AI Image Detective</h1>
<p class="intro">Choose a photo and let a machine-learning model find common objects.</p>
<label for="image-upload">Choose an image</label>
<input id="image-upload" type="file" accept="image/*">
<p id="status" class="status" aria-live="polite">Choose an image to preview.</p>
<div id="image-container" class="image-container hidden">
<img id="preview-image" class="preview-image" alt="Selected image preview">
</div>
<section id="results-panel" class="results-panel hidden">
<h2>Detected objects</h2>
<ul id="results-list"></ul>
</section>
</main>
<script type="module" src="./index.js"></script>
</body>
</html>
Style the upload interface
The CSS turns the bare controls into a focused app card. A flexible width keeps the interface usable when the Integrated Browser panel becomes narrow.
- Switch to style.css in Visual Studio Code.
- Add the page foundation with this code:
:root {
color: #172033;
background: #eef2ff;
font-family: Arial, Helvetica, sans-serif;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
padding: 32px 16px;
background: linear-gradient(135deg, #eef2ff, #f8fafc);
}
.app-card {
width: min(760px, 100%);
margin: 0 auto;
padding: 28px;
background: #ffffff;
border-radius: 18px;
box-shadow: 0 18px 50px rgba(30, 41, 59, 0.14);
}
How does the page frame work?
- The root styles set the page colors and the default font.
- The universal selector makes padding part of each element's declared size.
- The body creates the full-height gradient background.
- The app-card rule centers a white card with a maximum width of 760px.
- Save style.css.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see the interface centered inside a rounded white card. A pale gradient now fills the surrounding page.
Still seeing a plain page?
Check that index.html still links to ./style.css. Confirm that the class on the main element is spelled app-card.
Help me find why my page foundation styles are missing.
The first text group establishes the app's visual hierarchy. The eyebrow introduces the browser-based theme before the main heading.
- Add these text styles below the app-card block:
.eyebrow {
margin: 0;
color: #4f46e5;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 8px 0;
}
.intro {
margin: 0 0 22px;
color: #475569;
}
How do these text styles help?
- The eyebrow rule creates a compact uppercase label above the title.
- The heading margin keeps the title close to its supporting text.
- The intro rule adds space before the uploader controls.
- Save style.css.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see a small purple Browser-based AI label above the heading. The supporting sentence now appears in muted text.
Text styles not appearing?
Confirm that the paragraph classes in index.html are eyebrow and intro. CSS class names must match the HTML values exactly.
Help me compare my text classes with my CSS selectors.
The file picker is the main control in this step. A full-width dashed border makes its role clear inside the card.
- Add these control styles below the intro block:
label {
display: block;
margin-bottom: 8px;
font-weight: 700;
}
input[type="file"] {
width: 100%;
padding: 12px;
border: 2px dashed #a5b4fc;
border-radius: 10px;
background: #f8fafc;
}
How is the picker styled?
- The label becomes a bold block above the control.
- The attribute selector targets the image file input.
- The input fills the available card width without exceeding it.
- Save style.css.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see the file picker stretch across the card. Its dashed purple border separates it from the surrounding text.
Picker still looks unchanged?
Check that the input in index.html uses type="file". Confirm that the CSS selector includes the quotation marks around file.
Help me debug why my file input selector is not applying.
The status line reports what the app is doing. The image rules keep each selected photo inside the card while preserving its proportions.
- Add the status and preview styles below the file-input block:
.status {
min-height: 24px;
margin: 14px 0;
color: #4338ca;
font-weight: 700;
}
.image-container {
position: relative;
width: 100%;
margin-top: 18px;
}
.preview-image {
display: block;
width: 100%;
height: auto;
border-radius: 12px;
}
How will the preview scale?
- The status keeps a stable space for messages beneath the picker.
- The image container provides a full-width area for the selected photo.
- The preview uses automatic height to preserve the photo's proportions.
- Save style.css.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see the status message in bold purple text beneath the picker. The spacing below the control should remain steady.
Status style missing?
Confirm that the status paragraph in index.html includes class="status". Check the closing brace on the preceding file-input rule.
Help me find the CSS error before my status rule.
The results panel needs its own visual area once detection exists. The hidden utility keeps unfinished or empty sections out of view.
- Add the final styles below the preview-image block:
.results-panel {
margin-top: 22px;
padding: 18px;
border-radius: 12px;
background: #f8fafc;
}
.hidden {
display: none;
}
Why hide the results area?
- The results panel creates a separate card for future object names.
- The hidden class removes the empty preview and results panel from the page.
- Save style.css.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
You should see the heading, introduction, picker, and status inside the card. The empty image area and Detected objects panel are now hidden.
Empty sections still visible?
Confirm that both hidden elements in index.html include the hidden class. Check that the selector in style.css begins with a period.
Help me debug why my hidden elements remain visible.
✔️ Awesome, I've got everything!
Your uploader now has a responsive card layout. The interface is ready to display a selected photo.
ⓧ I'd like to double check the full code
- Compare your complete style.css file with this reference:
:root {
color: #172033;
background: #eef2ff;
font-family: Arial, Helvetica, sans-serif;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
padding: 32px 16px;
background: linear-gradient(135deg, #eef2ff, #f8fafc);
}
.app-card {
width: min(760px, 100%);
margin: 0 auto;
padding: 28px;
background: #ffffff;
border-radius: 18px;
box-shadow: 0 18px 50px rgba(30, 41, 59, 0.14);
}
.eyebrow {
margin: 0;
color: #4f46e5;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 8px 0;
}
.intro {
margin: 0 0 22px;
color: #475569;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 700;
}
input[type="file"] {
width: 100%;
padding: 12px;
border: 2px dashed #a5b4fc;
border-radius: 10px;
background: #f8fafc;
}
.status {
min-height: 24px;
margin: 14px 0;
color: #4338ca;
font-weight: 700;
}
.image-container {
position: relative;
width: 100%;
margin-top: 18px;
}
.preview-image {
display: block;
width: 100%;
height: auto;
border-radius: 12px;
}
.results-panel {
margin-top: 22px;
padding: 18px;
border-radius: 12px;
background: #f8fafc;
}
.hidden {
display: none;
}
Display the selected image
The browser receives a selected file through the file input's change event. JavaScript can then use FileReader to turn that file into an image source the page can display.
- Switch to index.js in Visual Studio Code.
- Add the image-preview behavior with this code:
const imageUpload = document.getElementById("image-upload");
const status = document.getElementById("status");
const imageContainer = document.getElementById("image-container");
const previewImage = document.getElementById("preview-image");
const resultsPanel = document.getElementById("results-panel");
const resultsList = document.getElementById("results-list");
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = () => {
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
resultsPanel.classList.add("hidden");
status.textContent = "Image ready. AI detection is coming next.";
};
reader.readAsDataURL(file);
});
What does this code do?
- The constants connect the script to the uploader elements in index.html.
- The change listener receives the first file selected through the input.
- The FileReader loads that file with readAsDataURL().
- The reader's result becomes the source of preview-image before its container becomes visible.
- Save index.js.
- Return to the Integrated Browser from earlier.
- Refresh the preview.
Before you choose a photo, do you expect the page to identify any objects yet?
- Use the image file picker to select a photo containing a common object.
Your selected image should appear beneath the status message. The status now reads Image ready. AI detection is coming next.
That upload loop is working. The page still provides no object names or boxes, which confirms the capability the next step needs to add.
Image not appearing?
Confirm that the IDs in index.js match the IDs in index.html exactly. Check that reader.readAsDataURL(file) appears after the reader.onload function.
Help me debug why my selected image is not appearing.
✔️ Awesome, I've got everything!
Your image uploader works. A selected local photo now appears inside the responsive app card.
ⓧ I'd like to double check the full code
- Compare your complete index.js file with this reference:
const imageUpload = document.getElementById("image-upload");
const status = document.getElementById("status");
const imageContainer = document.getElementById("image-container");
const previewImage = document.getElementById("preview-image");
const resultsPanel = document.getElementById("results-panel");
const resultsList = document.getElementById("results-list");
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = () => {
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
resultsPanel.classList.add("hidden");
status.textContent = "Image ready. AI detection is coming next.";
};
reader.readAsDataURL(file);
});
Your browser can now read a local image and display it inside the app. Next, you will give the detective an object-detection model so it can begin interpreting those pixels.
Let the AI Inspect the Image
Your uploader can now read a local image and display it in the app. It can display the pixels without understanding the objects they represent.
Now you will connect Transformers.js 4.3.0 to a pretrained object-detection model. The model performs AI inference inside the browser.
In this step, get ready to:
- Load the object-detection model while the image input remains disabled.
- Run the detector after the selected image finishes loading.
- Make the model's prediction data visible in the results panel.
Load the object-detection model
The model must finish loading before the app accepts an image. Disabling the file input prevents a detection request from reaching an unavailable model.
- Switch back to the index.html tab from earlier.
- Find these adjacent lines:
<input id="image-upload" type="file" accept="image/*">
<p id="status" class="status" aria-live="polite">Choose an image to preview.</p>
What does the current HTML allow?
The current file input is available as soon as the page opens. The status message only describes the image-preview stage.
- Replace both lines with this version:
<input id="image-upload" type="file" accept="image/*" disabled>
<p id="status" class="status" aria-live="polite">Loading AI model...</p>
What changed in the HTML?
- The disabled attribute blocks image selection during model loading.
- The status now tells you that the app is preparing the AI model.
- Save index.html.
- Refresh the Integrated Browser preview.
You should see Loading AI model... beneath a disabled image input. This confirms that the interface protects the loading state.
- Switch back to the style.css tab from earlier.
- Add this selector directly below the existing input[type="file"] block:
input:disabled {
cursor: wait;
opacity: 0.6;
}
What does this style do?
- The lower opacity makes the unavailable input visibly different.
- The wait cursor signals that the app is still preparing something.
- Save style.css.
- Refresh the Integrated Browser preview.
You should see the image input appear faded. Moving the pointer over it should show the wait cursor.
The page now communicates the loading state. The next code connects that state to the real model download.
- Switch back to the index.js tab from earlier.
- Replace the six const declarations at the beginning of the file with this expanded opening:
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0";
const imageUpload = document.getElementById("image-upload");
const status = document.getElementById("status");
const imageContainer = document.getElementById("image-container");
const previewImage = document.getElementById("preview-image");
const resultsPanel = document.getElementById("results-panel");
const resultsList = document.getElementById("results-list");
let detector;
try {
detector = await pipeline("object-detection", "Xenova/detr-resnet-50");
imageUpload.disabled = false;
status.textContent = "AI model ready. Upload an image.";
} catch (error) {
status.textContent = "The AI model could not load. Check your internet connection and refresh.";
}
What does this code do?
- The import loads pipeline from the version-pinned Transformers.js CDN URL.
- The pipeline() call prepares Xenova/detr-resnet-50 for the object-detection task.
- The detector variable stores the loaded model pipeline.
- The successful path enables the file input.
- The error path replaces the loading message with a recovery instruction.
The initial model download is roughly 40 MB. The Integrated Browser can briefly feel unresponsive because loading happens on the main interface thread.
- Save index.js.
- Refresh the Integrated Browser preview.
You should first see Loading AI model.... When loading finishes, you should see AI model ready. Upload an image.
That is a major piece working. Your browser has loaded a real object-detection model without an API key or backend server.
Model still loading?
Confirm that your computer still has internet access. The browser needs it for the initial library and model download.
Refresh the Integrated Browser after restoring the connection. Keep the preview open until the status reports that the model is ready.
Help me debug why the browser model does not finish loading.
Connect detection to the image
The detector needs the finished image data before it can inspect anything. The previewImage.onload handler creates that timing boundary.
- In index.js, find the current image-upload listener:
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = () => {
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
resultsPanel.classList.add("hidden");
status.textContent = "Image ready. AI detection is coming next.";
};
reader.readAsDataURL(file);
});
How does the current listener stop?
The current listener finishes after displaying the selected image. It never passes that image to the detector.
- Replace the listener with this version:
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
resultsPanel.classList.add("hidden");
const reader = new FileReader();
reader.onload = () => {
previewImage.onload = () => detect(previewImage);
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
};
reader.readAsDataURL(file);
});
What changed in the listener?
- The results panel becomes hidden when you choose another file.
- The previewImage.onload handler waits for the browser to finish decoding the image.
- The handler passes the loaded previewImage to detect().
- Save index.js.
- Refresh the Integrated Browser preview.
You should still see AI model ready. Upload an image. after loading completes. This confirms that the updated listener has valid syntax.
- Return to the bottom of index.js.
- Add the detect() function directly below the image-upload listener:
async function detect(image) {
imageUpload.disabled = true;
status.textContent = "Analyzing image...";
try {
const results = await detector(image.src, {
threshold: 0.5,
percentage: true,
});
resultsList.innerHTML = "";
resultsPanel.classList.remove("hidden");
results.forEach((result) => {
const item = document.createElement("li");
item.textContent = JSON.stringify(result);
resultsList.appendChild(item);
});
status.textContent = "Raw predictions ready.";
} catch (error) {
status.textContent = "The image could not be analyzed. Try a different image.";
} finally {
imageUpload.disabled = false;
}
}
What does the detector do?
- The function disables image selection during analysis.
- The detector keeps predictions whose confidence reaches 0.5.
- The percentage: true option returns box coordinates as proportions of the image.
- Each result becomes a list item through JSON.stringify(result).
- The finally block restores image selection after success or failure.
- Save index.js.
Test the detector
The first analysis can briefly pause the interface while the model processes the image. A short pause means the browser is performing the inference locally.
Before you choose a photo, what details do you expect the model to return for each detected object?
- Select an image containing common objects with the file picker.
You should see Analyzing image... while detection runs. The status should change to Raw predictions ready. when the results appear.
The results panel should contain entries with label, score, and box data. The image still has no visual boxes.
Why are the predictions hard to read?
Each JSON entry contains useful machine-readable data. The label names an object.
The score measures confidence. The box contains the detected object's coordinates.
These raw values prove that inference works. Their awkward presentation is the intended shortfall that the next step turns into readable labels and positioned overlays.
No raw predictions?
Wait for the model-ready status before choosing a file. A selection made while the input is unavailable cannot start detection.
Try a clear photo containing common objects if analysis completes with an empty list. Keep the internet connection available during the initial model download.
Help me debug why my detector does not show raw prediction data.
Your files should now match the completed code for this step. Use the second tab if you want to compare every line.
✔️ Awesome, I've got everything!
Great. Double check that you saved index.html, style.css, and index.js.
ⓧ I'd like to double check the full code
Compare your three files with these complete versions for this step.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Detective</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main class="app-card">
<p class="eyebrow">Browser-based AI</p>
<h1>AI Image Detective</h1>
<p class="intro">Choose a photo and let a machine-learning model find common objects.</p>
<label for="image-upload">Choose an image</label>
<input id="image-upload" type="file" accept="image/*" disabled>
<p id="status" class="status" aria-live="polite">Loading AI model...</p>
<div id="image-container" class="image-container hidden">
<img id="preview-image" class="preview-image" alt="Selected image preview">
</div>
<section id="results-panel" class="results-panel hidden">
<h2>Detected objects</h2>
<ul id="results-list"></ul>
</section>
</main>
<script type="module" src="./index.js"></script>
</body>
</html>
:root {
color: #172033;
background: #eef2ff;
font-family: Arial, Helvetica, sans-serif;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
padding: 32px 16px;
background: linear-gradient(135deg, #eef2ff, #f8fafc);
}
.app-card {
width: min(760px, 100%);
margin: 0 auto;
padding: 28px;
background: #ffffff;
border-radius: 18px;
box-shadow: 0 18px 50px rgba(30, 41, 59, 0.14);
}
.eyebrow {
margin: 0;
color: #4f46e5;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 8px 0;
}
.intro {
margin: 0 0 22px;
color: #475569;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 700;
}
input[type="file"] {
width: 100%;
padding: 12px;
border: 2px dashed #a5b4fc;
border-radius: 10px;
background: #f8fafc;
}
input:disabled {
cursor: wait;
opacity: 0.6;
}
.status {
min-height: 24px;
margin: 14px 0;
color: #4338ca;
font-weight: 700;
}
.image-container {
position: relative;
width: 100%;
margin-top: 18px;
}
.preview-image {
display: block;
width: 100%;
height: auto;
border-radius: 12px;
}
.results-panel {
margin-top: 22px;
padding: 18px;
border-radius: 12px;
background: #f8fafc;
}
.hidden {
display: none;
}
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0";
const imageUpload = document.getElementById("image-upload");
const status = document.getElementById("status");
const imageContainer = document.getElementById("image-container");
const previewImage = document.getElementById("preview-image");
const resultsPanel = document.getElementById("results-panel");
const resultsList = document.getElementById("results-list");
let detector;
try {
detector = await pipeline("object-detection", "Xenova/detr-resnet-50");
imageUpload.disabled = false;
status.textContent = "AI model ready. Upload an image.";
} catch (error) {
status.textContent = "The AI model could not load. Check your internet connection and refresh.";
}
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
resultsPanel.classList.add("hidden");
const reader = new FileReader();
reader.onload = () => {
previewImage.onload = () => detect(previewImage);
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
};
reader.readAsDataURL(file);
});
async function detect(image) {
imageUpload.disabled = true;
status.textContent = "Analyzing image...";
try {
const results = await detector(image.src, {
threshold: 0.5,
percentage: true,
});
resultsList.innerHTML = "";
resultsPanel.classList.remove("hidden");
results.forEach((result) => {
const item = document.createElement("li");
item.textContent = JSON.stringify(result);
resultsList.appendChild(item);
});
status.textContent = "Raw predictions ready.";
} catch (error) {
status.textContent = "The image could not be analyzed. Try a different image.";
} finally {
imageUpload.disabled = false;
}
}
Your browser can now inspect an uploaded image and return real object predictions. Next up, you will turn those coordinates into labeled boxes that people can understand at a glance.
Turn Predictions into Visual Results
Your detector already turns a photo into raw predictions. That proves browser-based AI inference is working.
Raw prediction objects are difficult to interpret. You will turn them into labelled bounding boxes and a readable results list.
In this step, get ready to:
- Convert each prediction into a readable label with a confidence percentage.
- Draw a colored box around each detected object.
- Clear stale detections when the learner selects another image.
Render readable predictions
Each prediction contains a label. It also contains a score that becomes easier to understand when displayed as a percentage.
- In index.js, scroll below the closing brace of detect().
- Add the readable results renderer by pasting this function:
function renderResults(results) {
resultsList.innerHTML = "";
resultsPanel.classList.remove("hidden");
if (results.length === 0) {
const item = document.createElement("li");
item.textContent = "No objects met the 50% confidence threshold.";
resultsList.appendChild(item);
return;
}
results.forEach(({ label, score }) => {
const item = document.createElement("li");
item.textContent = `${label}: ${Math.round(score * 100)}% confidence`;
resultsList.appendChild(item);
});
}
What does this function do?
- The empty-results branch displays a clear message when no prediction reaches the confidence threshold.
- The loop creates one list item for every detected object.
- The score calculation turns a decimal confidence value into a whole-number percentage.
- Inside detect(), delete the raw rendering block that starts with resultsList.innerHTML = ""; and ends after resultsList.appendChild(item);.
- Call the readable results renderer in the same location by adding this line:
renderResults(results);
Why call the renderer here?
The detector has finished producing predictions at this point. Passing those predictions to renderResults() keeps the display logic separate from the model call.
- Save index.js.
- Switch back to the Integrated Browser from earlier.
- Refresh the preview with its refresh control.
- Select an image containing common objects.
You should see object names followed by confidence percentages in the results panel. The raw coordinate data is gone.
Still seeing raw JSON?
Check that you removed the old loop containing JSON.stringify(result). Confirm that renderResults(results); sits inside the try block.
Make sure the renderResults() function sits outside detect().
help me debug why renderResults is not replacing the raw JSON output
Readable text explains what the model found. A visual overlay also needs the box coordinates from each prediction.
- Near the top of index.js, find the resultsList declaration.
- Add the color palette directly below that declaration:
const colors = ["#2563eb", "#dc2626", "#16a34a", "#9333ea", "#ea580c"];
Why use a color palette?
The palette gives neighboring detections different border colors. The renderer cycles through these values when an image contains more than five objects.
- Return to the bottom of index.js.
- Add the overlay renderer directly below renderResults() by pasting this function:
function renderBox({ box, label, score }, index) {
const { xmin, ymin, xmax, ymax } = box;
const color = colors[index % colors.length];
const boxElement = document.createElement("div");
const labelElement = document.createElement("span");
boxElement.className = "bounding-box";
Object.assign(boxElement.style, {
left: `${xmin * 100}%`,
top: `${ymin * 100}%`,
width: `${(xmax - xmin) * 100}%`,
height: `${(ymax - ymin) * 100}%`,
borderColor: color,
});
labelElement.className = "bounding-box-label";
labelElement.textContent = `${label} ${Math.round(score * 100)}%`;
labelElement.style.backgroundColor = color;
boxElement.appendChild(labelElement);
imageContainer.appendChild(boxElement);
}
How does the overlay work?
- The coordinate values identify the left edge, top edge, right edge, and bottom edge of the detected object.
- The percentage calculations turn those coordinates into positions inside the image container.
- The label element displays the object name with its rounded confidence percentage.
- The finished box is appended to imageContainer so it can sit over the preview image.
- Save index.js.
- Refresh the preview with its refresh control.
- Select an image containing common objects.
You should still see the readable results list. This confirms that the new renderer loads without a syntax error.
- Inside detect(), find the call to renderResults(results);.
- Call the overlay renderer directly below it by adding this line:
results.forEach(renderBox);
What does forEach pass in?
The loop passes one prediction into renderBox() at a time. It also supplies the prediction index so the function can select a color.
- Save index.js.
- Refresh the preview with its refresh control.
- Select the same test image again.
You should see the generated label text near the image. The next substep positions each generated element over its detected object.
Seeing no generated labels?
Check that results.forEach(renderBox); appears directly after renderResults(results);.
Confirm that renderBox() sits outside renderResults().
help me find why renderBox is not adding labels to the image container
Style the detection overlays
The image container already uses relative positioning. Absolute positioning can now place every generated box against that container.
- Switch back to the open style.css tab.
- Add the box styles directly below the .preview-image block:
.bounding-box {
position: absolute;
border: 3px solid;
border-radius: 4px;
pointer-events: none;
}
What styles the box?
- Absolute positioning places the box using the percentages assigned by renderBox().
- The border makes the detection boundary visible without covering the image.
- Disabled pointer events keep the overlay from blocking interaction with the page.
- Save style.css.
- Refresh the preview with its refresh control.
- Select your test image again.
You should see colored rectangles positioned over the detected objects. Their labels still need a readable treatment.
Boxes appearing below the image?
Confirm that the selector begins with .bounding-box. Check that its position value is absolute.
Make sure the existing .image-container block still uses relative positioning.
help me debug bounding boxes that are not positioned over the preview image
- Add the label styles directly below the .bounding-box block:
.bounding-box-label {
position: absolute;
top: 0;
left: 0;
padding: 3px 6px;
color: #ffffff;
font-size: 0.75rem;
font-weight: 700;
white-space: nowrap;
}
What styles the label?
The label sits in the top-left corner of its box. Its compact white text remains readable against the background color assigned in renderBox().
- Save style.css.
- Refresh the preview with its refresh control.
- Select your test image again.
You should see a colored name and confidence label attached to the top-left corner of each box.
- Finish the results panel spacing by adding these selectors below the existing .results-panel block:
.results-panel h2 {
margin-top: 0;
font-size: 1.1rem;
}
.results-panel ul {
margin-bottom: 0;
padding-left: 22px;
}
Why adjust the results panel?
The heading spacing keeps the panel compact. The list spacing gives every detected object a clear reading position.
- Save style.css.
- Refresh the preview with its refresh control.
- Select your test image again.
You should see labeled colored boxes over the image. The results panel should show a compact heading above the readable prediction list.
Labels difficult to read?
Check that .bounding-box-label includes white text. Confirm that renderBox() assigns the same color to the label background and box border.
help me debug unreadable bounding box labels in the image detector
✔️ Awesome, I've got everything!
Great. Double check that you saved style.css before continuing.
ⓧ I'd like to double check the full code
Compare your style.css file with this complete version.
:root {
color: #172033;
background: #eef2ff;
font-family: Arial, Helvetica, sans-serif;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
padding: 32px 16px;
background: linear-gradient(135deg, #eef2ff, #f8fafc);
}
.app-card {
width: min(760px, 100%);
margin: 0 auto;
padding: 28px;
background: #ffffff;
border-radius: 18px;
box-shadow: 0 18px 50px rgba(30, 41, 59, 0.14);
}
.eyebrow {
margin: 0;
color: #4f46e5;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
h1 {
margin: 8px 0;
}
.intro {
margin: 0 0 22px;
color: #475569;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 700;
}
input[type="file"] {
width: 100%;
padding: 12px;
border: 2px dashed #a5b4fc;
border-radius: 10px;
background: #f8fafc;
}
input:disabled {
cursor: wait;
opacity: 0.6;
}
.status {
min-height: 24px;
margin: 14px 0;
color: #4338ca;
font-weight: 700;
}
.image-container {
position: relative;
width: 100%;
margin-top: 18px;
}
.preview-image {
display: block;
width: 100%;
height: auto;
border-radius: 12px;
}
.bounding-box {
position: absolute;
border: 3px solid;
border-radius: 4px;
pointer-events: none;
}
.bounding-box-label {
position: absolute;
top: 0;
left: 0;
padding: 3px 6px;
color: #ffffff;
font-size: 0.75rem;
font-weight: 700;
white-space: nowrap;
}
.results-panel {
margin-top: 22px;
padding: 18px;
border-radius: 12px;
background: #f8fafc;
}
.results-panel h2 {
margin-top: 0;
font-size: 1.1rem;
}
.results-panel ul {
margin-bottom: 0;
padding-left: 22px;
}
.hidden {
display: none;
}
How to use this reference
Compare each selector in order. Pay close attention to the closing braces around the overlay and results-panel styles.
Clear old detections and verify the app
Every box is a new element inside the image container. Removing those elements before another result set prevents old detections from covering a new photo.
- Switch back to the open index.js tab.
- Add the cleanup function directly above renderResults() by pasting this code:
function clearDetections() {
document
.querySelectorAll(".bounding-box")
.forEach((boxElement) => boxElement.remove());
}
How does cleanup work?
The selector finds every generated box in the page. The loop removes each matched element before the app draws another result set.
- Inside the image upload event listener, find resultsPanel.classList.add("hidden");.
- Add the cleanup call directly above that line:
clearDetections();
Why clear on image selection?
A newly selected file immediately clears overlays from the previous photo. Hiding the results panel also prevents the old labels from remaining visible during the next analysis.
- Save index.js.
- Refresh the preview with its refresh control.
- Select one image containing common objects.
- Select a different image after the first analysis finishes.
You should see the first image's boxes disappear as soon as you select the second image.
- Inside the try block of detect(), find the renderer calls and the old raw-predictions status message.
- Replace that section with the final cleanup and success-message logic:
clearDetections();
renderResults(results);
results.forEach(renderBox);
status.textContent =
results.length === 1
? "Found 1 object."
: `Found ${results.length} objects.`;
What changes in the final detection flow?
- Cleanup runs again immediately before new boxes are rendered.
- The readable results list and visual boxes use the same prediction array.
- The status message reports a singular object or a plural object count.
- Save index.js.
✔️ Awesome, I've got everything!
Your final JavaScript is in place. Double check that index.js is saved before the last test.
ⓧ I'd like to double check the full code
Compare your index.js file with this complete version.
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.0";
const imageUpload = document.getElementById("image-upload");
const status = document.getElementById("status");
const imageContainer = document.getElementById("image-container");
const previewImage = document.getElementById("preview-image");
const resultsPanel = document.getElementById("results-panel");
const resultsList = document.getElementById("results-list");
const colors = ["#2563eb", "#dc2626", "#16a34a", "#9333ea", "#ea580c"];
let detector;
try {
detector = await pipeline("object-detection", "Xenova/detr-resnet-50");
imageUpload.disabled = false;
status.textContent = "AI model ready. Upload an image.";
} catch (error) {
status.textContent = "The AI model could not load. Check your internet connection and refresh.";
}
imageUpload.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
clearDetections();
resultsPanel.classList.add("hidden");
const reader = new FileReader();
reader.onload = () => {
previewImage.onload = () => detect(previewImage);
previewImage.src = reader.result;
imageContainer.classList.remove("hidden");
};
reader.readAsDataURL(file);
});
async function detect(image) {
imageUpload.disabled = true;
status.textContent = "Analyzing image...";
try {
const results = await detector(image.src, {
threshold: 0.5,
percentage: true,
});
clearDetections();
renderResults(results);
results.forEach(renderBox);
status.textContent =
results.length === 1
? "Found 1 object."
: `Found ${results.length} objects.`;
} catch (error) {
status.textContent = "The image could not be analyzed. Try a different image.";
} finally {
imageUpload.disabled = false;
}
}
function clearDetections() {
document
.querySelectorAll(".bounding-box")
.forEach((boxElement) => boxElement.remove());
}
function renderResults(results) {
resultsList.innerHTML = "";
resultsPanel.classList.remove("hidden");
if (results.length === 0) {
const item = document.createElement("li");
item.textContent = "No objects met the 50% confidence threshold.";
resultsList.appendChild(item);
return;
}
results.forEach(({ label, score }) => {
const item = document.createElement("li");
item.textContent = `${label}: ${Math.round(score * 100)}% confidence`;
resultsList.appendChild(item);
});
}
function renderBox({ box, label, score }, index) {
const { xmin, ymin, xmax, ymax } = box;
const color = colors[index % colors.length];
const boxElement = document.createElement("div");
const labelElement = document.createElement("span");
boxElement.className = "bounding-box";
Object.assign(boxElement.style, {
left: `${xmin * 100}%`,
top: `${ymin * 100}%`,
width: `${(xmax - xmin) * 100}%`,
height: `${(ymax - ymin) * 100}%`,
borderColor: color,
});
labelElement.className = "bounding-box-label";
labelElement.textContent = `${label} ${Math.round(score * 100)}%`;
labelElement.style.backgroundColor = color;
boxElement.appendChild(labelElement);
imageContainer.appendChild(boxElement);
}
How to use this reference
Compare the declarations and functions in order. Check the placement of both clearDetections() calls if old boxes remain.
Before the final check, consider whether any boxes from the first photo should remain after the second photo loads.
- Refresh the preview with its refresh control.
- Wait for the status to report that the model is ready.
- Select a photo containing common objects.
- Wait for the object count to replace the analyzing message.
- Select a second photo containing different objects.
- Wait for the second object count to appear.
You should see colored boxes with labels positioned over recognized objects. The results panel should list each object with its confidence percentage.
After the second image finishes, you should see a fresh set of detections. Every box from the first image should be gone.
Old boxes still visible?
Confirm that clearDetections() uses the exact .bounding-box selector. Check that renderBox() assigns that class to every generated box.
Make sure cleanup runs in the image upload listener. It must also run inside detect() before the renderers.
help me debug stale bounding boxes that remain after selecting another image
You did it. Your AI Image Detective now turns model coordinates into a visual result that someone can understand at a glance.
Secret mission
Add a Confidence Control
Give the user control over how certain the detector must be before it displays an object. You will add a confidence slider with a live percentage label plus a button that reruns detection on the current image.
Clean Up Your Resources
Clean Up Your Resources
Your AI Image Detective runs locally through Visual Studio Code's Integrated Browser. There are no ongoing costs.
Decide whether to keep the project ready, pause by closing it, or delete the local folder.
Resources you used:
- The ai-image-detective project folder containing index.html, style.css, and index.js.
Keep everything running
No action needed. Choose this if you want to keep testing the detector or demonstrate it to someone.
- Keep index.html, style.css, and index.js together inside the ai-image-detective folder.
- Leave the current Integrated Browser tab open if you plan to continue testing now.
Pause - I'll come back to this later
Close the current preview to stop using the model for now. Your project files stay ready for another session.
- Save any final changes in index.html, style.css, and index.js.
- Close the Integrated Browser tab.
- Close Visual Studio Code.
No background server or cloud resource keeps running after the preview closes.
Delete - I don't want to use this again
Deleting the project folder permanently removes your HTML, CSS, and JavaScript files. Your original photos stay safe because the app reads them from their existing locations.
- Close the Integrated Browser tab.
- Close Visual Studio Code.
- Use Windows search to open File Explorer.
- Browse to the location where you created the ai-image-detective folder.
- Select the ai-image-detective folder.
- Press Shift+Delete to permanently remove the folder.
- Confirm the permanent deletion if Windows asks.
- Check that the previous location no longer contains the ai-image-detective folder.
Cleanup complete. Your project files are gone while your original photos remain untouched.
Nice Work!
Nice Work!
You did it! Your AI Image Detective now turns a local photo into labeled object detections directly in the browser.
You've learned how to:
- Built a three-file web app with HTML, CSS, and JavaScript. Used the browser File API to read and preview a selected image.
- Loaded Transformers.js 4.3.0 with Xenova/detr-resnet-50 to run object detection without an API key. Managed asynchronous model loading through clear status messages.
- Converted each prediction into a labeled bounding box over the image. Presented its confidence score in a readable results panel.
- Completed the optional Secret Mission by adding a confidence slider from 10% through 90%. Added a rerun control that analyzes the current image with the selected threshold.
Ready to quiz yourself?