이미지에서 레이블 감지 - Amazon Rekognition

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

이미지에서 레이블 감지

DetectLabels작업을 사용하여 이미지에서 레이블 (개체 및 개념) 을 감지하고 이미지 속성에 대한 정보를 검색할 수 있습니다. 이미지 속성에는 전경색과 배경색, 이미지의 선명도, 밝기, 대비와 같은 속성이 포함됩니다. 이미지의 레이블만 검색하거나, 이미지의 속성만 검색하거나, 둘 다 검색할 수 있습니다. 예는 Amazon S3 버킷에 저장된 이미지 분석를 참조하세요.

다음 예제에서는 다양한 AWS SDK와 AWS CLI to 호출을 DetectLabels 사용합니다. DetectLabels 작업 응답에 대한 자세한 내용은 DetectLabels 응답 단원을 참조하십시오.

이미지에서 레이블을 감지하려면
  1. 아직 설정하지 않았다면 다음과 같이 하세요.

    1. AmazonRekognitionFullAccess 권한과 AmazonS3ReadOnlyAccess 권한을 가진 사용자를 생성하거나 업데이트합니다. 자세한 설명은 1단계: AWS 계정 설정 및 사용자 생성 섹션을 참조하세요.

    2. 및 AWS SDK를 AWS CLI 설치하고 구성합니다. 자세한 설명은 2단계: AWS CLI 및 AWS SDK 설정 섹션을 참조하세요.

  2. 나무, 집, 보트 등과 같은 객체가 한 개 이상 있는 이미지를 S3 버킷에 업로드합니다. 이미지는 .jpg 또는 .png 형식이어야 합니다.

    이에 관한 지침은 Amazon Simple Storage Service 사용 설명서에서 Amazon S3에 객체 업로드를 참조하세요.

  3. 다음 예제를 사용하여 DetectLabels 작업을 호출합니다.

    Java

    이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. bucketphoto의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

    package com.amazonaws.samples; import java.util.List; import com.amazonaws.services.rekognition.model.BoundingBox; import com.amazonaws.services.rekognition.model.DetectLabelsRequest; import com.amazonaws.services.rekognition.model.DetectLabelsResult; import com.amazonaws.services.rekognition.model.Image; import com.amazonaws.services.rekognition.model.Instance; import com.amazonaws.services.rekognition.model.Label; import com.amazonaws.services.rekognition.model.Parent; import com.amazonaws.services.rekognition.model.S3Object; import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.AmazonRekognitionException; public class DetectLabels { public static void main(String[] args) throws Exception { String photo = "photo"; String bucket = "bucket"; AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); DetectLabelsRequest request = new DetectLabelsRequest() .withImage(new Image().withS3Object(new S3Object().withName(photo).withBucket(bucket))) .withMaxLabels(10).withMinConfidence(75F); try { DetectLabelsResult result = rekognitionClient.detectLabels(request); List<Label> labels = result.getLabels(); System.out.println("Detected labels for " + photo + "\n"); for (Label label : labels) { System.out.println("Label: " + label.getName()); System.out.println("Confidence: " + label.getConfidence().toString() + "\n"); List<Instance> instances = label.getInstances(); System.out.println("Instances of " + label.getName()); if (instances.isEmpty()) { System.out.println(" " + "None"); } else { for (Instance instance : instances) { System.out.println(" Confidence: " + instance.getConfidence().toString()); System.out.println(" Bounding box: " + instance.getBoundingBox().toString()); } } System.out.println("Parent labels for " + label.getName() + ":"); List<Parent> parents = label.getParents(); if (parents.isEmpty()) { System.out.println(" None"); } else { for (Parent parent : parents) { System.out.println(" " + parent.getName()); } } System.out.println("--------------------"); System.out.println(); } } catch (AmazonRekognitionException e) { e.printStackTrace(); } } }
    AWS CLI

    이 예제는 detect-labels CLI 작업의 JSON 출력을 표시합니다. bucketphoto의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. profile-name의 값을 개발자 프로필 이름으로 대체하세요.

    aws rekognition detect-labels --image '{ "S3Object": { "Bucket": "bucket-name", "Name": "file-name" } }' \ --features GENERAL_LABELS IMAGE_PROPERTIES \ --settings '{"ImageProperties": {"MaxDominantColors":1}, {"GeneralLabels":{"LabelInclusionFilters":["Cat"]}}}' \ --profile profile-name \ --region us-east-1

    Windows 디바이스에서 CLI에 액세스하는 경우 작은따옴표 대신 큰따옴표를 사용하고 내부 큰따옴표는 백슬래시(즉 \)로 이스케이프 처리하여 발생할 수 있는 구문 분석 오류를 해결합니다. 예를 들어 다음을 참조하세요.

    aws rekognition detect-labels --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"file-name\"}}" --features GENERAL_LABELS IMAGE_PROPERTIES \ --settings "{\"GeneralLabels\":{\"LabelInclusionFilters\":[\"Car\"]}}" --profile profile-name --region us-east-1
    Python

    이 예제는 입력 이미지에서 감지된 레이블을 표시합니다. main 함수에서, bucketphoto 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 profile_name의 값을 개발자 프로필의 이름으로 대체합니다.

    #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) import boto3 def detect_labels(photo, bucket): session = boto3.Session(profile_name='profile-name') client = session.client('rekognition') response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}}, MaxLabels=10, # Uncomment to use image properties and filtration settings #Features=["GENERAL_LABELS", "IMAGE_PROPERTIES"], #Settings={"GeneralLabels": {"LabelInclusionFilters":["Cat"]}, # "ImageProperties": {"MaxDominantColors":10}} ) print('Detected labels for ' + photo) print() for label in response['Labels']: print("Label: " + label['Name']) print("Confidence: " + str(label['Confidence'])) print("Instances:") for instance in label['Instances']: print(" Bounding box") print(" Top: " + str(instance['BoundingBox']['Top'])) print(" Left: " + str(instance['BoundingBox']['Left'])) print(" Width: " + str(instance['BoundingBox']['Width'])) print(" Height: " + str(instance['BoundingBox']['Height'])) print(" Confidence: " + str(instance['Confidence'])) print() print("Parents:") for parent in label['Parents']: print(" " + parent['Name']) print("Aliases:") for alias in label['Aliases']: print(" " + alias['Name']) print("Categories:") for category in label['Categories']: print(" " + category['Name']) print("----------") print() if "ImageProperties" in str(response): print("Background:") print(response["ImageProperties"]["Background"]) print() print("Foreground:") print(response["ImageProperties"]["Foreground"]) print() print("Quality:") print(response["ImageProperties"]["Quality"]) print() return len(response['Labels']) def main(): photo = 'photo-name' bucket = 'bucket-name' label_count = detect_labels(photo, bucket) print("Labels detected: " + str(label_count)) if __name__ == "__main__": main()
    .NET

    이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. bucketphoto의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) using System; using Amazon.Rekognition; using Amazon.Rekognition.Model; public class DetectLabels { public static void Example() { String photo = "input.jpg"; String bucket = "bucket"; AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(); DetectLabelsRequest detectlabelsRequest = new DetectLabelsRequest() { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket }, }, MaxLabels = 10, MinConfidence = 75F }; try { DetectLabelsResponse detectLabelsResponse = rekognitionClient.DetectLabels(detectlabelsRequest); Console.WriteLine("Detected labels for " + photo); foreach (Label label in detectLabelsResponse.Labels) Console.WriteLine("{0}: {1}", label.Name, label.Confidence); } catch (Exception e) { Console.WriteLine(e.Message); } } }
    Ruby

    이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. bucketphoto의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

    #Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) # Add to your Gemfile # gem 'aws-sdk-rekognition' require 'aws-sdk-rekognition' credentials = Aws::Credentials.new( ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] ) bucket = 'bucket' # the bucket name without s3:// photo = 'photo' # the name of file client = Aws::Rekognition::Client.new credentials: credentials attrs = { image: { s3_object: { bucket: bucket, name: photo }, }, max_labels: 10 } response = client.detect_labels attrs puts "Detected labels for: #{photo}" response.labels.each do |label| puts "Label: #{label.name}" puts "Confidence: #{label.confidence}" puts "Instances:" label['instances'].each do |instance| box = instance['bounding_box'] puts " Bounding box:" puts " Top: #{box.top}" puts " Left: #{box.left}" puts " Width: #{box.width}" puts " Height: #{box.height}" puts " Confidence: #{instance.confidence}" end puts "Parents:" label.parents.each do |parent| puts " #{parent.name}" end puts "------------" puts "" end
    Node.js

    이 예제는 입력 이미지에서 감지된 레이블 목록을 표시합니다. bucketphoto의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 profile_name의 값을 개발자 프로필의 이름으로 대체합니다.

    TypeScript 정의를 사용하는 경우 Node.js 프로그램을 const AWS = require('aws-sdk') 실행하려면 정의를 import AWS from 'aws-sdk' 대신 사용해야 할 수도 있습니다. 자세한 내용은 AWS SDK for Javascript를 참조하세요. 구성 설정에 따라 AWS.config.update({region:region});으로 리전을 지정해야 할 수도 있습니다.

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) // Load the SDK var AWS = require('aws-sdk'); const bucket = 'bucket-name' // the bucketname without s3:// const photo = 'image-name' // the name of file var credentials = new AWS.SharedIniFileCredentials({profile: 'profile-name'}); AWS.config.credentials = credentials; AWS.config.update({region:'region-name'}); const client = new AWS.Rekognition(); const params = { Image: { S3Object: { Bucket: bucket, Name: photo }, }, MaxLabels: 10 } client.detectLabels(params, function(err, response) { if (err) { console.log(err, err.stack); // if an error occurred } else { console.log(`Detected labels for: ${photo}`) response.Labels.forEach(label => { console.log(`Label: ${label.Name}`) console.log(`Confidence: ${label.Confidence}`) console.log("Instances:") label.Instances.forEach(instance => { let box = instance.BoundingBox console.log(" Bounding box:") console.log(` Top: ${box.Top}`) console.log(` Left: ${box.Left}`) console.log(` Width: ${box.Width}`) console.log(` Height: ${box.Height}`) console.log(` Confidence: ${instance.Confidence}`) }) console.log("Parents:") label.Parents.forEach(parent => { console.log(` ${parent.Name}`) }) console.log("------------") console.log("") }) // for response.labels } // if });
    Java V2

    이 코드는 AWS 문서 SDK 예제 GitHub 저장소에서 가져온 것입니다. 전체 예제는 여기에서 확인하세요.

    //snippet-start:[rekognition.java2.detect_labels.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.services.rekognition.model.Image; import software.amazon.awssdk.services.rekognition.model.DetectLabelsRequest; import software.amazon.awssdk.services.rekognition.model.DetectLabelsResponse; import software.amazon.awssdk.services.rekognition.model.Label; import software.amazon.awssdk.services.rekognition.model.RekognitionException; import software.amazon.awssdk.services.rekognition.model.S3Object; import java.util.List; /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DetectLabels { public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <bucket> <image>\n\n" + "Where:\n" + " bucket - The name of the Amazon S3 bucket that contains the image (for example, ,ImageBucket)." + " image - The name of the image located in the Amazon S3 bucket (for example, Lake.png). \n\n"; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucket = args[0]; String image = args[1]; Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create("profile-name")) .build(); getLabelsfromImage(rekClient, bucket, image); rekClient.close(); } // snippet-start:[rekognition.java2.detect_labels_s3.main] public static void getLabelsfromImage(RekognitionClient rekClient, String bucket, String image) { try { S3Object s3Object = S3Object.builder() .bucket(bucket) .name(image) .build() ; Image myImage = Image.builder() .s3Object(s3Object) .build(); DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder() .image(myImage) .maxLabels(10) .build(); DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest); List<Label> labels = labelsResponse.labels(); System.out.println("Detected labels for the given photo"); for (Label label: labels) { System.out.println(label.name() + ": " + label.confidence().toString()); } } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } } // snippet-end:[rekognition.java2.detect_labels.main] }

DetectLabels 작업 요청

DetectLabel에 대한 입력은 이미지입니다. 이 예제 JSON 입력에서는 Amazon S3 버킷에서 소스 이미지를 불러옵니다. MaxLabels는 응답에 반환되는 레이블의 최대 수입니다. MinConfidence는 Amazon Rekognition Image가 감지된 레이블을 응답에 반환하기 위해 충족해야 하는 최소 정확성 신뢰도 수준입니다.

Features로 반환하려는 이미지의 특성을 하나 이상 지정할 수 있으며, 이를 통해 GENERAL_LABELSIMAGE_PROPERTIES를 선택할 수 있습니다. GENERAL_LABELS를 포함하면 입력 이미지에서 감지된 레이블이 반환되고 IMAGE_PROPERTIES를 포함하면 이미지 색상 및 품질에 액세스할 수 있습니다.

Settings를 통해 반환된 항목을 GENERAL_LABELSIMAGE_PROPERTIES 특성 둘 다에 대해 필터링할 수 있습니다. 레이블의 경우 포함 및 제외 필터를 사용할 수 있습니다. 특정 레이블, 개별 레이블 또는 레이블 카테고리별로 필터링할 수도 있습니다.

  • LabelInclusionFilters - 응답에 포함할 레이블을 지정할 수 있습니다.

  • LabelExclusionFilters - 응답에서 제외할 레이블을 지정할 수 있습니다.

  • LabelCategoryInclusionFilters - 응답에 포함할 레이블 범주를 지정할 수 있습니다.

  • LabelCategoryExclusionFilters - 응답에서 제외하려는 레이블 범주를 지정할 수 있습니다.

필요에 따라 포함 필터와 제외 필터를 조합하여 일부 레이블 또는 카테고리를 제외하는 동시에 다른 레이블이나 카테고리를 포함할 수도 있습니다.

IMAGE_PROPERTIES는 이미지의 주 색상 및 선명도, 밝기, 대비 등과 같은 품질 속성을 가리킵니다. IMAGE_PROPERTIES를 감지할 때 MaxDominantColors 파라미터를 사용하여 반환할 주 색상의 최대 수(기본값 10)를 지정할 수 있습니다.

{ "Image": { "S3Object": { "Bucket": "bucket", "Name": "input.jpg" } }, "MaxLabels": 10, "MinConfidence": 75, "Features": [ "GENERAL_LABELS", "IMAGE_PROPERTIES" ], "Settings": { "GeneralLabels": { "LabelInclusionFilters": [<Label(s)>], "LabelExclusionFilters": [<Label(s)>], "LabelCategoryInclusionFilters": [<Category Name(s)>], "LabelCategoryExclusionFilters": [<Category Name(s)>] }, "ImageProperties": { "MaxDominantColors":10 } } }

DetectLabels 응답

DetectLabels의 응답은 이미지에서 감지된 레이블의 배열과 각각의 해당 신뢰도 수준입니다.

다음은 DetectLabels의 응답 예제입니다. 아래 샘플 응답에는 다음을 포함하여 GENERAL_LABELS에 대해 반환되는 다양한 속성이 포함되어 있습니다.

  • Name - 탐지된 레이블의 이름. 이 예제에서는 작업을 통해 Mobile Phone 레이블이 붙은 객체를 감지했습니다.

  • Confidence - 각 레이블에는 연결된 신뢰도 수준이 있습니다. 이 예제에서 레이블에 대한 신뢰도는 99.36% 였습니다.

  • Parents - 탐지된 레이블의 상위 레이블입니다. 이 예제에서 Mobile Phone 레이블에는 Phone이라는 상위 레이블이 있습니다.

  • Aliases - 레이블에 있을 수 있는 별칭에 대한 정보. 이 예제에서 Mobile Phone 레이블에는 Cell Phone이라는 별칭이 있을 수 있습니다.

  • Categories - 탐지된 레이블이 속하는 레이블 카테고리입니다. 이 예제에서는 Technology and Computing입니다.

일반적 객체 레이블에 대한 응답은 입력 이미지 상의 레이블 위치에 대한 경계 상자 정보를 포함합니다. 예를 들어 인물 레이블은 두 개의 경계 상자를 포함하는 인스턴스 배열을 갖습니다. 이들은 이미지에서 감지된 두 사람의 위치입니다.

응답에는 IMAGE_PROPERTIES와 관련된 속성도 포함됩니다. IMAGE_PROPERTIES 기능이 제공하는 속성은 다음과 같습니다.

  • Quality - 입력 이미지의 선명도, 밝기 및 대비에 대한 정보로, 0에서 100 사이의 점수가 매겨집니다. 전체 이미지 및 가능한 경우 이미지의 배경 및 전경에 대한 품질이 보고됩니다. 그러나 대비는 전체 이미지에 대해서만 보고되는 반면 선명도 및 밝기는 배경 및 전경에 대해서도 보고됩니다.

  • Dominant Color - 이미지의 주 색상 배열입니다. 각각의 주 색상은 단순화된 색상 이름, CSS 색상 팔레트, RGB 값 및 16진수 코드로 기술됩니다.

  • Foreground - 입력 이미지 전경의 주 색상, 선명도 및 밝기에 대한 정보입니다.

  • Background - 입력 이미지 배경의 주 색상, 선명도 및 밝기에 대한 정보입니다.

GENERAL_LABELS와 IMAGE_PROPERTIES를 입력 파라미터로 함께 사용하면 Amazon Rekognition Image는 경계 상자가 있는 객체의 주 색상도 반환합니다.

LabelModelVersion 필드에는 DetectLabels가 사용하는 감지 모델의 버전 번호가 포함됩니다.

{ "Labels": [ { "Name": "Mobile Phone", "Parents": [ { "Name": "Phone" } ], "Aliases": [ { "Name": "Cell Phone" } ], "Categories": [ { "Name": "Technology and Computing" } ], "Confidence": 99.9364013671875, "Instances": [ { "BoundingBox": { "Width": 0.26779675483703613, "Height": 0.8562285900115967, "Left": 0.3604024350643158, "Top": 0.09245597571134567, } "Confidence": 99.9364013671875, "DominantColors": [ { "Red": 120, "Green": 137, "Blue": 132, "HexCode": "3A7432", "SimplifiedColor": "red", "CssColor": "fuscia", "PixelPercentage": 40.10 } ], } ] } ], "ImageProperties": { "Quality": { "Brightness": 40, "Sharpness": 40, "Contrast": 24, }, "DominantColors": [ { "Red": 120, "Green": 137, "Blue": 132, "HexCode": "3A7432", "SimplifiedColor": "red", "CssColor": "fuscia", "PixelPercentage": 40.10 } ], "Foreground": { "Quality": { "Brightness": 40, "Sharpness": 40, }, "DominantColors": [ { "Red": 200, "Green": 137, "Blue": 132, "HexCode": "3A7432", "CSSColor": "", "SimplifiedColor": "red", "PixelPercentage": 30.70 } ], } "Background": { "Quality": { "Brightness": 40, "Sharpness": 40, }, "DominantColors": [ { "Red": 200, "Green": 137, "Blue": 132, "HexCode": "3A7432", "CSSColor": "", "SimplifiedColor": "Red", "PixelPercentage": 10.20 } ], }, }, "LabelModelVersion": "3.0" }

응답의 DetectLabels 변환

DetectLabels API를 사용할 때는 기본 레이블과 별칭이 모두 동일한 목록에 포함되었던 이전 API 응답 구조를 모방하는 응답 구조가 필요할 수 있습니다.

다음은 현재 API 응답의 예시입니다. DetectLabels

"Labels": [ { "Name": "Mobile Phone", "Confidence": 99.99717712402344, "Instances": [], "Parents": [ { "Name": "Phone" } ], "Aliases": [ { "Name": "Cell Phone" } ] } ]

다음 예제는 DetectLabelsAPI의 이전 응답을 보여줍니다.

"Labels": [ { "Name": "Mobile Phone", "Confidence": 99.99717712402344, "Instances": [], "Parents": [ { "Name": "Phone" } ] }, { "Name": "Cell Phone", "Confidence": 99.99717712402344, "Instances": [], "Parents": [ { "Name": "Phone" } ] }, ]

필요한 경우 현재 응답을 이전 응답 형식을 따르도록 변환할 수 있습니다. 다음 샘플 코드를 사용하여 최신 API 응답을 이전 API 응답 구조로 변환할 수 있습니다.

Python

다음 코드 샘플은 DetectLabels API의 현재 응답을 변환하는 방법을 보여줍니다. 아래 코드 샘플에서 EXAMPLE_INFERENCE_OUTPUT 값을 실행한 작업의 출력으로 바꿀 수 있습니다. DetectLabels

from copy import deepcopy LABEL_KEY = "Labels" ALIASES_KEY = "Aliases" INSTANCE_KEY = "Instances" NAME_KEY = "Name" #Latest API response sample EXAMPLE_INFERENCE_OUTPUT = { "Labels": [ { "Name": "Mobile Phone", "Confidence": 97.530106, "Categories": [ { "Name": "Technology and Computing" } ], "Aliases": [ { "Name": "Cell Phone" } ], "Instances":[ { "BoundingBox":{ "Height":0.1549897, "Width":0.07747964, "Top":0.50858885, "Left":0.00018205095 }, "Confidence":98.401276 } ] }, { "Name": "Urban", "Confidence": 99.99982, "Categories": [ "Colors and Visual Composition" ] } ] } def expand_aliases(inferenceOutputsWithAliases): if LABEL_KEY in inferenceOutputsWithAliases: expandInferenceOutputs = [] for primaryLabelDict in inferenceOutputsWithAliases[LABEL_KEY]: if ALIASES_KEY in primaryLabelDict: for alias in primaryLabelDict[ALIASES_KEY]: aliasLabelDict = deepcopy(primaryLabelDict) aliasLabelDict[NAME_KEY] = alias[NAME_KEY] del aliasLabelDict[ALIASES_KEY] if INSTANCE_KEY in aliasLabelDict: del aliasLabelDict[INSTANCE_KEY] expandInferenceOutputs.append(aliasLabelDict) inferenceOutputsWithAliases[LABEL_KEY].extend(expandInferenceOutputs) return inferenceOutputsWithAliases if __name__ == "__main__": outputWithExpandAliases = expand_aliases(EXAMPLE_INFERENCE_OUTPUT) print(outputWithExpandAliases)

다음은 변환된 응답의 예시입니다.

#Output example after the transformation { "Labels": [ { "Name": "Mobile Phone", "Confidence": 97.530106, "Categories": [ { "Name": "Technology and Computing" } ], "Aliases": [ { "Name": "Cell Phone" } ], "Instances":[ { "BoundingBox":{ "Height":0.1549897, "Width":0.07747964, "Top":0.50858885, "Left":0.00018205095 }, "Confidence":98.401276 } ] }, { "Name": "Cell Phone", "Confidence": 97.530106, "Categories": [ { "Name": "Technology and Computing" } ], "Instances":[] }, { "Name": "Urban", "Confidence": 99.99982, "Categories": [ "Colors and Visual Composition" ] } ] }