# Detect labels in an image by using client libraries

This page shows you how to get started with the Vision API in your favorite programming language.


*** ** * ** ***

To follow step-by-step guidance for this task directly in the
Cloud Shell Editor, click **Guide me**:

[Guide me](https://console.cloud.google.com/?walkthrough_id=vision--detect-labels-image-client-libraries-python)

*** ** * ** ***

## Before you begin

## Install the client library

### Go

Create a project directory, initialize a Go module, and then download the client library:

```
mkdir my-vision-app && cd my-vision-app
go mod init example.com/vision-app
go get cloud.google.com/go/vision/apiv1
```

### Java


For more on setting up your Java development environment, refer to the [Java Development Environment Setup Guide](https://docs.cloud.google.com/java/docs/setup.md.txt).

> [!NOTE]
> **Note:** If your application uses the Spring Framework, a [Spring module](https://docs.cloud.google.com/vision/docs/adding-spring.md.txt) is also available.

If you are using [Maven](https://maven.apache.org/), add
the following to your `pom.xml` file. For more information about
BOMs, see [The Google Cloud Platform Libraries BOM](https://cloud.google.com/java/docs/bom).

```markdown
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.90.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
  </dependency>
</dependencies>
```

If you are using [Gradle](https://gradle.org/),
add the following to your dependencies:

```markdown
implementation platform('com.google.cloud:libraries-bom:26.90.0')

implementation 'com.google.cloud:google-cloud-vision'
```

If you are using [sbt](https://www.scala-sbt.org/), add
the following to your dependencies:

```markdown
libraryDependencies += "com.google.cloud" % "google-cloud-vision" % "3.100.0"
```

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your
project using the following IDE plugins:

- [Cloud Code for VS Code](https://docs.cloud.google.com/code/docs/vscode/client-libraries.md.txt)
- [Cloud Code for IntelliJ](https://docs.cloud.google.com/code/docs/intellij/client-libraries.md.txt)

The plugins provide additional functionality, such as key management for service accounts. Refer
to each plugin's documentation for details.

> [!NOTE]
> **Note:** Cloud Java client libraries do not currently support Android.

### Node.js


For more on setting up your Node.js development environment, refer to the [Node.js Development Environment Setup Guide](https://docs.cloud.google.com/nodejs/docs/setup.md.txt).

```
npm install @google-cloud/vision
```

### Python


For more on setting up your Python development environment, refer to the [Python Development Environment Setup Guide](https://docs.cloud.google.com/python/docs/setup.md.txt).

```
pip install --upgrade google-cloud-vision
```

<br />

## Label detection samples

Now you can use the Vision API to request
information from an image, such as label detection. Run the following code
to perform your first image label detection request.

<br />

### Go


Before trying this sample, follow the Go setup instructions in the
[Vision quickstart using
client libraries](https://docs.cloud.google.com/vision/docs/quickstart-client-libraries).


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


To authenticate to Vision, 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.md.txt).

```go

// 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.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.NewImageFromReader(file)
	if err != nil {
		log.Fatalf("Failed to create image: %v", err)
	}

	labels, err := client.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


Before trying this sample, follow the Java setup instructions in the
[Vision quickstart using
client libraries](https://docs.cloud.google.com/vision/docs/quickstart-client-libraries).


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


To authenticate to Vision, 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.md.txt).

```java
// Imports the Google Cloud client library

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
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 (ImageAnnotatorClient vision = ImageAnnotatorClient.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);
      ByteString imgBytes = ByteString.copyFrom(data);

      // Builds the image annotation request
      List<AnnotateImageRequest> requests = new ArrayList<>();
      Image img = Image.newBuilder().setContent(imgBytes).build();
      Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
      requests.add(request);

      // Performs label detection on the image file
      BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
      List<AnnotateImageResponse> responses = response.getResponsesList();

      for (AnnotateImageResponse res : responses) {
        if (res.hasError()) {
          System.out.format("Error: %s%n", res.getError().getMessage());
          return;
        }

        for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          annotation
              .getAllFields()
              .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
        }
      }
    }
  }
}
```

### Node.js


Before trying this sample, follow the Node.js setup instructions in the
[Vision quickstart using
client libraries](https://docs.cloud.google.com/vision/docs/quickstart-client-libraries).


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


To authenticate to Vision, 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.md.txt).

```javascript
async function quickstart() {
  // Imports the Google Cloud client library
  const vision = require('@google-cloud/vision');

  // Creates a client
  const client = new vision.ImageAnnotatorClient();

  // Performs label detection on the image file
  const [result] = await client.labelDetection('./resources/wakeupcat.jpg');
  const labels = result.labelAnnotations;
  console.log('Labels:');
  labels.forEach(label => console.log(label.description));
}
quickstart();
```

### Python


Before trying this sample, follow the Python setup instructions in the
[Vision quickstart using
client libraries](https://docs.cloud.google.com/vision/docs/quickstart-client-libraries).


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


To authenticate to Vision, 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.md.txt).

```python

# 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

```

<br />

## Run the sample

To run the prior samples, use the following commands. If you cloned the GitHub
repository for the specific sample language, uncomment the first line:

### Go

```bash
# cd golang-samples/vision/vision_quickstart/
go run .
```

### Java

```bash
# cd java-docs-samples/vision/snippets/src/main/java/com/example/vision/quickstart/
javac QuickstartSample.java
java QuickstartSample.java
```

### Node.js

```bash
# cd nodejs-docs-samples/vision/
node quickstart.js
```

### Python

```bash
# cd python-docs-samples/vision/snippets/quickstart
python -c 'import quickstart; quickstart.run_quickstart()'
```
Congratulations! You've sent your first request to Vision.

## How did it go?

<button class="button button-blue expand-control gc-analytics-event" data-category="Quickstart" data-action="Feedback" data-label="Vision API, Client Libraries" data-value="1" track-type="quickstart" track-name="feedbackLink" track-metadata-position="steps" track-metadata-end-goal="itWorked"> It worked! </button>

> [!TIP]
> **Great!** What did you like about the quickstart? What could we have done better? [Let us know!](https://docs.cloud.google.com/vision/docs/detect-labels-image-client-libraries.md.txt#).

<button class="button expand-control gc-analytics-event" data-category="Quickstart" data-action="Feedback" data-label="Vision API, Client Libraries" data-value="0" style="position: absolute; top: 0; left: 110px;" track-type="quickstart" track-name="feedbackLink" track-metadata-position="steps" track-metadata-end-goal="itFailed"> I got stuck. </button>

> [!WARNING]
> **We're sorry to hear that.** [Let us know what went wrong](https://docs.cloud.google.com/vision/docs/detect-labels-image-client-libraries.md.txt#). We'll want to fix it.

## Clean up


To avoid incurring charges to your Google Account for
the resources used in this quickstart:

- Use the [Google Cloud console](https://console.cloud.google.com/) to delete your project if you do not need it.

## What's next


Find out more about our [Vision API Client Libraries](https://docs.cloud.google.com/vision/docs/reference/libraries).