Running Crop Hints

Crop Hints suggests vertices for a crop region on an image.

Run Crop Hints on a local image

Protocol

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

To run Crop Hints, 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": "CROP_HINTS"
        }
      ]
    }
  ]
}

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": [
    {
      "cropHintsAnnotation": {
        "cropHints": [
          {
            "boundingPoly": {
              "vertices": [
                {},
                {
                  "x": 280
                },
                {
                  "x": 280,
                  "y": 43
                },
                {
                  "y": 43
                }
              ]
            },
            "confidence": 0.79999995,
            "importanceFraction": 1
          }
        ]
      }
    }
  ]
}

Java

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

public static void detectCropHints(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.CROP_HINTS).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
    CropHintsAnnotation annotation = res.getCropHintsAnnotation();
    for (CropHint hint : annotation.getCropHintsList()) {
      out.println(hint.getBoundingPoly());
    }
  }
}

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 = 'my-file.jpg';

// Find crop hints for the local file
vision.detectCrops(fileName)
  .then((data) => {
    const cropHints = data[0];

    cropHints.forEach((hintBounds, hintIdx) => {
      console.log(`Crop Hint ${hintIdx}:`);
      hintBounds.forEach((bound, boundIdx) => {
        console.log(`  Bound ${boundIdx}: (${bound.x}, ${bound.y})`);
      });
    });
  });

Python

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

def detect_crop_hints(path):
    """Detects crop hints in an image."""
    vision_client = vision.Client()
    with io.open(path, 'rb') as image_file:
        content = image_file.read()
    image = vision_client.image(content=content)

    hints = image.detect_crop_hints({1.77})

    for n, hint in enumerate(hints):
        print('\nCrop Hint: {}'.format(n))

        vertices = (['({},{})'.format(bound.x_coordinate, bound.y_coordinate)
                    for bound in hint.bounds.vertices])

        print('bounds: {}'.format(','.join(vertices)))

Running Crop Hints on a remote image

For your convenience, the Cloud Vision API can run Crop Hints 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 run Crop Hints, 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": "CROP_HINTS"
        }
      ]
    }
  ]
}

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": [
   {
      "cropHintsAnnotation": {
        "cropHints": [
          {
            "boundingPoly": {
              "vertices": [
                {},
                {
                  "x": 280
                },
                {
                  "x": 280,
                  "y": 43
                },
                {
                  "y": 43
                }
              ]
            },
            "confidence": 0.79999995,
            "importanceFraction": 1
          }
        ]
      }
    }
  ]
}

Java

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

public static void detectCropHintsGcs(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.CROP_HINTS).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
    CropHintsAnnotation annotation = res.getCropHintsAnnotation();
    for (CropHint hint : annotation.getCropHintsList()) {
      out.println(hint.getBoundingPoly());
    }
  }
}

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 = 'my-file.jpg';

// Find crop hints for the remote file
vision.detectCrops(storage.bucket(bucketName).file(fileName))
  .then((data) => {
    const cropHints = data[0];

    cropHints.forEach((hintBounds, hintIdx) => {
      console.log(`Crop Hint ${hintIdx}:`);
      hintBounds.forEach((bound, boundIdx) => {
        console.log(`  Bound ${boundIdx}: (${bound.x}, ${bound.y})`);
      });
    });
  });

Python

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

def detect_crop_hints_uri(uri):
    """Detects crop hints in the file located in Google Cloud Storage."""
    vision_client = vision.Client()
    image = vision_client.image(source_uri=uri)

    hints = image.detect_crop_hints({1.77})
    for n, hint in enumerate(hints):
        print('\nCrop Hint: {}'.format(n))

        vertices = (['({},{})'.format(bound.x_coordinate, bound.y_coordinate)
                    for bound in hint.bounds.vertices])

        print('bounds: {}'.format(','.join(vertices)))