Perform label detection on an image.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Detect labels on an image](https://docs.cloud.google.com/vision/docs/samples/vision-quickstart)
- [Quickstart: Detect labels in an image by using client libraries](https://docs.cloud.google.com/vision/docs/detect-labels-image-client-libraries)
- [Vision client libraries](https://docs.cloud.google.com/vision/docs/libraries)

## Code sample

### Go


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Go API
reference documentation](https://godoc.org/cloud.google.com/go/vision/apiv1).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    // Sample vision-quickstart uses the Google Cloud Vision API to label an image.
    package main

    import (
    	"context"
    	"fmt"
    	"log"
    	"os"

    	vision "cloud.google.com/go/vision/apiv1"
    )

    func main() {
    	ctx := context.Background()

    	// Creates a client.
    	client, err := vision.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/vision/latest/apiv1.html#cloud_google_com_go_vision_apiv1_ImageAnnotatorClient_NewImageAnnotatorClient(ctx)
    	if err != nil {
    		log.Fatalf("Failed to create client: %v", err)
    	}
    	defer client.Close()

    	// Sets the name of the image file to annotate.
    	filename := "../testdata/cat.jpg"

    	file, err := os.Open(filename)
    	if err != nil {
    		log.Fatalf("Failed to read file: %v", err)
    	}
    	defer file.Close()
    	image, err := vision.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/vision/latest/apiv1.html#cloud_google_com_go_vision_apiv1_NewImageFromReader(file)
    	if err != nil {
    		log.Fatalf("Failed to create image: %v", err)
    	}

    	labels, err := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/vision/latest/apiv1.html#cloud_google_com_go_vision_apiv1_ImageAnnotatorClient_DetectLabels(ctx, image, nil, 10)
    	if err != nil {
    		log.Fatalf("Failed to detect labels: %v", err)
    	}

    	fmt.Println("Labels:")
    	for _, label := range labels {
    		fmt.Println(label.Description)
    	}
    }

### Java


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/overview).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    // Imports the Google Cloud client library

    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageResponse.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateImagesResponse.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.EntityAnnotation.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.Type.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html;
    import com.google.protobuf.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.List;

    public class QuickstartSample {
      public static void main(String... args) throws Exception {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the "close" method on the client to safely clean up any remaining background resources.
        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html vision = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html.create()) {

          // The path to the image file to annotate
          String fileName = "./resources/wakeupcat.jpg";

          // Reads the image file into memory
          Path path = Paths.get(fileName);
          byte[] data = Files.readAllBytes(path);
          https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html imgBytes = https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html#com_google_protobuf_ByteString_copyFrom_byte___(data);

          // Builds the image annotation request
          List<AnnotateImageRequest> requests = new ArrayList<>();
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html img = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html.newBuilder().setContent(imgBytes).build();
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html feat = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.newBuilder().setType(https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.Type.html.LABEL_DETECTION).build();
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html request =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html.newBuilder().addFeatures(feat).setImage(img).build();
          requests.add(request);

          // Performs label detection on the image file
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateImagesResponse.html response = vision.batchAnnotateImages(requests);
          List<AnnotateImageResponse> responses = response.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.BatchAnnotateImagesResponse.html#com_google_cloud_vision_v1_BatchAnnotateImagesResponse_getResponsesList__();

          for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageResponse.html res : responses) {
            if (res.hasError()) {
              System.out.format("Error: %s%n", res.getError().getMessage());
              return;
            }

            for (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.EntityAnnotation.html annotation : res.getLabelAnnotationsList()) {
              annotation
                  .getAllFields()
                  .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
            }
          }
        }
      }
    }

### Kotlin

    // import com.google.cloud.vision.v1.ImageAnnotatorClient
    // import java.io.File
    val imgProto = ByteString.copyFrom(File(imageFileName).readBytes())
    val vision = ImageAnnotatorClient.create()

    // Set up the Cloud Vision API request.
    val img = Image.newBuilder().setContent(imgProto).build()
    val feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build()
    val request = AnnotateImageRequest.newBuilder()
        .addFeatures(feat)
        .setImage(img)
        .build()

    // Call the Cloud Vision API and perform label detection on the image.
    val result = vision.batchAnnotateImages(arrayListOf(request))

    // Print the label annotations for the first response.
    result.responsesList[0].labelAnnotationsList.forEach { label ->
        println("${label.description} (${(label.score * 100).toInt()}%)")
    }

### Node.js


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Node.js API
reference documentation](https://googleapis.dev/nodejs/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    async function quickstart() {
      // Imports the Google Cloud client library
      const vision = require('https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html');

      // Creates a client
      const client = new vision.https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html();

      // Performs label detection on the image file
      const [result] = await client.labelDetection('./resources/wakeupcat.jpg');
      const labels = https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/vision/protos.google.longrunning.operation.html.labelAnnotations;
      console.log('Labels:');
      labels.forEach(label => console.log(label.description));
    }
    quickstart();

### PHP


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    # includes the autoloader for libraries installed with composer
    require __DIR__ . '/vendor/autoload.php';

    # imports the Google Cloud client library
    use Google\Cloud\Vision\V1\Client\ImageAnnotatorClient;

    # instantiates a client
    $imageAnnotator = new ImageAnnotatorClient();

    # the name of the image file to annotate
    $fileName = 'test/data/wakeupcat.jpg';

    # prepare the image to be annotated
    $image = file_get_contents($fileName);

    # performs label detection on the image file
    $response = $imageAnnotator->labelDetection($image);
    $labels = $response->getLabelAnnotations();

    if ($labels) {
        echo('Labels:' . PHP_EOL);
        foreach ($labels as $label) {
            echo($label->getDescription() . PHP_EOL);
        }
    } else {
        echo('No label found' . PHP_EOL);
    }

### Python


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    # Imports the Google Cloud client library
    from google.cloud import vision



    def run_quickstart() -> vision.EntityAnnotation:
        """Provides a quick start example for Cloud Vision."""

        # Instantiates a client
        client = vision.ImageAnnotatorClient()

        # The URI of the image file to annotate
        file_uri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg"

        image = vision.Image()
        image.source.image_uri = file_uri

        # Performs label detection on the image file
        response = client.label_detection(image=image)
        labels = response.label_annotations

        print("Labels:")
        for label in labels:
            print(label.description)

        return labels

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=cloudvision).