Package: azure-ai-vision-imageanalysis
Azure Image Analysis client library for PythonThe Image Analysis service provides AI algorithms for processing images and returning information about their content. In a single service call, you can extract one or more visual features from the image simultaneously, including getting a caption for the image, extracting text shown in the image (OCR) and detecting objects. For more information on the service and the supported visual features, seeImage Analysis overview, and theConceptspage.Use the Image Analysis client library to:Authenticate against the serviceSet what features you would like to extractUpload an image for analysis, or send an image URLGet the analysis resultProduct documentation|Samples|Vision Studio|API reference documentation|Package (Pypi)|SDK source codeGetting startedPrerequisitesPython 3.8or later installed, includingpip.AnAzure subscription.AComputer Vision resourcein your Azure subscription.You will need the key and endpoint from this resource to authenticate against the service.Note that in order to run Image Analysis with theCAPTIONorDENSE_CAPTIONSfeatures, the Azure resource needs to be from a GPU-supported region. See the noteherefor a list of supported regions.Install the Image Analysis packagepipinstallazure-ai-vision-imageanalysisSet environment variablesTo authenticate theImageAnalysisClient, you will need the endpoint and key from your Azure Computer Vision resource in theAzure Portal. The code snippet below assumes these values are stored in environment variables:Set the environment variableVISION_ENDPOINTto the endpoint URL. It has the formhttps://your-resource-name.cognitiveservices.azure.com, whereyour-resource-nameis your unique Azure Computer Vision resource name.Set the environment variableVISION_KEYto the key. The key is a 32-character Hexadecimal number.Note that the client library does not directly read these environment variable at run time. The endpoint and key must be provided to the constructor ofImageAnalysisClientin your code. The code snippet below reads environment variables to promote the practice of not hard-coding secrets in your source code.Create and authenticate the clientOnce you define the environment variables, this Python code will create and authenticate a synchronousImageAnalysisClient:importosfromazure.ai.vision.imageanalysisimportImageAnalysisClientfromazure.ai.vision.imageanalysis.modelsimportVisualFeaturesfromazure.core.credentialsimportAzureKeyCredential# Set the values of your computer vision endpoint and computer vision key# as environment variables:try:endpoint=os.environ["VISION_ENDPOINT"]key=os.environ["VISION_KEY"]exceptKeyError:print("Missing environment variable 'VISION_ENDPOINT' or 'VISION_KEY'")print("Set them before running this sample.")exit()# Create an Image Analysis client for synchronous operationsclient=ImageAnalysisClient(endpoint=endpoint,credential=AzureKeyCredential(key))A synchronous client supports synchronous analysis methods, meaning they will block until the service responds with analysis results. The code snippets below all use synchronous methods because it's easier for a getting-started guide. The SDK offers equivalent asynchronous APIs which are often preferred. To create an asynchronous client, do the following:Update the above code to importImageAnalysisClientfrom theaionamespace:fromazure.ai.vision.imageanalysis.aioimportImageAnalysisClientInstall the additional packageaiohttp:pipinstallaiohttpKey conceptsVisual featuresOnce you've initialized anImageAnalysisClient, you need to select one or more visual features to analyze. The options are specified by the enum classVisualFeatures. The following features are supported:VisualFeatures.CAPTION(Examples|Samples): Generate a human-readable sentence that describes the content of an image.VisualFeatures.READ(Examples|Samples): Also known as Optical Character Recognition (OCR). Extract printed or handwritten text from images.Note: For extracting text from PDF, Office, and HTML documents and document images, use the Document Intelligence service with theRead model. This model is optimized for text-heavy digital and scanned documents with an asynchronous REST API that makes it easy to power your intelligent document processing scenarios. This service is separate from the Image Analysis service and has its own SDK.VisualFeatures.DENSE_CAPTIONS(Samples): Dense Captions provides more details by generating one-sentence captions for up to 10 different regions in the image, including one for the whole image.VisualFeatures.TAGS(Samples): Extract content tags for thousands of recognizable objects, living beings, scenery, and actions that appear in images.VisualFeatures.OBJECTS(Samples): Object detection. This is similar to tagging, but focused on detecting physical objects in the image and returning their location.VisualFeatures.SMART_CROPS(Samples): Used to find a representative sub-region of the image for thumbnail generation, with priority given to include faces.VisualFeatures.PEOPLE(Samples): Detect people in the image and return their location.For more information about these features, seeImage Analysis overview, and theConceptspage.Analyze from image buffer or URLTheImageAnalysisClienthas two overloads for the methodanalyze:Analyze an image from an inputbytesobject. The client will upload the image to the service as part of the REST request.Analyze an image from a publicly-accessible URL. The client will send the image URL to the service. The service will fetch the image.The examples below show how to do both. Theanalyzefrom an inputbytesobject examples populate thebytesobject by loading an image from a file on disk.Supported image formatsImage Analysis works on images that meet the following requirements:The image must be presented in JPEG, PNG, GIF, BMP, WEBP, ICO, TIFF, or MPO formatThe file size of the image must be less than 20 megabytes (MB)The dimensions of the image must be greater than 50 x 50 pixels and less than 16,000 x 16,000 pixelsExamplesThe following sections provide code snippets covering these common Image Analysis scenarios:Generate an image caption for an image fileGenerate an image caption for an image URLExtract text (OCR) from an image fileExtract text (OCR) from an image URLThese snippets use the synchronousclientfromCreate and authenticate the client.See theSamplesfolder for fully working samples for all visual features, including asynchronous clients.Generate an image caption for an image fileThis example demonstrates how to generate a one-sentence caption for the image filesample.jpgusing theImageAnalysisClient. The synchronous (blocking)analyzemethod call returns anImageAnalysisResultobject with acaptionproperty of typeCaptionResult. It contains the generated caption and its confidence score in the range [0, 1]. By default the caption may contain gender terms such as "man", "woman", or "boy", "girl". You have the option to request gender-neutral terms such as "person" or "child" by settinggender_neutral_caption = Truewhen callinganalyze.Notes:Caption is only available in some Azure regions. SeePrerequisites.Caption is only supported in English at the moment.# Load image to analyze into a 'bytes' objectwithopen("sample.jpg","rb")asf:image_data=f.read()# Get a caption for the image. This will be a synchronously (blocking) call.result=client.analyze(image_data=image_data,visual_features=[VisualFeatures.CAPTION],gender_neutral_caption=True,# Optional (default is False))# Print caption results to the consoleprint("Image analysis results:")print(" Caption:")ifresult.captionisnotNone:print(f"   '{result.caption.text}', Confidence{result.caption.confidence:.4f}")To generate captions for additional images, simply callanalyzemultiple times. You can use the sameImageAnalysisClientdo to multiple analysis calls.Generate an image caption for an image URLThis example is similar to the above, expect it calls theanalyzemethod and provides apublicly accessible image URLinstead of a file name.# Get a caption for the image. This will be a synchronously (blocking) call.result=client.analyze_from_url(image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",visual_features=[VisualFeatures.CAPTION],gender_neutral_caption=True,# Optional (default is False))# Print caption results to the consoleprint("Image analysis results:")print(" Caption:")ifresult.captionisnotNone:print(f"   '{result.caption.text}', Confidence{result.caption.confidence:.4f}")Extract text from an image fileThis example demonstrates how to extract printed or hand-written text for the image filesample.jpgusing theImageAnalysisClient. The synchronous (blocking)analyzemethod call returns anImageAnalysisResultobject with areadproperty of typeReadResult. It includes a list of text lines and a bounding polygon surrounding each text line. For each line, it also returns a list of words in the text line and a bounding polygon surrounding each word.# Load image to analyze into a 'bytes' objectwithopen("sample.jpg","rb")asf:image_data=f.read()# Extract text (OCR) from an image stream. This will be a synchronously (blocking) call.result=client.analyze(image_data=image_data,visual_features=[VisualFeatures.READ])# Print text (OCR) analysis results to the consoleprint("Image analysis results:")print(" Read:")ifresult.readisnotNone:forlineinresult.read.blocks[0].lines:print(f"   Line: '{line.text}', Bounding box{line.bounding_polygon}")forwordinline.words:print(f"     Word: '{word.text}', Bounding polygon{word.bounding_polygon}, Confidence{word.confidence:.4f}")To extract text for additional images, simply callanalyzemultiple times. You can use the same ImageAnalysisClient do to multiple analysis calls.Note: For extracting text from PDF, Office, and HTML documents and document images, use the Document Intelligence service with theRead model. This model is optimized for text-heavy digital and scanned documents with an asynchronous REST API that makes it easy to power your intelligent document processing scenarios. This service is separate from the Image Analysis service and has its own SDK.Extract text from an image URLThis example is similar to the above, expect it calls theanalyzemethod and provides apublicly accessible image URLinstead of a file name.# Extract text (OCR) from an image stream. This will be a synchronously (blocking) call.result=client.analyze_from_url(image_url="https://aka.ms/azsdk/image-analysis/sample.jpg",visual_features=[VisualFeatures.READ])# Print text (OCR) analysis results to the consoleprint("Image analysis results:")print(" Read:")ifresult.readisnotNone:forlineinresult.read.blocks[0].lines:print(f"   Line: '{line.text}', Bounding box{line.bounding_polygon}")forwordinline.words:print(f"     Word: '{word.text}', Bounding polygon{word.bounding_polygon}, Confidence{word.confidence:.4f}")TroubleshootingExceptionsTheanalyzemethods raise anHttpResponseErrorexception for a non-success HTTP status code response from the service. The exception'sstatus_codewill be the HTTP response status code. The exception'serror.messagecontains a detailed message that will allow you to diagnose the issue:try:result=client.analyze(...)exceptHttpResponseErrorase:print(f"Status code:{e.status_code}")print(f"Reason:{e.reason}")print(f"Message:{e.error.message}")For example, when you provide a wrong authentication key:Status code: 401
Reason: PermissionDenied
Message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.Or when you provide an image URL that does not exist or not accessible:Status code: 400
Reason: Bad Request
Message: The provided image url is not accessible.LoggingThe client uses the standardPython logging library. The SDK logs HTTP request and response details, which may be useful in troubleshooting. To log to stdout, add the following:importsysimportlogging# Acquire the logger for this client library. Use 'azure' to affect both# 'azure.core` and `azure.ai.vision.imageanalysis' libraries.logger=logging.getLogger("azure")# Set the desired logging level. logging.INFO or logging.DEBUG are good options.logger.setLevel(logging.INFO)# Direct logging output to stdout (the default):handler=logging.StreamHandler(stream=sys.stdout)# Or direct logging output to a file:# handler = logging.FileHandler(filename = 'sample.log')logger.addHandler(handler)# Optional: change the default logging format. Here we add a timestamp.formatter=logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s")handler.setFormatter(formatter)By default logs redact the values of URL query strings, the values of some HTTP request and response headers (includingOcp-Apim-Subscription-Keywhich holds the key), and the request and response payloads. To create logs without redaction, set the method argumentlogging_enable = Truewhen you createImageAnalysisClient, or when you callanalyzeon the client.# Create an Image Analysis client with none redacted logclient=ImageAnalysisClient(endpoint=endpoint,credential=AzureKeyCredential(key),logging_enable=True)None redacted logs are generated for log levellogging.DEBUGonly. Be sure to protect none redacted logs to avoid compromising security. For more information seeConfigure logging in the Azure libraries for PythonNext stepsHave a look at theSamplesfolder, containing fully runnable Python code for Image Analysis (all visual features, synchronous and asynchronous clients, from image file or URL).ContributingThis project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution.
For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether
you need to provide a CLA and decorate the PR appropriately (e.g., label,
comment). Simply follow the instructions provided by the bot. You will only
need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information,
see the Code of Conduct FAQ or contactopencode@microsoft.comwith any
additional questions or comments.