Как аннотировать НЕСКОЛЬКО изображений из одного вызова с помощью API видения Google? питон

Недавно я начал использовать Google Vision API. Я пытаюсь аннотировать пакет изображений и поэтому выдал 'аннотацию пакетного изображения в автономном режиме. ' из их документации.

Однако мне непонятно, как я могу аннотировать НЕСКОЛЬКО изображений из одного вызова API. Допустим, я сохранил 10 изображений в своей облачной корзине Google. Как я могу аннотировать все эти изображения сразу и сохранить их в одном файле JSON? Прямо сейчас я написал программу, которая вызывает их функцию-пример, и она работает, но, говоря проще, почему я не могу сказать: «Посмотрите в этой папке и аннотируйте все изображения в ней»?

Заранее спасибо.

from batch_image_labeling import sample_async_batch_annotate_images
counter = 0
for file in os.listdir('my_directory'):
    filename = file
    sample_async_batch_annotate_images('gs://my_bucket/{}'.format(filename), 'gs://my_bucket/{}'.format(counter))
    counter += 1


from google.cloud import vision_v1
from google.cloud.vision_v1 import enums
import six

def sample_async_batch_annotate_images(input_image_uri, output_uri):
  """Perform async batch image annotation"""

  client = vision_v1.ImageAnnotatorClient()

  if isinstance(input_image_uri, six.binary_type):
    input_image_uri = input_image_uri.decode('utf-8')
  if isinstance(output_uri, six.binary_type):
    output_uri = output_uri.decode('utf-8')
  source = {'image_uri': input_image_uri}
  image = {'source': source}
  type_ = enums.Feature.Type.LABEL_DETECTION
  features_element = {'type': type_}
  type_2 = enums.Feature.Type.IMAGE_PROPERTIES
  features_element_2 = {'type': type_2}
  features = [features_element, features_element_2]
  requests_element = {'image': image, 'features': features}
  requests = [requests_element]
  gcs_destination = {'uri': output_uri}

  # The max number of responses to output in each JSON file
  batch_size = 2
  output_config = {'gcs_destination': gcs_destination, 'batch_size': batch_size}

  operation = client.async_batch_annotate_images(requests, output_config)

  print('Waiting for operation to complete...')
  response = operation.result()

  # The output is written to GCS with the provided output_uri as prefix
  gcs_output_uri = response.output_config.gcs_destination.uri
  print('Output written to GCS with prefix: {}'.format(gcs_output_uri))

person Bente    schedule 06.11.2019    source источник


Ответы (1)


Из этого примера несколько неясно, но ваш вызов async_batch_annotate_images принимает параметр requests, который представляет собой список нескольких запросов. Итак, вы можете сделать что-то вроде этого:

rom google.cloud import vision_v1
from google.cloud.vision_v1 import enums
import six

def generate_request(input_image_uri):
  if isinstance(input_image_uri, six.binary_type):
    input_image_uri = input_image_uri.decode('utf-8')
  if isinstance(output_uri, six.binary_type):
    output_uri = output_uri.decode('utf-8')
  source = {'image_uri': input_image_uri}
  image = {'source': source}
  type_ = enums.Feature.Type.LABEL_DETECTION
  features_element = {'type': type_}
  type_2 = enums.Feature.Type.IMAGE_PROPERTIES
  features_element_2 = {'type': type_2}
  features = [features_element, features_element_2]
  requests_element = {'image': image, 'features': features}

  return requests_element


def sample_async_batch_annotate_images(input_uri, output_uri):
  """Perform async batch image annotation"""

  client = vision_v1.ImageAnnotatorClient()

  requests = [
    generate_request(input_uri.format(filename))
    for filename in os.listdir('my_directory')
  ]

  gcs_destination = {'uri': output_uri}

  # The max number of responses to output in each JSON file
  batch_size = 1
  output_config = {'gcs_destination': gcs_destination, 'batch_size': batch_size}

  operation = client.async_batch_annotate_images(requests, output_config)

  print('Waiting for operation to complete...')
  response = operation.result()

  # The output is written to GCS with the provided output_uri as prefix
  gcs_output_uri = response.output_config.gcs_destination.uri
  print('Output written to GCS with prefix: {}'.format(gcs_output_uri))


sample_async_batch_annotate_images('gs://my_bucket/{}', 'gs://my_bucket/results')

Это может аннотировать до 2000 изображений в одном запросе. Единственным недостатком является то, что вы можете указать только один output_uri в качестве адресата, поэтому вы не сможете использовать counter для помещения каждого результата в отдельный файл, но вы можете установить batch_size = 1, чтобы обеспечить запись каждого ответа отдельно, если это необходимо. что ты хочешь.

person Dustin Ingram    schedule 06.11.2019
comment
@Bente Рад это слышать! Пожалуйста, не забудьте принять ответ. - person Dustin Ingram; 09.11.2019
comment
Возможно ли иметь такой же скрипт в Node.js? - person Jinjun; 28.01.2020
comment
Я смог получить выходные файлы, названные счетчиком, указав свой URI GCS как "gs://my_bucket/results/batch-{}-".format(counter). Файлы будут отображаться в корзине как batch-1-output-x-to-y.json. Я смог использовать пакетные файлы со 100 ответами в каждом. - person BrettJ; 04.06.2020