Edge 컨테이너 가이드

AutoML Vision Edge 모델을 만들고 Google Cloud Storage 버킷으로 내보낸 후에 RESTful 서비스를 AutoML Vision Edge 모델TF Serving Docker 이미지와 함께 사용할 수 있습니다.

빌드 대상

Docker 컨테이너를 사용하면 다양한 기기에서 손쉽게 Edge 모델을 배포할 수 있습니다. 원하는 언어로 컨테이너에서 REST API를 호출하여 Edge 모델을 실행할 수 있으며, 종속 항목을 설치하거나 적절한 TensorFlow 버전을 찾을 필요가 없다는 추가적인 이점도 있습니다.

이 가이드에서는 Docker 컨테이너를 사용하는 기기에서 Edge 모델을 실행하는 과정을 단계별로 보여줍니다.

구체적으로 이 가이드는 세 가지 단계를 안내합니다.

  1. 사전 빌드된 컨테이너 가져오기
  2. Edge 모델을 포함하는 컨테이너를 실행하여 REST API 시작
  3. 예측 실행

대부분의 기기는 CPU만 있지만 일부 기기는 더 빠른 예측을 위해 GPU가 있을 수 있습니다. 따라서 사전 빌드된 CPU 및 GPU 컨테이너 모두에 대한 가이드를 제공합니다.

목표

입문 내용에서는 코드 샘플을 사용해 다음을 수행하는 전반적인 과정을 둘러봅니다.

  1. Docker 컨테이너를 가져옵니다.
  2. Edge 모델을 포함하는 Docker 컨테이너를 사용하여 REST API를 시작합니다.
  3. 예측을 실행하여 분석된 결과를 얻습니다.

시작하기 전에

이 가이드를 완료하려면 다음 조건을 충족해야 합니다.

  1. 내보낼 수 있는 Edge 모델을 학습시킵니다. Edge 기기 모델 빠른 시작을 따라 Edge 모델을 학습시킵니다.
  2. AutoML Vision Edge 모델을 내보냅니다. 이 모델은 컨테이너와 함께 REST API로 제공됩니다.
  3. Docker를 설치합니다. Docker 컨테이너를 실행하기 위한 필수 소프트웨어입니다.
  4. (선택사항) NVIDIA Docker 및 드라이버를 설치합니다. 이 작업은 GPU가 있는 기기를 사용하고 있으며 예측 속도를 높이고 싶은 경우의 선택적 단계입니다.
  5. 테스트 이미지를 준비합니다. 이 이미지는 분석된 결과를 얻기 위한 요청으로 전송됩니다.

모델을 내보내고 필수 소프트웨어를 설치하기 위한 세부정보가 다음 섹션에 나와 있습니다.

AutoML Vision Edge 모델 내보내기

Edge 모델을 학습시킨 후에 다른 기기로 내보낼 수 있습니다.

컨테이너는 TensorFlow 모델을 지원하며, 이 모델은 내보낼 때 saved_model.pb로 명명됩니다.

컨테이너의 AutoML Vision Edge 모델을 내보내려면 UI에서 컨테이너 탭을 선택한 다음 모델을 Google Cloud Storage의 ${YOUR_MODEL_PATH}로 내보냅니다. 이렇게 내보낸 모델이 나중에 컨테이너와 함께 REST API로 제공됩니다.

컨테이너 옵션으로 내보내기

내보낸 모델을 로컬로 다운로드하려면 다음 명령어를 실행합니다.

각 항목의 의미는 다음과 같습니다.

  • ${YOUR_MODEL_PATH} - Google Cloud Storage에서의 모델 위치입니다(예: gs://my-bucket-vcm/models/edge/ICN4245971651915048908/2020-01-20_01-27-14-064_tf-saved-model/).
  • ${YOUR_LOCAL_MODEL_PATH} - 모델을 다운로드할 로컬 경로입니다(예: /tmp).
gsutil cp ${YOUR_MODEL_PATH} ${YOUR_LOCAL_MODEL_PATH}/saved_model.pb

Docker 설치

Docker는 컨테이너 내에 애플리케이션을 배포하고 실행하는 데 사용되는 소프트웨어입니다.

Docker Community Edition(CE)을 시스템에 설치합니다. 이를 사용하여 Edge 모델을 REST API로 제공합니다.

NVIDIA 드라이버 및 NVIDIA Docker 설치(선택사항 - GPU만 해당)

일부 기기에는 더 빠른 예측을 제공하기 위해 GPU가 있습니다. NVIDIA GPU를 지원하는 GPU Docker 컨테이너가 제공됩니다.

GPU 컨테이너를 실행하려면 시스템에 NVIDIA 드라이버NVIDIA Docker를 설치해야 합니다.

CPU를 사용하여 모델 추론 실행

이 섹션에서는 CPU 컨테이너를 사용하여 모델 추론을 실행하는 방법에 대한 단계별 안내를 제공합니다. 설치된 Docker를 사용하여 CPU 컨테이너를 가져오고 실행한 후 내보낸 Edge 모델을 REST API로 제공한 다음 테스트 이미지의 요청을 REST API에 보내 분석된 결과를 얻습니다.

Docker 이미지 가져오기

먼저, Docker를 사용하여 사전 빌드된 CPU 컨테이너를 가져옵니다. 사전 빌드된 CPU 컨테이너에는 내보낸 Edge 모델을 제공하기 위한 전체 환경이 이미 있습니다. 하지만 여기에는 아직 Edge 모델이 포함되어 있지 않습니다.

사전 빌드된 CPU 컨테이너는 Google Container Registry에 저장됩니다. 컨테이너를 요청하기 전에 Google Container Registry에서 컨테이너 위치의 환경 변수를 설정합니다.

export CPU_DOCKER_GCS_PATH=gcr.io/cloud-devrel-public-resources/gcloud-container-1.14.0:latest

Container Registry 경로의 환경 변수를 설정한 후에는 다음 명령줄을 실행하여 CPU 컨테이너를 가져옵니다.

sudo docker pull ${CPU_DOCKER_GCS_PATH}

Docker 컨테이너 실행

기존 컨테이너를 가져온 후 이 CPU 컨테이너를 실행하여 Edge 모델 추론을 REST API와 함께 제공합니다.

CPU 컨테이너를 시작하기 전에 시스템 변수를 설정해야 합니다.

  • ${CONTAINER_NAME} - - 실행될 때 컨테이너 이름을 나타내는 문자열입니다(예: CONTAINER_NAME=automl_high_accuracy_model_cpu).
  • ${PORT} - 나중에 기기에서 REST API 호출을 받아들이는 포트를 나타내는 숫자입니다(예: PORT=8501).

변수를 설정한 후에 명령줄에서 Docker를 실행하여 Edge 모델 추론을 REST API와 함께 제공합니다.

sudo docker run --rm --name ${CONTAINER_NAME} -p ${PORT}:8501 -v ${YOUR_MODEL_PATH}:/tmp/mounted_model/0001 -t ${CPU_DOCKER_GCS_PATH}

컨테이너가 실행되면 http://localhost:${PORT}/v1/models/default:predict에서 REST API를 제공할 준비가 된 것입니다. 다음 섹션에서는 이 위치에 예측 요청을 보내는 방법을 자세히 설명합니다.

예측 요청 보내기

이제 컨테이너가 성공적으로 실행되므로, 테스트 이미지에서 예측 요청을 REST API로 전송할 수 있습니다.

명령줄

명령줄 요청 본문에는 제공된 이미지 식별을 위한 key 문자열 및 base64로 인코딩된 image_bytes가 포함됩니다. 이미지 인코딩에 대한 자세한 내용은 Base64 인코딩 주제를 참조하세요. 요청 JSON 파일의 형식은 다음과 같습니다.

/tmp/request.json
{
  "instances":
  [
    {
      "image_bytes":
      {
        "b64": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "key": "your-chosen-image-key"
    }
  ]
}

로컬 JSON 요청 파일을 만든 후에는 예측 요청을 전송할 수 있습니다.

다음 명령어를 사용하여 예측 요청을 전송합니다.

curl -X POST -d  @/tmp/request.json http://localhost:${PORT}/v1/models/default:predict
응답

다음과 비슷한 출력이 표시됩니다.

{
  "predictions": [
    {
      "detection_multiclass_scores": [
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00240907, 0.00173151, 0.00134027, 0.00287125, 0.00130472, 0.00242674],
        [0.00227344, 0.00124374, 0.00147101, 0.00377446, 0.000997812, 0.0029003],
        [0.00132903, 0.000844955, 0.000537515, 0.00474253, 0.000508994, 0.00130466],
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00110534, 0.000204086, 0.000247836, 0.000553966, 0.000193745, 0.000359297],
        [0.00112912, 0.000443578, 0.000779897, 0.00203282, 0.00069508, 0.00188044],
        [0.00271052, 0.00163364, 0.00138229, 0.00314173, 0.00164038, 0.00332257],
        [0.00227907, 0.00217116, 0.00190553, 0.00321552, 0.00233933, 0.0053153],
        [0.00271052, 0.00163364, 0.00138229, 0.00314173, 0.00164038, 0.00332257],
        [0.00250274, 0.000489146, 0.000879943, 0.00355569, 0.00129834, 0.00355521],
        [0.00227344, 0.00124374, 0.00147101, 0.00377446, 0.000997812, 0.0029003],
        [0.00241205, 0.000786602, 0.000896335, 0.00187016, 0.00106838, 0.00193021],
        [0.00132069, 0.00173706, 0.00389183, 0.00536761, 0.00387135, 0.00752795],
        [0.0011555, 0.00025022, 0.000221372, 0.000536889, 0.000187278, 0.000306398],
        [0.00150242, 0.000391901, 0.00061205, 0.00158429, 0.000300348, 0.000788659],
        [0.00181362, 0.000169843, 0.000458032, 0.000690967, 0.000296295, 0.000412017],
        [0.00101465, 0.000184, 0.000148445, 0.00068599, 0.000111818, 0.000290155],
        [0.00128508, 0.00108775, 0.00298983, 0.00174832, 0.00143594, 0.00285548],
        [0.00137702, 0.000480384, 0.000831485, 0.000920624, 0.000405788, 0.000735044],
        [0.00103369, 0.00152704, 0.000892937, 0.00269693, 0.00214335, 0.00588191],
        [0.0013324, 0.000647604, 0.00293729, 0.00156629, 0.00195253, 0.00239435],
        [0.0022423, 0.00141206, 0.0012649, 0.00450748, 0.00138766, 0.00249887],
        [0.00125939, 0.0002428, 0.000370741, 0.000917137, 0.00024578, 0.000412881],
        [0.00135186, 0.000139147, 0.000525713, 0.00103053, 0.000366062, 0.000844955],
        [0.00127548, 0.000989318, 0.00256863, 0.00162545, 0.00311682, 0.00439551],
        [0.00112912, 0.000443578, 0.000779897, 0.00203282, 0.00069508, 0.00188044],
        [0.00114602, 0.00107747, 0.00145, 0.00320849, 0.00211915, 0.00331426],
        [0.00148326, 0.00059548, 0.00431389, 0.00164703, 0.00311947, 0.00268343],
        [0.00154313, 0.000925034, 0.00770769, 0.00252789, 0.00489518, 0.00352332],
        [0.00135094, 0.00042069, 0.00088492, 0.000987828, 0.000755847, 0.00144881],
        [0.0015994, 0.000540197, 0.00163212, 0.00140327, 0.00114474, 0.0026556],
        [0.00150502, 0.000138223, 0.000343591, 0.000529736, 0.000173837, 0.000381887],
        [0.00127372, 0.00066787, 0.00149515, 0.00272799, 0.00110033, 0.00370145],
        [0.00144503, 0.000365585, 0.00318581, 0.00126475, 0.00212631, 0.00204816],
        [0.00132069, 0.00173706, 0.00389183, 0.00536761, 0.00387135, 0.00752795],
        [0.00198057, 0.000307024, 0.000573188, 0.00147268, 0.000757724, 0.0017142],
        [0.00157535, 0.000590324, 0.00190055, 0.00170627, 0.00138417, 0.00246152],
        [0.00177169, 0.000364572, 0.00183856, 0.000767767, 0.00121492, 0.000916481]
      ],
      "detection_classes":
        [5.0, 2.0, 5.0, 5.0, 5.0, 4.0, 5.0, 5.0, 4.0, 4.0, 2.0, 4.0, 4.0, 4.0, 5.0, 4.0, 5.0,
        5.0, 4.0, 5.0, 5.0, 4.0, 5.0, 2.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 4.0, 4.0,
        5.0, 4.0, 4.0, 5.0, 5.0],
      "num_detections": 40.0,
      "image_info": [320, 320, 1, 0, 320, 320],
      "detection_boxes": [
        [0.457792, 0.0, 0.639324, 0.180828],
        [0.101111, 0.0, 0.89904, 0.995376],
        [0.447649, 0.314644, 0.548206, 0.432875],
        [0.250341, 0.733411, 0.3419, 0.847185],
        [0.573936, 0.0933048, 0.766472, 0.208054],
        [0.490438, 0.194659, 0.825894, 0.563959],
        [0.619383, 0.57948, 0.758244, 0.694948],
        [0.776185, 0.554518, 0.841549, 0.707129],
        [0.101111, 0.0, 0.89904, 0.995376],
        [0.431243, 0.0917888, 0.850772, 0.617123],
        [0.250883, 0.13572, 0.780518, 0.817881],
        [0.327646, 0.878977, 0.607503, 0.989904],
        [0.573936, 0.0933048, 0.766472, 0.208054],
        [0.37792, 0.460952, 0.566977, 0.618865],
        [0.373325, 0.575019, 0.463646, 0.642949],
        [0.27251, 0.0714827, 0.790764, 0.77176],
        [0.725154, 0.561221, 0.849777, 0.702165],
        [0.37549, 0.558988, 0.460575, 0.626821],
        [0.265563, 0.248368, 0.785451, 0.977509],
        [0.605674, 0.597553, 0.760419, 0.744799],
        [0.400611, 0.327271, 0.487579, 0.424036],
        [0.48632, 0.980808, 0.606008, 0.997468],
        [0.542414, 0.0588853, 0.752879, 0.200775],
        [0.490438, 0.194659, 0.825894, 0.563959],
        [0.368839, 0.115654, 0.741839, 0.587659],
        [0.467101, 0.985155, 0.588853, 0.997708],
        [0.755204, 0.561319, 0.836475, 0.676249],
        [0.409855, 0.302322, 0.773464, 0.587772],
        [0.351938, 0.934163, 0.587043, 0.99954],
        [0.27758, 0.72402, 0.334137, 0.846945],
        [0.29875, 0.601199, 0.381122, 0.679323],
        [0.64637, 0.566566, 0.767553, 0.67331],
        [0.372612, 0.596795, 0.457588, 0.666544],
        [0.438422, 0.989558, 0.578529, 0.998366],
        [0.586531, 0.499894, 0.879711, 0.845526],
        [0.608476, 0.644501, 0.759154, 0.827037],
        [0.352501, 0.477601, 0.710863, 0.948605],
        [0.466184, 0.953443, 0.668056, 0.996681],
        [0.547756, 0.00152373, 0.722814, 0.150687],
        [0.759639, 0.548476, 0.866864, 0.722007]
      ],
      "detection_scores":
        [0.877304, 0.839354, 0.824509, 0.579912, 0.461549, 0.306151, 0.268687, 0.197998, 0.181444,
        0.17856, 0.152705, 0.148958, 0.14726, 0.135506, 0.128483, 0.12234, 0.105697, 0.105665,
        0.0941569, 0.0891062, 0.0845169, 0.0810551, 0.0794339, 0.0784486, 0.0771784, 0.0770716,
        0.075339, 0.0716749, 0.0715761, 0.07108, 0.0705339, 0.0693555, 0.0677402, 0.0644643,
        0.0631491, 0.062369, 0.0619523, 0.060859, 0.0601122, 0.0589799],
      "detection_classes_as_text":
        ["Tomato", "Salad", "Tomato", "Tomato", "Tomato", "Seafood", "Tomato", "Tomato", "Seafood",
        "Seafood", "Salad", "Seafood", "Seafood", "Seafood", "Tomato", "Seafood", "Tomato",
        "Tomato", "Seafood", "Tomato", "Tomato", "Seafood", "Tomato", "Salad", "Seafood",
        "Seafood", "Tomato", "Seafood", "Seafood", "Tomato", "Tomato", "Tomato", "Tomato",
        "Seafood", "Seafood", "Tomato", "Seafood", "Seafood", "Tomato", "Tomato"],
      "key": "1"
    }
  ]
}

Python

AutoML Vision 객체 감지용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Vision 객체 감지 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Vision 객체 감지 Python API 참조 문서를 참조하세요.

AutoML Vision 객체 감지에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import base64
import cv2
import io
import json

import requests

def preprocess_image(image_file_path, max_width, max_height):
    """Preprocesses input images for AutoML Vision Edge models.

    Args:
        image_file_path: Path to a local image for the prediction request.
        max_width: The max width for preprocessed images. The max width is 640
            (1024) for AutoML Vision Image Classfication (Object Detection)
            models.
        max_height: The max width for preprocessed images. The max height is
            480 (1024) for AutoML Vision Image Classfication (Object
            Detetion) models.
    Returns:
        The preprocessed encoded image bytes.
    """
    # cv2 is used to read, resize and encode images.
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 85]
    im = cv2.imread(image_file_path)
    [height, width, _] = im.shape
    if height > max_height or width > max_width:
        ratio = max(height / float(max_width), width / float(max_height))
        new_height = int(height / ratio + 0.5)
        new_width = int(width / ratio + 0.5)
        resized_im = cv2.resize(
            im, (new_width, new_height), interpolation=cv2.INTER_AREA
        )
        _, processed_image = cv2.imencode(".jpg", resized_im, encode_param)
    else:
        _, processed_image = cv2.imencode(".jpg", im, encode_param)
    return base64.b64encode(processed_image).decode("utf-8")

def container_predict(image_file_path, image_key, port_number=8501):
    """Sends a prediction request to TFServing docker container REST API.

    Args:
        image_file_path: Path to a local image for the prediction request.
        image_key: Your chosen string key to identify the given image.
        port_number: The port number on your device to accept REST API calls.
    Returns:
        The response of the prediction request.
    """
    # AutoML Vision Edge models will preprocess the input images.
    # The max width and height for AutoML Vision Image Classification and
    # Object Detection models are 640*480 and 1024*1024 separately. The
    # example here is for Image Classification models.
    encoded_image = preprocess_image(
        image_file_path=image_file_path, max_width=640, max_height=480
    )

    # The example here only shows prediction with one image. You can extend it
    # to predict with a batch of images indicated by different keys, which can
    # make sure that the responses corresponding to the given image.
    instances = {
        "instances": [{"image_bytes": {"b64": str(encoded_image)}, "key": image_key}]
    }

    # This example shows sending requests in the same server that you start
    # docker containers. If you would like to send requests to other servers,
    # please change localhost to IP of other servers.
    url = "http://localhost:{}/v1/models/default:predict".format(port_number)

    response = requests.post(url, data=json.dumps(instances))
    print(response.json())

GPU 컨테이너를 사용하여 모델 추론 실행(선택사항)

이 섹션에서는 GPU 컨테이너를 사용하여 모델 추론을 실행하는 방법을 보여줍니다. 이 프로세스는 CPU를 사용하여 모델 추론을 실행하는 방법과 매우 유사합니다. 주요 차이점은 GPU 컨테이너 경로와 GPU 컨테이너를 시작하는 방법입니다.

Docker 이미지 가져오기

먼저, Docker를 사용하여 사전 빌드된 GPU 컨테이너를 가져옵니다. 사전 빌드된 GPU 컨테이너에는 내보낸 Edge 모델을 GPU로 제공하기 위한 환경이 이미 있습니다. 하지만 여기에는 아직 Edge 모델이나 드라이버가 포함되어 있지 않습니다.

사전 빌드된 CPU 컨테이너는 Google Container Registry에 저장됩니다. 컨테이너를 요청하기 전에 Google Container Registry에서 컨테이너 위치의 환경 변수를 설정합니다.

export GPU_DOCKER_GCS_PATH=gcr.io/cloud-devrel-public-resources/gcloud-container-1.14.0-gpu:latest

다음 명령어를 실행하여 GPU 컨테이너를 가져옵니다.

sudo docker pull ${GPU_DOCKER_GCS_PATH}

Docker 컨테이너 실행

이 단계에서는 GPU 컨테이너를 실행하여 Edge 모델 추론을 REST API와 함께 제공합니다. 앞서 설명한 것처럼 NVIDIA 드라이버와 Docker를 설치해야 합니다. 또한 다음 시스템 변수를 설정해야 합니다.

  • ${CONTAINER_NAME} - - 실행될 때 컨테이너 이름을 나타내는 문자열입니다(예: CONTAINER_NAME=automl_high_accuracy_model_gpu).
  • ${PORT} - 나중에 기기에서 REST API 호출을 받아들이는 포트를 나타내는 숫자입니다(예: PORT=8502).

변수를 설정한 후에 명령줄에서 Docker를 실행하여 Edge 모델 추론을 REST API와 함께 제공합니다.

sudo docker run --runtime=nvidia --rm --name "${CONTAINER_NAME}" -v \
${YOUR_MODEL_PATH}:/tmp/mounted_model/0001 -p \
${PORT}:8501 -t ${GPU_DOCKER_GCS_PATH}

컨테이너가 실행되면 http://localhost:${PORT}/v1/models/default:predict에서 REST API를 제공할 준비가 된 것입니다. 다음 섹션에서는 이 위치에 예측 요청을 보내는 방법을 자세히 설명합니다.

예측 요청 보내기

이제 컨테이너가 성공적으로 실행되므로, 테스트 이미지에서 예측 요청을 REST API로 전송할 수 있습니다.

명령줄

명령줄 요청 본문에는 제공된 이미지 식별을 위한 key 문자열 및 base64로 인코딩된 image_bytes가 포함됩니다. 이미지 인코딩에 대한 자세한 내용은 Base64 인코딩 주제를 참조하세요. 요청 JSON 파일의 형식은 다음과 같습니다.

/tmp/request.json
{
  "instances":
  [
    {
      "image_bytes":
      {
        "b64": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "key": "your-chosen-image-key"
    }
  ]
}

로컬 JSON 요청 파일을 만든 후에는 예측 요청을 전송할 수 있습니다.

다음 명령어를 사용하여 예측 요청을 전송합니다.

curl -X POST -d  @/tmp/request.json http://localhost:${PORT}/v1/models/default:predict
응답

다음과 비슷한 출력이 표시됩니다.

{
  "predictions": [
    {
      "detection_multiclass_scores": [
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00240907, 0.00173151, 0.00134027, 0.00287125, 0.00130472, 0.00242674],
        [0.00227344, 0.00124374, 0.00147101, 0.00377446, 0.000997812, 0.0029003],
        [0.00132903, 0.000844955, 0.000537515, 0.00474253, 0.000508994, 0.00130466],
        [0.00233048, 0.00207388, 0.00123361, 0.0052332, 0.00132892, 0.00333592],
        [0.00110534, 0.000204086, 0.000247836, 0.000553966, 0.000193745, 0.000359297],
        [0.00112912, 0.000443578, 0.000779897, 0.00203282, 0.00069508, 0.00188044],
        [0.00271052, 0.00163364, 0.00138229, 0.00314173, 0.00164038, 0.00332257],
        [0.00227907, 0.00217116, 0.00190553, 0.00321552, 0.00233933, 0.0053153],
        [0.00271052, 0.00163364, 0.00138229, 0.00314173, 0.00164038, 0.00332257],
        [0.00250274, 0.000489146, 0.000879943, 0.00355569, 0.00129834, 0.00355521],
        [0.00227344, 0.00124374, 0.00147101, 0.00377446, 0.000997812, 0.0029003],
        [0.00241205, 0.000786602, 0.000896335, 0.00187016, 0.00106838, 0.00193021],
        [0.00132069, 0.00173706, 0.00389183, 0.00536761, 0.00387135, 0.00752795],
        [0.0011555, 0.00025022, 0.000221372, 0.000536889, 0.000187278, 0.000306398],
        [0.00150242, 0.000391901, 0.00061205, 0.00158429, 0.000300348, 0.000788659],
        [0.00181362, 0.000169843, 0.000458032, 0.000690967, 0.000296295, 0.000412017],
        [0.00101465, 0.000184, 0.000148445, 0.00068599, 0.000111818, 0.000290155],
        [0.00128508, 0.00108775, 0.00298983, 0.00174832, 0.00143594, 0.00285548],
        [0.00137702, 0.000480384, 0.000831485, 0.000920624, 0.000405788, 0.000735044],
        [0.00103369, 0.00152704, 0.000892937, 0.00269693, 0.00214335, 0.00588191],
        [0.0013324, 0.000647604, 0.00293729, 0.00156629, 0.00195253, 0.00239435],
        [0.0022423, 0.00141206, 0.0012649, 0.00450748, 0.00138766, 0.00249887],
        [0.00125939, 0.0002428, 0.000370741, 0.000917137, 0.00024578, 0.000412881],
        [0.00135186, 0.000139147, 0.000525713, 0.00103053, 0.000366062, 0.000844955],
        [0.00127548, 0.000989318, 0.00256863, 0.00162545, 0.00311682, 0.00439551],
        [0.00112912, 0.000443578, 0.000779897, 0.00203282, 0.00069508, 0.00188044],
        [0.00114602, 0.00107747, 0.00145, 0.00320849, 0.00211915, 0.00331426],
        [0.00148326, 0.00059548, 0.00431389, 0.00164703, 0.00311947, 0.00268343],
        [0.00154313, 0.000925034, 0.00770769, 0.00252789, 0.00489518, 0.00352332],
        [0.00135094, 0.00042069, 0.00088492, 0.000987828, 0.000755847, 0.00144881],
        [0.0015994, 0.000540197, 0.00163212, 0.00140327, 0.00114474, 0.0026556],
        [0.00150502, 0.000138223, 0.000343591, 0.000529736, 0.000173837, 0.000381887],
        [0.00127372, 0.00066787, 0.00149515, 0.00272799, 0.00110033, 0.00370145],
        [0.00144503, 0.000365585, 0.00318581, 0.00126475, 0.00212631, 0.00204816],
        [0.00132069, 0.00173706, 0.00389183, 0.00536761, 0.00387135, 0.00752795],
        [0.00198057, 0.000307024, 0.000573188, 0.00147268, 0.000757724, 0.0017142],
        [0.00157535, 0.000590324, 0.00190055, 0.00170627, 0.00138417, 0.00246152],
        [0.00177169, 0.000364572, 0.00183856, 0.000767767, 0.00121492, 0.000916481]
      ],
      "detection_classes":
        [5.0, 2.0, 5.0, 5.0, 5.0, 4.0, 5.0, 5.0, 4.0, 4.0, 2.0, 4.0, 4.0, 4.0, 5.0, 4.0, 5.0,
        5.0, 4.0, 5.0, 5.0, 4.0, 5.0, 2.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 4.0, 4.0,
        5.0, 4.0, 4.0, 5.0, 5.0],
      "num_detections": 40.0,
      "image_info": [320, 320, 1, 0, 320, 320],
      "detection_boxes": [
        [0.457792, 0.0, 0.639324, 0.180828],
        [0.101111, 0.0, 0.89904, 0.995376],
        [0.447649, 0.314644, 0.548206, 0.432875],
        [0.250341, 0.733411, 0.3419, 0.847185],
        [0.573936, 0.0933048, 0.766472, 0.208054],
        [0.490438, 0.194659, 0.825894, 0.563959],
        [0.619383, 0.57948, 0.758244, 0.694948],
        [0.776185, 0.554518, 0.841549, 0.707129],
        [0.101111, 0.0, 0.89904, 0.995376],
        [0.431243, 0.0917888, 0.850772, 0.617123],
        [0.250883, 0.13572, 0.780518, 0.817881],
        [0.327646, 0.878977, 0.607503, 0.989904],
        [0.573936, 0.0933048, 0.766472, 0.208054],
        [0.37792, 0.460952, 0.566977, 0.618865],
        [0.373325, 0.575019, 0.463646, 0.642949],
        [0.27251, 0.0714827, 0.790764, 0.77176],
        [0.725154, 0.561221, 0.849777, 0.702165],
        [0.37549, 0.558988, 0.460575, 0.626821],
        [0.265563, 0.248368, 0.785451, 0.977509],
        [0.605674, 0.597553, 0.760419, 0.744799],
        [0.400611, 0.327271, 0.487579, 0.424036],
        [0.48632, 0.980808, 0.606008, 0.997468],
        [0.542414, 0.0588853, 0.752879, 0.200775],
        [0.490438, 0.194659, 0.825894, 0.563959],
        [0.368839, 0.115654, 0.741839, 0.587659],
        [0.467101, 0.985155, 0.588853, 0.997708],
        [0.755204, 0.561319, 0.836475, 0.676249],
        [0.409855, 0.302322, 0.773464, 0.587772],
        [0.351938, 0.934163, 0.587043, 0.99954],
        [0.27758, 0.72402, 0.334137, 0.846945],
        [0.29875, 0.601199, 0.381122, 0.679323],
        [0.64637, 0.566566, 0.767553, 0.67331],
        [0.372612, 0.596795, 0.457588, 0.666544],
        [0.438422, 0.989558, 0.578529, 0.998366],
        [0.586531, 0.499894, 0.879711, 0.845526],
        [0.608476, 0.644501, 0.759154, 0.827037],
        [0.352501, 0.477601, 0.710863, 0.948605],
        [0.466184, 0.953443, 0.668056, 0.996681],
        [0.547756, 0.00152373, 0.722814, 0.150687],
        [0.759639, 0.548476, 0.866864, 0.722007]
      ],
      "detection_scores":
        [0.877304, 0.839354, 0.824509, 0.579912, 0.461549, 0.306151, 0.268687, 0.197998, 0.181444,
        0.17856, 0.152705, 0.148958, 0.14726, 0.135506, 0.128483, 0.12234, 0.105697, 0.105665,
        0.0941569, 0.0891062, 0.0845169, 0.0810551, 0.0794339, 0.0784486, 0.0771784, 0.0770716,
        0.075339, 0.0716749, 0.0715761, 0.07108, 0.0705339, 0.0693555, 0.0677402, 0.0644643,
        0.0631491, 0.062369, 0.0619523, 0.060859, 0.0601122, 0.0589799],
      "detection_classes_as_text":
        ["Tomato", "Salad", "Tomato", "Tomato", "Tomato", "Seafood", "Tomato", "Tomato", "Seafood",
        "Seafood", "Salad", "Seafood", "Seafood", "Seafood", "Tomato", "Seafood", "Tomato",
        "Tomato", "Seafood", "Tomato", "Tomato", "Seafood", "Tomato", "Salad", "Seafood",
        "Seafood", "Tomato", "Seafood", "Seafood", "Tomato", "Tomato", "Tomato", "Tomato",
        "Seafood", "Seafood", "Tomato", "Seafood", "Seafood", "Tomato", "Tomato"],
      "key": "1"
    }
  ]
}

Python

AutoML Vision 객체 감지용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Vision 객체 감지 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Vision 객체 감지 Python API 참조 문서를 참조하세요.

AutoML Vision 객체 감지에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import base64
import cv2
import io
import json

import requests

def preprocess_image(image_file_path, max_width, max_height):
    """Preprocesses input images for AutoML Vision Edge models.

    Args:
        image_file_path: Path to a local image for the prediction request.
        max_width: The max width for preprocessed images. The max width is 640
            (1024) for AutoML Vision Image Classfication (Object Detection)
            models.
        max_height: The max width for preprocessed images. The max height is
            480 (1024) for AutoML Vision Image Classfication (Object
            Detetion) models.
    Returns:
        The preprocessed encoded image bytes.
    """
    # cv2 is used to read, resize and encode images.
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 85]
    im = cv2.imread(image_file_path)
    [height, width, _] = im.shape
    if height > max_height or width > max_width:
        ratio = max(height / float(max_width), width / float(max_height))
        new_height = int(height / ratio + 0.5)
        new_width = int(width / ratio + 0.5)
        resized_im = cv2.resize(
            im, (new_width, new_height), interpolation=cv2.INTER_AREA
        )
        _, processed_image = cv2.imencode(".jpg", resized_im, encode_param)
    else:
        _, processed_image = cv2.imencode(".jpg", im, encode_param)
    return base64.b64encode(processed_image).decode("utf-8")

def container_predict(image_file_path, image_key, port_number=8501):
    """Sends a prediction request to TFServing docker container REST API.

    Args:
        image_file_path: Path to a local image for the prediction request.
        image_key: Your chosen string key to identify the given image.
        port_number: The port number on your device to accept REST API calls.
    Returns:
        The response of the prediction request.
    """
    # AutoML Vision Edge models will preprocess the input images.
    # The max width and height for AutoML Vision Image Classification and
    # Object Detection models are 640*480 and 1024*1024 separately. The
    # example here is for Image Classification models.
    encoded_image = preprocess_image(
        image_file_path=image_file_path, max_width=640, max_height=480
    )

    # The example here only shows prediction with one image. You can extend it
    # to predict with a batch of images indicated by different keys, which can
    # make sure that the responses corresponding to the given image.
    instances = {
        "instances": [{"image_bytes": {"b64": str(encoded_image)}, "key": image_key}]
    }

    # This example shows sending requests in the same server that you start
    # docker containers. If you would like to send requests to other servers,
    # please change localhost to IP of other servers.
    url = "http://localhost:{}/v1/models/default:predict".format(port_number)

    response = requests.post(url, data=json.dumps(instances))
    print(response.json())

요약

이 가이드에서는 CPU 또는 GPU Docker 컨테이너를 사용하여 Edge 모델을 실행하는 방법을 살펴봤습니다. 이제 더 많은 기기에 컨테이너 기반 솔루션을 배포할 수 있습니다.

다음 단계