빠른 시작: 이미지 분석

이미지 분석 REST API 또는 클라이언트 라이브러리를 시작하여 기본 이미지 태그 지정 스크립트를 설정합니다. 이미지 분석 서비스는 이미지를 처리하고 시각적 기능에 대한 정보를 반환하기 위한 AI 알고리즘을 제공합니다. 다음 단계에 따라 애플리케이션에 패키지를 설치하고 샘플 코드를 사용해 보세요.

C#용 이미지 분석 클라이언트 라이브러리를 사용하여 콘텐츠 태그용 이미지를 분석하세요. 이 빠른 시작에서는 클라이언트 개체를 사용하여 원격 이미지를 분석하고 결과를 출력하는 AnalyzeImageUrl 메서드를 정의합니다.

참조 설명서 | 라이브러리 소스 코드 | 패키지(NuGet) | 샘플

로컬 이미지를 분석할 수도 있습니다. ComputerVisionClient 메서드(예: AnalyzeImageInStreamAsync)를 참조하세요. 또는 로컬 이미지와 관련된 시나리오는 GitHub의 샘플 코드를 참조하세요.

분석 API는 이미지 태그 생성 외에도 다양한 작업을 수행할 수 있습니다. 사용 가능한 모든 기능을 보여 주는 예제는 이미지 분석 방법 가이드를 참조하세요.

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • Visual Studio IDE 또는 현재 버전의 .NET Core.
  • Azure 구독을 만든 후에는 Azure Portal에서 Computer Vision 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 Azure AI 비전 서비스에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
    • 평가판 가격 책정 계층(F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

환경 변수 만들기

이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동을 선택합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. VISION_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. VISION_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다.

이미지 분석

  1. 새 C# 애플리케이션을 만듭니다.

    Visual Studio를 사용하여 새 .NET Core 애플리케이션을 만듭니다.

    클라이언트 라이브러리 설치

    새 프로젝트가 만들어지면 솔루션 탐색기에서 마우스 오른쪽 단추로 프로젝트 솔루션을 클릭하고, NuGet 패키지 관리를 선택하여 클라이언트 라이브러리를 설치합니다. 열리는 패키지 관리자에서 찾아보기를 선택하고, 시험판 포함을 선택하고, Microsoft.Azure.CognitiveServices.Vision.ComputerVision를 검색합니다. 7.0.0 버전, 설치를 차례로 선택합니다.

  2. 선호하는 편집기 또는 IDE에서 프로젝트 디렉터리의 Program.cs 파일을 엽니다. 다음 코드를 붙여넣습니다.

    using System;
    using System.Collections.Generic;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
    using System.Threading.Tasks;
    using System.IO;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Threading;
    using System.Linq;
    
    namespace ComputerVisionQuickstart
    {
        class Program
        {
            // Add your Computer Vision key and endpoint
            static string key = Environment.GetEnvironmentVariable("VISION_KEY");
            static string endpoint = Environment.GetEnvironmentVariable("VISION_ENDPOINT");
    
            // URL image used for analyzing an image (image of puppy)
            private const string ANALYZE_URL_IMAGE = "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png";
    
            static void Main(string[] args)
            {
                Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
                Console.WriteLine();
    
                // Create a client
                ComputerVisionClient client = Authenticate(endpoint, key);
    
                // Analyze an image to get features and other properties.
                AnalyzeImageUrl(client, ANALYZE_URL_IMAGE).Wait();
            }
    
            /*
             * AUTHENTICATE
             * Creates a Computer Vision client used by each example.
             */
            public static ComputerVisionClient Authenticate(string endpoint, string key)
            {
                ComputerVisionClient client =
                  new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
                  { Endpoint = endpoint };
                return client;
            }
           
            public static async Task AnalyzeImageUrl(ComputerVisionClient client, string imageUrl)
            {
                Console.WriteLine("----------------------------------------------------------");
                Console.WriteLine("ANALYZE IMAGE - URL");
                Console.WriteLine();
    
                // Creating a list that defines the features to be extracted from the image. 
    
                List<VisualFeatureTypes?> features = new List<VisualFeatureTypes?>()
                {
                    VisualFeatureTypes.Tags
                };
    
                Console.WriteLine($"Analyzing the image {Path.GetFileName(imageUrl)}...");
                Console.WriteLine();
                // Analyze the URL image 
                ImageAnalysis results = await client.AnalyzeImageAsync(imageUrl, visualFeatures: features);
    
                // Image tags and their confidence score
                Console.WriteLine("Tags:");
                foreach (var tag in results.Tags)
                {
                    Console.WriteLine($"{tag.Name} {tag.Confidence}");
                }
                Console.WriteLine();
            }
        }
    }
    

    Important

    완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 보안 문서를 참조하세요.

  3. 애플리케이션 실행

    IDE 창의 위쪽에서 디버그 단추를 클릭하여 애플리케이션을 실행합니다.


출력

----------------------------------------------------------
ANALYZE IMAGE - URL

Analyzing the image sample16.png...

Tags:
grass 0.9957543611526489
dog 0.9939157962799072
mammal 0.9928356409072876
animal 0.9918001890182495
dog breed 0.9890419244766235
pet 0.974603533744812
outdoor 0.969241738319397
companion dog 0.906731367111206
small greek domestic dog 0.8965123891830444
golden retriever 0.8877675533294678
labrador retriever 0.8746421337127686
puppy 0.872604250907898
ancient dog breeds 0.8508287668228149
field 0.8017748594284058
retriever 0.6837497353553772
brown 0.6581960916519165

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계

이 빠른 시작에서는 Image Analysis 클라이언트 라이브러리를 설치하고 기본 이미지 분석 호출을 수행하는 방법을 알아보았습니다. 다음으로, Analyze API 기능에 대해 자세히 알아보세요.

Python용 이미지 분석 클라이언트 라이브러리를 사용하여 콘텐츠 태그용 원격 이미지를 분석하세요.

로컬 이미지를 분석할 수도 있습니다. ComputerVisionClientOperationsMixin 메서드(예: analyze_image_in_stream)를 참조하세요. 또는 로컬 이미지와 관련된 시나리오는 GitHub의 샘플 코드를 참조하세요.

분석 API는 이미지 태그 생성 외에도 다양한 작업을 수행할 수 있습니다. 사용 가능한 모든 기능을 보여 주는 예제는 이미지 분석 방법 가이드를 참조하세요.

참조 설명서 | 라이브러리 소스 코드 | 패키지(PiPy) | 샘플

필수 조건

  • Azure 구독 - 체험 구독 만들기

  • Python 3.x

    • Python 설치에 pip가 포함되어야 합니다. 명령줄에서 pip --version을 실행하여 pip가 설치되어 있는지 확인할 수 있습니다. 최신 버전의 Python을 설치하여 pip를 받으세요.
  • Azure 구독이 있으면 Azure portal에서 Vision 리소스를 생성하여 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.

    • 애플리케이션을 Azure AI 비전 서비스에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
    • 평가판 가격 책정 계층(F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

환경 변수 만들기

이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동을 선택합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. VISION_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. VISION_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다.

이미지 분석

  1. 클라이언트 라이브러리를 설치합니다.

    다음을 사용하여 클라이언트 라이브러리를 설치할 수 있습니다.

    pip install --upgrade azure-cognitiveservices-vision-computervision
    

    또한 베개 라이브러리를 설치합니다.

    pip install pillow
    
  2. 새 Python 애플리케이션을 만듭니다.

    예를 들어 새 Python 파일(quickstart-file.py)을 만듭니다.

  3. 텍스트 편집기 또는 IDE에서 quickstart-file.py 파일을 열고 다음 코드를 붙여넣습니다.

    from azure.cognitiveservices.vision.computervision import ComputerVisionClient
    from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
    from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
    from msrest.authentication import CognitiveServicesCredentials
    
    from array import array
    import os
    from PIL import Image
    import sys
    import time
    
    '''
    Authenticate
    Authenticates your credentials and creates a client.
    '''
    subscription_key = os.environ["VISION_KEY"]
    endpoint = os.environ["VISION_ENDPOINT"]
    
    computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
    '''
    END - Authenticate
    '''
    
    '''
    Quickstart variables
    These variables are shared by several examples
    '''
    # Images used for the examples: Describe an image, Categorize an image, Tag an image, 
    # Detect faces, Detect adult or racy content, Detect the color scheme, 
    # Detect domain-specific content, Detect image types, Detect objects
    images_folder = os.path.join (os.path.dirname(os.path.abspath(__file__)), "images")
    remote_image_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg"
    '''
    END - Quickstart variables
    '''
    
    
    '''
    Tag an Image - remote
    This example returns a tag (key word) for each thing in the image.
    '''
    print("===== Tag an image - remote =====")
    # Call API with remote image
    tags_result_remote = computervision_client.tag_image(remote_image_url )
    
    # Print results with confidence score
    print("Tags in the remote image: ")
    if (len(tags_result_remote.tags) == 0):
        print("No tags detected.")
    else:
        for tag in tags_result_remote.tags:
            print("'{}' with confidence {:.2f}%".format(tag.name, tag.confidence * 100))
    print()
    '''
    END - Tag an Image - remote
    '''
    print("End of Computer Vision quickstart.")
    
  4. quickstart 파일의 python 명령을 사용하여 애플리케이션을 실행합니다.

    python quickstart-file.py
    

출력

===== Tag an image - remote =====
Tags in the remote image:
'outdoor' with confidence 99.00%
'building' with confidence 98.81%
'sky' with confidence 98.21%
'stadium' with confidence 98.17%
'ancient rome' with confidence 96.16%
'ruins' with confidence 95.04%
'amphitheatre' with confidence 93.99%
'ancient roman architecture' with confidence 92.65%
'historic site' with confidence 89.55%
'ancient history' with confidence 89.54%
'history' with confidence 86.72%
'archaeological site' with confidence 84.41%
'travel' with confidence 65.85%
'large' with confidence 61.02%
'city' with confidence 56.57%

End of Azure AI Vision quickstart.

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계

이 빠른 시작에서는 Image Analysis 클라이언트 라이브러리를 설치하고 기본 이미지 분석 호출을 수행하는 방법을 알아보았습니다. 다음으로, Analyze API 기능에 대해 자세히 알아보세요.

이미지 분석 클라이언트 라이브러리를 사용하여 태그, 텍스트 설명, 얼굴, 성인 콘텐츠 등에 대한 원격 이미지를 분석합니다.

로컬 이미지를 분석할 수도 있습니다. ComputerVision 메서드(예: AnalyzeImage)를 참조하세요. 또는 로컬 이미지와 관련된 시나리오는 GitHub의 샘플 코드를 참조하세요.

분석 API는 이미지 태그 생성 외에도 다양한 작업을 수행할 수 있습니다. 사용 가능한 모든 기능을 보여 주는 예제는 이미지 분석 방법 가이드를 참조하세요.

참조 설명서 | 라이브러리 소스 코드 |아티팩트(Maven) | 샘플

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • JDK(Java Development Kit)의 현재 버전
  • Gradle 빌드 도구 또는 다른 종속성 관리자
  • Azure 구독이 있으면 Azure portal에서 Vision 리소스를 생성하여 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 Azure AI 비전 서비스에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
    • 평가판 가격 책정 계층(F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

환경 변수 만들기

이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동을 선택합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. VISION_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. VISION_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다.

이미지 분석

  1. 새 Gradle 프로젝트를 만듭니다.

    콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

    mkdir myapp && cd myapp
    

    작업 디렉터리에서 gradle init 명령을 실행합니다. 이 명령은 build.gradle.kts를 포함하여 런타임에 애플리케이션을 만들고 구성하는 데 사용되는 Gradle용 필수 빌드 파일을 만듭니다.

    gradle init --type basic
    

    DSL을 선택하라는 메시지가 표시되면 Kotlin을 선택합니다.

  2. 클라이언트 라이브러리를 설치합니다.

    이 빠른 시작에서는 Gradle 종속성 관리자를 사용합니다. 다른 종속성 관리자에 대한 클라이언트 라이브러리 및 정보는 Maven 중앙 리포지토리에서 찾을 수 있습니다.

    build.gradle.kts를 찾고, 원하는 IDE 또는 텍스트 편집기에서 엽니다. 그런 다음, 다음 빌드 구성을 복사합니다. 이 구성은 진입점이 ImageAnalysisQuickstart 클래스 인 Java 애플리케이션으로 프로젝트를 정의합니다. Azure AI Vision 라이브러리를 가져옵니다.

    plugins {
        java
        application
    }
    application { 
        mainClass.set("ImageAnalysisQuickstart")
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        implementation(group = "com.microsoft.azure.cognitiveservices", name = "azure-cognitiveservices-computervision", version = "1.0.9-beta")
    }
    
  3. Java 파일을 만듭니다.

    작업 디렉터리에서 다음 명령을 실행하여 프로젝트 원본 폴더를 만듭니다.

    mkdir -p src/main/java
    

    새 폴더로 이동하여 ImageAnalysisQuickstart.java 파일을 만듭니다.

  4. 선호하는 편집기 또는 IDE에서 ImageAnalysisQuickstart.java 파일을 열고 다음 코드를 붙여넣습니다.

    import com.microsoft.azure.cognitiveservices.vision.computervision.*;
    import com.microsoft.azure.cognitiveservices.vision.computervision.implementation.ComputerVisionImpl;
    import com.microsoft.azure.cognitiveservices.vision.computervision.models.*;
    
    import java.io.*;
    import java.nio.file.Files;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    public class ImageAnalysisQuickstart {
    
        // Use environment variables
        static String key = System.getenv("VISION_KEY");
        static String endpoint = System.getenv("VISION_ENDPOINT");
    
        public static void main(String[] args) {
            
            System.out.println("\nAzure Cognitive Services Computer Vision - Java Quickstart Sample");
    
            // Create an authenticated Computer Vision client.
            ComputerVisionClient compVisClient = Authenticate(key, endpoint); 
    
            // Analyze local and remote images
            AnalyzeRemoteImage(compVisClient);
    
        }
    
        public static ComputerVisionClient Authenticate(String key, String endpoint){
            return ComputerVisionManager.authenticate(key).withEndpoint(endpoint);
        }
    
    
        public static void AnalyzeRemoteImage(ComputerVisionClient compVisClient) {
            /*
             * Analyze an image from a URL:
             *
             * Set a string variable equal to the path of a remote image.
             */
            String pathToRemoteImage = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/faces.jpg";
    
            // This list defines the features to be extracted from the image.
            List<VisualFeatureTypes> featuresToExtractFromRemoteImage = new ArrayList<>();
            featuresToExtractFromRemoteImage.add(VisualFeatureTypes.TAGS);
    
            System.out.println("\n\nAnalyzing an image from a URL ...");
    
            try {
                // Call the Computer Vision service and tell it to analyze the loaded image.
                ImageAnalysis analysis = compVisClient.computerVision().analyzeImage().withUrl(pathToRemoteImage)
                        .withVisualFeatures(featuresToExtractFromRemoteImage).execute();
    
    
                // Display image tags and confidence values.
                System.out.println("\nTags: ");
                for (ImageTag tag : analysis.tags()) {
                    System.out.printf("\'%s\' with confidence %f\n", tag.name(), tag.confidence());
                }
            }
    
            catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        // END - Analyze an image from a URL.
    
    }
    
  5. 프로젝트 루트 폴더로 돌아가서 다음을 사용하여 앱을 빌드합니다.

    gradle build
    

    그런 다음, gradle run 명령을 사용하여 실행합니다.

    gradle run
    

출력

Azure AI Vision - Java Quickstart Sample

Analyzing an image from a URL ...

Tags:
'person' with confidence 0.998895
'human face' with confidence 0.997437
'smile' with confidence 0.991973
'outdoor' with confidence 0.985962
'happy' with confidence 0.969785
'clothing' with confidence 0.961570
'friendship' with confidence 0.946441
'tree' with confidence 0.917331
'female person' with confidence 0.890976
'girl' with confidence 0.888741
'social group' with confidence 0.872044
'posing' with confidence 0.865493
'adolescent' with confidence 0.857371
'love' with confidence 0.852553
'laugh' with confidence 0.850097
'people' with confidence 0.849922
'lady' with confidence 0.844540
'woman' with confidence 0.818172
'group' with confidence 0.792975
'wedding' with confidence 0.615252
'dress' with confidence 0.517169

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계

이 빠른 시작에서는 Image Analysis 클라이언트 라이브러리를 설치하고 기본 이미지 분석 호출을 수행하는 방법을 알아보았습니다. 다음으로, Analyze API 기능에 대해 자세히 알아보세요.

JavaScript용 이미지 분석 클라이언트 라이브러리를 사용하여 콘텐츠 태그용 원격 이미지를 분석하세요.

로컬 이미지를 분석할 수도 있습니다. ComputerVisionClient 메서드(예: describeImageInStream)를 참조하세요. 또는 로컬 이미지와 관련된 시나리오는 GitHub의 샘플 코드를 참조하세요.

분석 API는 이미지 태그 생성 외에도 다양한 작업을 수행할 수 있습니다. 사용 가능한 모든 기능을 보여 주는 예제는 이미지 분석 방법 가이드를 참조하세요.

참조 설명서 | 라이브러리 소스 코드 | 패키지(npm) | 샘플

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • 현재 버전의 Node.js
  • Azure 구독이 있으면 Azure portal에서 Vision 리소스를 생성하여 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 Azure AI 비전 서비스에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
    • 평가판 가격 책정 계층(F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

환경 변수 만들기

이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.

Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동을 선택합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.

코드에 키를 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Azure AI 서비스 보안 문서를 참조하세요.

키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.

  1. VISION_KEY 환경 변수를 설정하려면 your-key를 리소스에 대한 키 중 하나로 바꿉니다.
  2. VISION_ENDPOINT 환경 변수를 설정하려면 your-endpoint를 리소스에 대한 엔드포인트로 바꿉니다.
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다.

이미지 분석

  1. 새 Node.js 애플리케이션 만들기

    콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

    mkdir myapp && cd myapp
    

    package.json 파일을 사용하여 노드 애플리케이션을 만들려면 npm init 명령을 실행합니다.

    npm init
    

    클라이언트 라이브러리 설치

    ms-rest-azure@azure/cognitiveservices-computervision npm 패키지를 설치합니다.

    npm install @azure/cognitiveservices-computervision
    

    또한 비동기 모듈을 설치합니다.

    npm install async
    

    종속성이 있는 앱의 package.json 파일이 업데이트됩니다.

    이름이 index.js인 새 파일을 만듭니다.

  2. 텍스트 편집기에서 index.js 파일을 열고 다음 코드를 붙여 넣습니다.

    'use strict';
    
    const async = require('async');
    const fs = require('fs');
    const https = require('https');
    const path = require("path");
    const createReadStream = require('fs').createReadStream
    const sleep = require('util').promisify(setTimeout);
    const ComputerVisionClient = require('@azure/cognitiveservices-computervision').ComputerVisionClient;
    const ApiKeyCredentials = require('@azure/ms-rest-js').ApiKeyCredentials;
    
    /**
     * AUTHENTICATE
     * This single client is used for all examples.
     */
    const key = process.env.VISION_KEY;
    const endpoint = process.env.VISION_ENDPOINT;
    
    
    const computerVisionClient = new ComputerVisionClient(
      new ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': key } }), endpoint);
    /**
     * END - Authenticate
     */
    
    
    function computerVision() {
      async.series([
        async function () {
    
          /**
           * DETECT TAGS  
           * Detects tags for an image, which returns:
           *     all objects in image and confidence score.
           */
          console.log('-------------------------------------------------');
          console.log('DETECT TAGS');
          console.log();
    
          // Image of different kind of dog.
          const tagsURL = 'https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png';
    
          // Analyze URL image
          console.log('Analyzing tags in image...', tagsURL.split('/').pop());
          const tags = (await computerVisionClient.analyzeImage(tagsURL, { visualFeatures: ['Tags'] })).tags;
          console.log(`Tags: ${formatTags(tags)}`);
    
          // Format tags for display
          function formatTags(tags) {
            return tags.map(tag => (`${tag.name} (${tag.confidence.toFixed(2)})`)).join(', ');
          }
          /**
           * END - Detect Tags
           */
          console.log();
          console.log('-------------------------------------------------');
          console.log('End of quickstart.');
    
        },
        function () {
          return new Promise((resolve) => {
            resolve();
          })
        }
      ], (err) => {
        throw (err);
      });
    }
    
    computerVision();
    
  3. quickstart 파일의 node 명령을 사용하여 애플리케이션을 실행합니다.

    node index.js
    

출력

-------------------------------------------------
DETECT TAGS

Analyzing tags in image... sample16.png
Tags: grass (1.00), dog (0.99), mammal (0.99), animal (0.99), dog breed (0.99), pet (0.97), outdoor (0.97), companion dog (0.91), small greek domestic dog (0.90), golden retriever (0.89), labrador retriever (0.87), puppy (0.87), ancient dog breeds (0.85), field (0.80), retriever (0.68), brown (0.66)

-------------------------------------------------
End of quickstart.

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.

다음 단계

이 빠른 시작에서는 Image Analysis 클라이언트 라이브러리를 설치하고 기본 이미지 분석 호출을 수행하는 방법을 알아보았습니다. 다음으로, Analyze API 기능에 대해 자세히 알아보세요.

이미지 분석 REST API를 사용하여 태그에 대한 이미지를 분석합니다.

분석 API는 이미지 태그 생성 외에도 다양한 작업을 수행할 수 있습니다. 사용 가능한 모든 기능을 보여 주는 예제는 이미지 분석 방법 가이드를 참조하세요.

참고 항목

이 빠른 시작에서는 cURL 명령을 사용하여 REST API를 호출합니다. 프로그래밍 언어를 사용하여 REST API를 호출할 수도 있습니다. C#, Python, JavaJavaScript의 예는 GitHub 샘플을 참조하세요.

필수 조건

  • Azure 구독 - 체험 구독 만들기
  • Azure 구독이 있으면 Azure portal에서 Vision 리소스를 생성하여 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.
    • 애플리케이션을 Azure AI 비전 서비스에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다.
    • 평가판 가격 책정 계층(F0)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • cURL 설치

이미지 분석

다양한 시각적 기능을 위한 이미지를 분석하려면 다음 단계를 수행합니다.

  1. 다음 명령을 텍스트 편집기에 복사합니다.

    curl.exe -H "Ocp-Apim-Subscription-Key: <subscriptionKey>" -H "Content-Type: application/json" "https://westcentralus.api.cognitive.microsoft.com/vision/v3.2/analyze?visualFeatures=Tags" -d "{'url':'https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png'}"
    
  2. 필요한 경우 명령에서 다음 내용을 변경합니다.

    1. <subscriptionKey> 값을 키로 바꿉니다.
    2. 요청 URL(westcentralus)의 첫 번째 부분을 고유한 엔드포인트 URL의 텍스트로 바꿉니다.

      참고 항목

      2019년 7월 1일 이후에 만들어진 새 리소스는 사용자 지정 하위 도메인 이름을 사용합니다. 자세한 내용과 지역 엔드포인트의 전체 목록은 Azure AI 서비스에 대한 사용자 지정 하위 도메인 이름을 참조하세요.

    3. 필요한 경우 요청 본문의 이미지 URL(https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png)을 분석할 다른 이미지의 URL로 변경합니다.
  3. 명령 프롬프트 창을 엽니다.

  4. 텍스트 편집기에서 편집한 curl 명령을 명령 프롬프트 창에 붙여넣은 다음 명령을 실행합니다.

응답 검사

성공적인 응답이 JSON을 통해 반환됩니다. 애플리케이션 예제는 다음 예제와 유사하게 명령 프롬프트 창에서 성공한 응답을 구문 분석하고 표시합니다.

{{
   "tags":[
      {
         "name":"text",
         "confidence":0.9992657899856567
      },
      {
         "name":"post-it note",
         "confidence":0.9879657626152039
      },
      {
         "name":"handwriting",
         "confidence":0.9730165004730225
      },
      {
         "name":"rectangle",
         "confidence":0.8658561706542969
      },
      {
         "name":"paper product",
         "confidence":0.8561884760856628
      },
      {
         "name":"purple",
         "confidence":0.5961999297142029
      }
   ],
   "requestId":"2788adfc-8cfb-43a5-8fd6-b3a9ced35db2",
   "metadata":{
      "height":945,
      "width":1000,
      "format":"Jpeg"
   },
   "modelVersion":"2021-05-01"
}

다음 단계

이 빠른 시작에서는 REST API를 사용하여 기본 이미지 분석을 호출하는 방법을 배웠습니다. 다음으로, Analyze API 기능에 대해 자세히 알아보세요.