Detecting Logos

Logo Detection detects popular product logos within an image.

Detecting Logos in a local image

Protocol

Refer to the images:annotate API endpoint for complete details.

To perform Logo Detection, make a POST request and provide the appropriate request body:

POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
{
  "requests": [
    {
      "image": {
        "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "features": [
        {
          "type": "LOGO_DETECTION"
        }
      ]
    }
  ]
}

See the AnnotateImageRequest reference documentation for more information on configuring the request body.

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "responses": [
    {
      "logoAnnotations": [
        {
          "mid": "/m/045c7b",
          "description": "Google",
          "score": 0.32291126,
          "boundingPoly": {
            "vertices": [
              {
                "x": 63,
                "y": 18
              },
              {
                "x": 123,
                "y": 18
              },
              {
                "x": 123,
                "y": 38
              },
              {
                "x": 63,
                "y": 38
              }
            ]
          }
        }
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// Load an image from a local file.
var image = Image.FromFile(filePath);
var client = ImageAnnotatorClient.Create();
var response = client.DetectLogos(image);
foreach (var annotation in response)
{
    if (annotation.Description != null)
        Console.WriteLine(annotation.Description);
}

Go

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// detectLogos gets logos from the Vision API for an image at the given file path.
func detectLogos(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewClient(ctx)
	if err != nil {
		return err
	}

	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return err
	}
	annotations, err := client.DetectLogos(ctx, image, 10)
	if err != nil {
		return err
	}

	if len(annotations) == 0 {
		fmt.Fprintln(w, "No logos found.")
	} else {
		fmt.Fprintln(w, "Logos:")
		for _, annotation := range annotations {
			fmt.Fprintln(w, annotation.Description)
		}
	}

	return nil
}

Java

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

public static void detectLogos(String filePath, PrintStream out) throws IOException {
  List<AnnotateImageRequest> requests = new ArrayList<>();

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

  Image img = Image.newBuilder().setContent(imgBytes).build();
  Feature feat = Feature.newBuilder().setType(Type.LOGO_DETECTION).build();
  AnnotateImageRequest request =
      AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
  requests.add(request);

  BatchAnnotateImagesResponse response =
      ImageAnnotatorClient.create().batchAnnotateImages(requests);
  List<AnnotateImageResponse> responses = response.getResponsesList();

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

    // For full list of available annotations, see http://g.co/cloud/vision/docs
    for (EntityAnnotation annotation : res.getLogoAnnotationsList()) {
      out.println(annotation.getDescription());
    }
  }
}

Node.js

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// Imports the Google Cloud client library
const Vision = require('@google-cloud/vision');

// Instantiates a client
const vision = Vision();

// The path to the local image file, e.g. "/path/to/image.png"
// const fileName = '/path/to/image.png';

// Performs logo detection on the local file
vision.detectLogos(fileName)
  .then((results) => {
    const logos = results[0];

    console.log('Logos:');
    logos.forEach((logo) => console.log(logo));
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

use Google\Cloud\Vision\VisionClient;

// $projectId = 'YOUR_PROJECT_ID';
// $path = 'path/to/your/image.jpg'

$vision = new VisionClient([
    'projectId' => $projectId,
]);
$image = $vision->image(file_get_contents($path), ['LOGO_DETECTION']);
$result = $vision->annotate($image);
print("Logos:\n");
foreach ((array) $result->logos() as $logo) {
    print($logo->description() . PHP_EOL);
}

Python

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

def detect_logos(path):
    """Detects logos in the file."""
    vision_client = vision.Client()

    with io.open(path, 'rb') as image_file:
        content = image_file.read()

    image = vision_client.image(content=content)

    logos = image.detect_logos()
    print('Logos:')

    for logo in logos:
        print(logo.description)

Ruby

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

# project_id = "Your Google Cloud project ID"
# image_path = "Path to local image file, eg. './image.png'"

require "google/cloud/vision"

vision = Google::Cloud::Vision.new project: project_id
image  = vision.image image_path

image.logos.each do |logo|
  puts logo.description
end

Detecting Logos in a remote image

For your convenience, the Cloud Vision API can perform logo detection directly on an image file located in Google Cloud Storage or on the Web without the need to send the contents of the image file in the body of your request.

Protocol

Refer to the images:annotate API endpoint for complete details.

To perform Logo Detection, make a POST request and provide the appropriate request body:

POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
{
  "requests": [
    {
      "image": {
        "source": {
          "gcsImageUri": "gs://YOUR_BUCKET_NAME/YOUR_FILE_NAME"
        }
      },
      "features": [
        {
          "type": "LOGO_DETECTION"
        }
      ]
    }
  ]
}

See the AnnotateImageRequest reference documentation for more information on configuring the request body.

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "responses": [
    {
      "logoAnnotations": [
        {
          "mid": "/m/045c7b",
          "description": "Google",
          "score": 0.32291126,
          "boundingPoly": {
            "vertices": [
              {
                "x": 63,
                "y": 18
              },
              {
                "x": 123,
                "y": 18
              },
              {
                "x": 123,
                "y": 38
              },
              {
                "x": 63,
                "y": 38
              }
            ]
          }
        }
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// Specify a Google Cloud Storage uri for the image.
var image = Image.FromUri(uri);
var client = ImageAnnotatorClient.Create();
var response = client.DetectLogos(image);
foreach (var annotation in response)
{
    if (annotation.Description != null)
        Console.WriteLine(annotation.Description);
}

Go

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// detectLogos gets logos from the Vision API for an image at the given file path.
func detectLogosURI(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewClient(ctx)
	if err != nil {
		return err
	}

	image := vision.NewImageFromURI(file)
	annotations, err := client.DetectLogos(ctx, image, 10)
	if err != nil {
		return err
	}

	if len(annotations) == 0 {
		fmt.Fprintln(w, "No logos found.")
	} else {
		fmt.Fprintln(w, "Logos:")
		for _, annotation := range annotations {
			fmt.Fprintln(w, annotation.Description)
		}
	}

	return nil
}

Java

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

public static void detectLogosGcs(String gcsPath, PrintStream out) throws IOException {
  List<AnnotateImageRequest> requests = new ArrayList<>();

  ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
  Image img = Image.newBuilder().setSource(imgSource).build();
  Feature feat = Feature.newBuilder().setType(Type.LOGO_DETECTION).build();
  AnnotateImageRequest request =
      AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
  requests.add(request);

  BatchAnnotateImagesResponse response =
      ImageAnnotatorClient.create().batchAnnotateImages(requests);
  List<AnnotateImageResponse> responses = response.getResponsesList();

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

    // For full list of available annotations, see http://g.co/cloud/vision/docs
    for (EntityAnnotation annotation : res.getLogoAnnotationsList()) {
      out.println(annotation.getDescription());
    }
  }
}

Node.js

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

// Imports the Google Cloud client libraries
const Storage = require('@google-cloud/storage');
const Vision = require('@google-cloud/vision');

// Instantiates clients
const storage = Storage();
const vision = Vision();

// The name of the bucket where the file resides, e.g. "my-bucket"
// const bucketName = 'my-bucket';

// The path to the file within the bucket, e.g. "path/to/image.png"
// const fileName = 'path/to/image.png';

// Performs logo detection on the remote file
vision.detectLogos(storage.bucket(bucketName).file(fileName))
  .then((results) => {
    const logos = results[0];

    console.log('Logos:');
    logos.forEach((logo) => console.log(logo));
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

use Google\Cloud\Vision\VisionClient;
use Google\Cloud\Storage\StorageClient;

// $projectId = 'YOUR_PROJECT_ID';
// $bucketName = 'your-bucket-name'
// $objectName = 'your-object-name'

$vision = new VisionClient([
    'projectId' => $projectId,
]);
$storage = new StorageClient([
    'projectId' => $projectId,
]);

// fetch the storage object and annotate the image
$object = $storage->bucket($bucketName)->object($objectName);
$image = $vision->image($object, ['LOGO_DETECTION']);
$result = $vision->annotate($image);

// print the response
print("Logos:\n");
foreach ((array) $result->logos() as $logo) {
    print($logo->description() . PHP_EOL);
}

Python

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

def detect_logos_uri(uri):
    """Detects logos in the file located in Google Cloud Storage or on the Web.
    """
    vision_client = vision.Client()
    image = vision_client.image(source_uri=uri)

    logos = image.detect_logos()
    print('Logos:')

    for logo in logos:
        print(logo.description)

Ruby

For more on installing and creating a Cloud Vision API client, refer to Cloud Vision API Client Libraries.

# project_id = "Your Google Cloud project ID"
# image_path = "Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'"

require "google/cloud/vision"

vision = Google::Cloud::Vision.new project: project_id
image  = vision.image image_path

image.logos.each do |logo|
  puts logo.description
end

Send feedback about...

Google Cloud Vision API Documentation