Identify Object in an Image with Next.js

Eugene Musebe

Identify object in an image with Nextjs

Introduction

This article is to demonstrate how nextjs can be used to identify objects inside an image file.

Codesandbox

The final version of this project can be viewed on Codesandbox.

You can find the full source code on my Github repo.

Prerequisites

Basic/entry-level knowledge and understanding of javascript and React/Nextjs.

Setting Up the Sample Project

Create your project's root directory: npx create-next-app videocall

Head to the directory: cd videocall

We will use Cloudinary online storage feature to store the processed media files.

Include Cloudinary in your project dependencies: npm install cloudinary

Use this Link to create or log into your Cloudinary account. You should receive a dashboard containing the necessary environment variables for integration.

Create a new file named .env.local in your project root directory and use the following guide to fill your variables.

1"pages/api/cloudinary.js"
2
3
4CLOUDINARY_CLOUD_NAME =
5
6CLOUDINARY_API_KEY =
7
8CLOUDINARY_API_SECRET=

Restart your project: npm run dev.

Create a directory pages/api/cloudinary.js.

Configure the environment keys and libraries.

1"pages/api/cloudinary.js"
2
3
4var cloudinary = require("cloudinary").v2;
5
6cloudinary.config({
7 cloud_name: process.env.CLOUDINARY_NAME,
8 api_key: process.env.CLOUDINARY_API_KEY,
9 api_secret: process.env.CLOUDINARY_API_SECRET,
10});

From Cloudinary, we will also consume one of its addons, specifically the Cloudinary AI Content Analysis add-on. This will enable you to have access to its content-aware detection model. There are several models involved as you can explore through thislink.

From your console, locate the addon from your navigation bar:

Use the Nextjs server-side handler function to execute the Nextjs post request:

1"pages/api/cloudinary.js"
2
3
4export default async function handler(req, res) {
5 if (req.method === "POST") {
6 let url = ""
7 if (req.method === 'POST') {
8 // console.log(fileStr)
9 try {
10 const uploadedResponse = await cloudinary.uploader.upload(fileStr, {
11 detection:'coco_v1',
12 auto_tagging : 0.6
13 });
14 uploaded_url = uploadedResponse.tags;
15 } catch (error) {
16 console.log(error);
17 }
18 res.status(200).json({ data: uploaded_url});
19 console.log('complete!');
20 }
21}

The above function will upload the request body media files to Cloudinary, It will then follow the parameters instruction to detect the image items and send the list back to the front end as a response array.

Frontend

We will require html2canvas to capture the image file from the DOM as a base64 string: npm install html2canvas.

Include it in the home along with the react hooks we will use:

1"pages/index.js"
2
3
4import { useRef, useState } from 'react';
5import html2canvas from 'html2canvas';

Declare the following variables in the Home function. We will use them as we move one

1"pages/index.js"
2
3
4export default function Home() {
5
6 const imageRef = useRef(undefined);
7
8 const [items, setItems] = useState('')
9 let array;
10
11 return(
12 <>
13 </>
14 )
15}

Fill the UI code in the return statement. The css files can be found in the Github repo:

1"pages/index.js"
2
3
4return (
5 <div className="container">
6 <h1>Identify object in an image with Nextjs</h1>
7 <div className="row">
8 <div className="column">
9 <img ref={imageRef} src="sample.jpg" />
10
11 </div>
12 <div className="column">
13 <section>
14 <h3>Identified items Show Here</h3>
15
16 {items && <h5>{items}</h5>}
17 </section>
18 </div>
19 </div>
20 <button className="button" onClick={tagHandler}>Identify</button>
21 </div>
22)

To identify the image items, we only require one function. Let's call it itemHandler:

1"pages/index.js"
2
3
4 const tagHandler = () => {
5 const image = imageRef.current;
6 html2canvas(image).then((canvas) => {
7 try {
8 fetch('/api/cloudinary', {
9 method: 'POST',
10 body: JSON.stringify({ data: canvas.toDataURL() }),
11 headers: { 'Content-Type': 'application/json' },
12 })
13 .then((response) => response.json())
14 .then((data) => {
15 array = data.data
16 setItems(array.toString())
17
18 console.log(items)
19 });
20 } catch (error) {
21 console.error(error);
22 }
23 })
24 }

First, we reference our initial image object(on the left below) and capture its base64 string using html2canvas. We then send it to the backend for item identification. The response will contain an array of items identified. We capture them as a string using the setItems state hook and use the hook to display the result to the user.

That's it! Run your code to view your project.

Ensure to go through the article to enjoy the experience.

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.