Detect multiple objects in a local file (beta)

Stay organized with collections Save and categorize content based on your preferences.

Perform object detection for multiple objects in an image using on a local file (for beta launch).

Code sample


Before trying this sample, follow the Java setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Java API reference documentation.

 * Detects localized objects in the specified local image.
 * @param filePath The path to the file to perform localized object detection on.
 * @param out A {@link PrintStream} to write detected objects to.
 * @throws Exception on errors while closing the client.
 * @throws IOException on Input/Output errors.
public static void detectLocalizedObjects(String filePath, PrintStream out)
    throws Exception, IOException {
  List<AnnotateImageRequest> requests = new ArrayList<>();

  ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));

  Image img = Image.newBuilder().setContent(imgBytes).build();
  AnnotateImageRequest request =

  // Perform the request
  try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
    BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
    List<AnnotateImageResponse> responses = response.getResponsesList();

    // Display the results
    for (AnnotateImageResponse res : responses) {
      for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) {
        out.format("Object name: %s\n", entity.getName());
        out.format("Confidence: %s\n", entity.getScore());
        out.format("Normalized Vertices:\n");
            .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY()));


Before trying this sample, follow the Python setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Python API reference documentation.

def localize_objects(path):
    """Localize objects in the local image.

    path: The path to the local file.
    from import vision_v1p3beta1 as vision
    client = vision.ImageAnnotatorClient()

    with open(path, 'rb') as image_file:
        content =
    image = vision.Image(content=content)

    objects = client.object_localization(

    print('Number of objects found: {}'.format(len(objects)))
    for object_ in objects:
        print('\n{} (confidence: {})'.format(, object_.score))
        print('Normalized bounding polygon vertices: ')
        for vertex in object_.bounding_poly.normalized_vertices:
            print(' - ({}, {})'.format(vertex.x, vertex.y))

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.