Aviso de fim do suporte: em 31 de outubro de 2025, o suporte para o Amazon Lookout for Vision AWS será interrompido. Depois de 31 de outubro de 2025, você não poderá mais acessar o console do Lookout for Vision ou os recursos do Lookout for Vision. Para obter mais informações, visite esta postagem do blog
As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Exibindo informações de classificação e segmentação
Este exemplo mostra a imagem analisada e sobrepõe os resultados da análise. Se a resposta incluir uma máscara de anomalia, a máscara será mostrada nas cores dos tipos de anomalia associados.
Para mostrar informações de classificação e segmentação de imagens
Se ainda não tiver feito isso, faça o seguinte:
-
Se você ainda não tiver feito isso, instale e configure o AWS CLI e AWS SDKs o. Para obter mais informações, consulte Etapa 4: configurar o AWS CLI e AWS SDKs.
-
O usuário que chama
DetectAnomalies
deve ter acesso à versão do modelo que você deseja usar. Para obter mais informações, consulte Configurar SDK permissões.Use o seguinte código:
O código de exemplo a seguir detecta anomalias em uma imagem que você fornece. O exemplo utiliza as seguintes opções de linha de comando:
project
: o nome do projeto que você deseja usar.version
: a versão do modelo, dentro do projeto, que você deseja usar.image
— o caminho e o arquivo de um arquivo de imagem local (JPEGou PNG formato).
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to detect and show anomalies in an image using a trained Amazon Lookout for Vision model. The script displays the analysed image and overlays mask and analysis output. """ import argparse import logging import io import boto3 from PIL import Image, ImageDraw, ImageFont from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class ShowAnomalies: """ Class to detect and show anomalies in an image analyzed by detect_anomalies. """ @staticmethod def draw_line(draw, text, fnt, y_coordinate, color): """ Draws a line of text on the supplied drawing surface. :param draw: The surface on which to draw the text. :param text: The text to draw in the drawing surface. :param fnt: The font for the text. :param y_coordinate: The y position for the text. :param color: The color for the text. :returns The y coordinate for the next line of text. """ text_width, text_height = draw.textsize(text, fnt) draw.rectangle([(10, y_coordinate), (text_width + 10, y_coordinate + text_height)], fill="black") draw.text((10, y_coordinate), text, fill=color, font=fnt) y_coordinate += text_height return y_coordinate @staticmethod def draw_analysis_text(image, analysis): """ Draws classification and segmentation info onto supplied image overlay analysis results on an image analyzed by detect_anomalies. :param analysis: The response from a call to detect_anomalies. :returns Nothing """ ## Calculate a reasonable font size based on image width. font_size = int(image.size[0]/32) fnt = ImageFont.truetype('/Library/Fonts/Tahoma.ttf', font_size) draw = ImageDraw.Draw(image) y_coordinate = 0 # Draw classification information. prediction = "Anomalous" if analysis["DetectAnomalyResult"]["IsAnomalous"] \ else "Normal" confidence = analysis["DetectAnomalyResult"]["Confidence"] found_anomalies = analysis["DetectAnomalyResult"]['Anomalies'] segmentation_info = False logger.info("Prediction: %s", format(prediction)) logger.info("Confidence: %s", format(confidence)) y_coordinate = 0 y_coordinate = ShowAnomalies.draw_line( draw, "Classification", fnt, y_coordinate, "white") y_coordinate = ShowAnomalies.draw_line( draw, f" Prediction: {prediction}", fnt, y_coordinate, "white") y_coordinate = ShowAnomalies.draw_line( draw, f" Confidence: {confidence:.2%}", fnt, y_coordinate, "white") # Draw segmentation information, if present. if (len(found_anomalies)) > 1: logger.info("Anomalies:") y_coordinate = ShowAnomalies.draw_line( draw, "Segmentation:", fnt, y_coordinate, "white") for i in range(1, len(found_anomalies)): # Only display info if more than 0% coverage found. percent_coverage = found_anomalies[i]['PixelAnomaly']['TotalPercentageArea'] if percent_coverage > 0: segmentation_info = True logger.info(" %s", found_anomalies[i]['Name']) logger.info(" Color: %s", found_anomalies[i]['PixelAnomaly']['Color']) logger.info(" Area: %s", percent_coverage) y_coordinate = ShowAnomalies.draw_line( draw, f" Anomaly: {found_anomalies[i]['Name']}. Area: {percent_coverage:.2%}", fnt, y_coordinate, found_anomalies[i]['PixelAnomaly']['Color']) if not segmentation_info: y_coordinate = ShowAnomalies.draw_line( draw, "No segmentation information found.", fnt, y_coordinate, "white") @staticmethod def show_anomaly_prediction(lookoutvision_client, project_name, model_version, photo): """ Detects anomalies in an image (jpg/png) by using your Amazon Lookout for Vision model. Displays the image and overlays prediction information text. :param lookoutvision_client: An Amazon Lookout for Vision Boto3 client. :param project_name: The name of the project that contains the model that you want to use. :param model_version: The version of the model that you want to use. :param photo: The path and name of the image in which you want to detect anomalies. """ try: logger.info("Detecting anomalies in %s", photo) image = Image.open(photo) image_type = Image.MIME[image.format] # Check that image type is valid. if image_type not in ("image/jpeg", "image/png"): logger.info("Invalid image type for %s", photo) raise ValueError( f"Invalid file format. Supply a jpeg or png format file: {photo}" ) # Get images bytes for call to detect_anomalies. image_bytes = io.BytesIO() image.save(image_bytes, format=image.format) image_bytes = image_bytes.getvalue() # Analyze the image. response = lookoutvision_client.detect_anomalies( ProjectName=project_name, ContentType=image_type, Body=image_bytes, ModelVersion=model_version ) # Overlay mask onto analyzed image. image_mask_bytes = response["DetectAnomalyResult"]["AnomalyMask"] image_mask = Image.open(io.BytesIO(image_mask_bytes)) final_img = Image.blend(image, image_mask, 0.5) \ if response["DetectAnomalyResult"]["IsAnomalous"] else image # Overlay analysis output on image. ShowAnomalies.draw_analysis_text(final_img, response) final_img.show() except ClientError as err: logger.info(format(err)) raise def add_arguments(parser): """ Adds command line arguments to the parser. :param parser: The command line parser. """ parser.add_argument( "project", help="The project containing the model that you want to use." ) parser.add_argument( "version", help="The version of the model that you want to use." ) parser.add_argument( "image", help="The file that you want to analyze. " "Supply a local file path.", ) def main(): """ Entrypoint for anomaly detection example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") session = boto3.Session( profile_name='lookoutvision-access') lookoutvision_client = session.client("lookoutvision") parser = argparse.ArgumentParser(usage=argparse.SUPPRESS) add_arguments(parser) args = parser.parse_args() # Analyze the image and show results. ShowAnomalies.show_anomaly_prediction( lookoutvision_client, args.project, args.version, args.image ) except ClientError as err: print("A service error occured: " + format(err.response["Error"]["Message"])) except FileNotFoundError as err: print("The supplied file couldn't be found: " + err.filename) except ValueError as err: print("A value error occured. " + format(err)) else: print("Successfully completed analysis.") if __name__ == "__main__": main()
Interrompa o modelo caso não planeje continuar usando-o.