Image analytics with Azure AI Computer Vision

Image analytics with Azure AI Computer Vision Continuing to explore the various uses for Azure AI services. In this post, we’ll use the Computer Vision service to perform image analysis through a React application that we’ll be implementing

Source comparison and review notes
  • Automated pair-review warning (AI bilingual content review): Both originals put REACT_APP_AZURE_SUBSCRIPTION_KEY in browser-side React configuration. GitHub Actions secrets do not keep a build-time REACT_APP value secret from end users; this exposes the subscription key to clients.
  • Automated pair-review warning (AI bilingual content review): The English rendering changes executable JavaScript constructs, including fetch(`${endpoint}...`) to single-quoted fetch('${endpoint}...') and logical && expressions to &, so its copied code is not equivalent to the Spanish example.

Image

Continuing to explore the various uses for Azure AI services.

In this post, we’ll use the Computer Vision service to perform image analysis through a React application that we’ll be implementing in the Azure Static Web App service.

This powerful tool uses machine learning to analyze images and extract rich, contextual insights.

Repository:

GitHub - mdiloreto/analyze-and-generate-images-with-Azure-AI2
Contribute to mdiloreto/analyze-and-generate-images-with-Azure-AI2 development by creating an account on GitHub.github.com

App demo in Azure Static Web App

After deploying our React application in an Azure Static Web App (SWA) using GitHub Actions, we will be able to enter through the public url:

Image

Enter the URL of a photo in the input value and click on “Analyze”:

Run the Loading process while querying the API:

Image

And then it will yield the result:

  • Showing the Image:
Image
  • Throwing Description and Tags:
Image
  • Read Text elements (OCR):
Image

And it also gives us the possibility to see the full answer in JSON format:

Image
Image

Demo: Azure AI Computer Vision React App.

Image

Azure Computer Visions is part of the Azure AI family of cognitive services and specializes in image and video processing and analysis. With the ability to detect and classify visual content, Computer Vision transforms images into understandable data that can drive decisions and process automation. Its features include:

  • Object and scene detection and analysis: The API can identify and locate objects within an image, providing not only the type of object detected, but also the specific position of the object. This is useful for counting, security, and inventory management applications, for example.
  • Reading and extracting text: Using OCR (Optical Character Recognition), Computer Vision is able to read text in a variety of languages, even in low light conditions or on uneven surfaces. This opens up possibilities in document digitization and data entry automation.
  • Facial analysis: Facial analysis can identify approximate ages, emotions, and other attributes from images of human faces.
  • Image description: Probably one of the most impressive features is the ability to generate a textual description of an image, similar to how a person might describe it. This is not only useful for the creation of accessible content (such as in the case of visually impaired people), but also for content analysis on social media or other platforms.

How can we use it?

This is one of the main features of this service: its use is very simple, you just have to call the API.

In this case, we will be making a call to the API in its version 4.0 for the Image Analysis function. I leave below the reference link:

Call the Image Analysis 4.0 Analyze API - Azure AI services
Learn how to call the Image Analysis 4.0 API and configure its behavior.learn.microsoft.com

To call the API we must make an HTTP POST request to the endpoint of our service specifying the parameters in the URL:

Plain text
https://<endpoint>/computervision/imageanalysis:analyze?api-version=2023-10-01&features=tags,read,caption,denseCaptions,smartCrops,objects,people
  • : Represents the Computer Vision service-specific access point assigned to you when you created the resource in Azure. This endpoint varies depending on the region and service instance you’ve configured.
  • /computervision/imageanalysis:analyze: This is the path that indicates the specific API resource to use. In this case, computervision/imageanalysis:analyze refers to the image analysis operation within the Computer Vision service.
  • ?api-version=2023–10–01: This is a query parameter that specifies the version of the API you want to use. Version 2023–10–01 refers to a specific version of the API that supports certain features.
  • &features=tags,read,caption,denseCaptions,smartCrops,objects,people: This is another query parameter that indicates the visual analysis features you want to trigger for the image.
Plain text
<endpoint>
Plain text
/computervision/imageanalysis:analyze
Plain text
computervision/imageanalysis:analyze
Plain text
?api-version=2023-10-01
Plain text
2023-10-01
Plain text
&features=tags,read,caption,denseCaptions,smartCrops,objects,people

Types of Image Analysis in API 4.0

Each Feature offers different types of information:

  • tags: Returns keywords or tags that are relevant to the content of the image.
  • read: Uses OCR (Optical Character Recognition) to read the text visible in the image.
  • caption: Provides a concise textual description of the image.
  • denseCaptions: Provides detailed descriptions for prominent regions of the image.
  • smartCrops: Provides image cropping suggestions based on important visual aspects.
  • objects: Detects objects within the image, including their approximate location.
  • people: Identifies the people in the image, including their approximate location.
Plain text
Tags
Plain text
read
Plain text
Caption
Plain text
denseCaptions
Plain text
smartCrops
Plain text
objects
Plain text
people

Adding the Computer Vision service to Azure

First, we’ll search for “Compute Vision” in our global Azure search engine:

Image

We will enter the service and click on “+Create”

Image

Let’s popularize the Basic Wizard information:

Image
  • In this case, we are selecting the Standard service, but for tests you will be able to use the Free Tier without problems.

In this case we won’t do any network configuration for reasons of the demo, but I recommend keeping the services within our private networks in most cases for security:

Image

The rest of the settings are kept by default. And click on “Review + Create”.

Our Compute Vision Service will be created in our subscription:

Image

Key & Endpoint

The first thing we need to use our Compute Vision service on Azure is the Endpoint and a KEY API.

Image

We must take note and keep this information private. We don’t have to hardcode any of this data in our code, as we’ll see later we’ll use environment variables. In this case, saving the information in the GitHub Actions Secrets.

Save variables to Git Hub Actions

First of all, I recommend forking or cloning the repository and storing it in a personal GitHueb Actions repository.

Repository:https://github.com/mdiloreto/analyze-and-generate-images-with-Azure-AI2

First of all, we will enter our repo and click on “Settings”:

Image

In the Security Settings section, click on “Secrets and Variables” and click on “Actions”:

Image

And we’ll add the variables:

  • REACT_APP_AZURE_ENDPOINT.
  • REACT_APP_AZURE_SUBSCRIPTION_KEY.
Image

We can then pass these variables through our GitHub Actions Workflow.

Passing Environment Variables Through GitHub Actions Workflow

We’ll use the GitHub Actions Workflow yaml to pass the environment variables from our Endpoint and Key:

YAML
# Environment variables available to all jobs and steps in this workflow
Env:
REACT_APP_AZURE_SUBSCRIPTION_KEY: ${{ secrets. REACT_APP_AZURE_SUBSCRIPTION_KEY }}
REACT_APP_AZURE_ENDPOINT: ${{ secrets. REACT_APP_AZURE_ENDPOINT }}

API call with JavaScript React

We’ll be using the following code to consume our Azure Computer Vision service:

Plain text
azure-image-analysis.js
const subscriptionKey = process.env.REACT_APP_AZURE_SUBSCRIPTION_KEY;
const endpoint = process.env.REACT_APP_AZURE_ENDPOINT;
async function analyzeImage(imageUrl) {
API version and query parameters for the features you want to analyze
const apiVersion = '2023-10-01';
const features = 'tags,read,caption';
const response = await fetch('${endpoint}computervision/imageanalysis:analyze?api-version=${apiVersion}&features=${features}', {
method: 'POST',
body: JSON.stringify({ url: imageUrl }),
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Image analysis failed:', response.statusText);
}
return response.json();
}
export default analyzeImage;
  • As we can see, we took the environment variables passed through GitHub Actions Secrets.

Then we import it into the main js code:

JavaScript
import analyzeImage from './azure-image-analysis';

And we call our function by clicking on the Analyze button:

Plain text
const handleAnalyzeClick = async() => {
try {
setLoading(true);
const results = await analyzeImage(inputValue);
setAnalysisResults(results);
} catch (error) {
console.error(error);
} finally {
setLoading(false); This ensures we set loading to false even if there's an error
}
};

API Response

The API response is in JSON format, here’s an example:

Plain text
Full JSON:
{
"modelVersion": "2023-10-01",
"captionResult": {
"text": "a man in a blue jersey running on a field with a net and a crowd of people in the background",
"confidence": 0.7091192603111267
},
"metadata": {
width: 889,
Height: 1186
},
"tagsResult": {
"values": [
{
"name": "person",
confidence: 0.9974309206008911
},
{
"name": "sport",
"confidence": 0.9920082688331604
},
{
"name": "athletic game",
"confidence": 0.9869891405105591
...... other tags.....
]
},
"readResult": {
"blocks": [
{
"lines": [
{
"text": "ETIHAD",
"boundingPolygon": [
{
"x": 376,
"and": 418
},
{
"x": 519,
"and": 364
},
{
"x": 530,
"and": 391
},
{
"x": 387,
"and": 447
}
],
"words": [
{
"text": "ETIHAD",
"boundingPolygon": [
{
"x": 379,
"and": 419
},
{
"x": 501,
"and": 371
},
{
"x": 515,
"and": 397
},
{
"x": 393,
"and": 446
}
],
confidence: 0.868
}
]
},
-....... OTher OCRs. .....
}
]
}
]
}
]
}
}

The important thing is that we process and return the information that in this case interests us from the analysis:

HTML
return (
<div>
<h2>Computer Vision Analysis Results</h2>
<img src={inputValue} alt="Analyzed content" style={{ maxWidth: '100%' }} />
{results.captionResult & (
<div>
<h3>Description:</h3>
<p>{results.captionResult.text}</p>
</div>
)}
{results.tagsResult & (
<div>
<h3>Tags:</h3>
<ul className="center-aligned-list">
{results.tagsResult.values.map((tag, index) => (
<li key={index}>{tag.name}</li>
))}
</ul>
</div>
)}
{results.readResult & & (
<div>
<h3>Read Text:</h3>
<ul className="center-aligned-list">
{results.readResult.blocks.map((block, blockIndex)=>
block.lines.map((line, lineIndex) => (
<li key={'${blockIndex}-${lineIndex}'}>{line.text}</li>
))
)}
</ul>
</div>
)}
<button onClick={toggleJsonDisplay}>
{showJson ? 'Hide full JSON' : 'Show full JSON'}
</button>
{showJson & & (
<div>
<h3>Full JSON:</h3>
<pre>{JSON.stringify(results, null, 2)}</pre>
</div>
)}
</div>
);
}

Giving the possibility to see the full answer in the last part with the “showJson” button

Mateo Di Loreto

Thanks for reading. The learning continues in the next article.