0

So I just want to detect text or labels from an image using the google cloud vision API. But When I run this code I always get: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request

But I don't know why...here is the full json output what I get:

{
  "code": 400,
  "errors": [
    {
      "domain": "global",
      "message": "Request Admission Denied.",
      "reason": "badRequest"
    }
  ],
  "message": "Request Admission Denied.",
  "status": "INVALID_ARGUMENT"
}

My test code is here:

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class GoogleDetection extends Detector {

    private static final String CLOUD_VISION_API_KEY = "MY_API_KEY";

    @Override
    String detect(String filePath) {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

        Vision.Builder builder = new Vision.Builder(httpTransport, jsonFactory, null);
        builder.setVisionRequestInitializer(new
                VisionRequestInitializer(CLOUD_VISION_API_KEY));
        Vision vision = builder.build();

        BatchAnnotateImagesRequest batchAnnotateImagesRequest =
                new BatchAnnotateImagesRequest();
        batchAnnotateImagesRequest.setRequests(new ArrayList<AnnotateImageRequest>() {{
            AnnotateImageRequest annotateImageRequest = new AnnotateImageRequest();

            // Image to bytes
            Image base64EncodedImage = new Image();
            BufferedImage bufferedImage = null;
            File imgPath = new File(filePath);
            try {
                bufferedImage = ImageIO.read(imgPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            WritableRaster raster = bufferedImage.getRaster();
            DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

            byte[] imageBytes = data.getData();

            // Base64 encode the JPEG
            base64EncodedImage.encodeContent(imageBytes);
            annotateImageRequest.setImage(base64EncodedImage);


            // add the features we want
            annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
                Feature labelDetection = new Feature();
                labelDetection.setType("LABEL_DETECTION");
                labelDetection.setMaxResults(10);
                add(labelDetection);
            }});

            // Add the list of one thing to the request
            add(annotateImageRequest);
        }});

        Vision.Images.Annotate annotateRequest;
        BatchAnnotateImagesResponse response = null;
        try {
            annotateRequest = vision.images().annotate(batchAnnotateImagesRequest);
            // Due to a bug: requests to Vision API containing large images fail when GZipped.
            annotateRequest.setDisableGZipContent(true);

            response = annotateRequest.execute();
            System.out.println(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return convertResponseToString(response);
    }

    private String convertResponseToString(BatchAnnotateImagesResponse response) {
        String message = "I found these things:\n\n";

        List<EntityAnnotation> labels = response.getResponses().get(0).getLabelAnnotations();
        if (labels != null) {
            for (EntityAnnotation label : labels) {
                message += String.format("%.3f: %s", label.getScore(), label.getDescription());
                message += "\n";
            }
        } else {
            message += "nothing";
        }

        return message;
    }
}

So the question is.. what is wrong with this code?

1 Answers1

0

Check this answer: https://stackoverflow.com/a/38131991/2734665 The image max file size is 4MB, the max request size is 8MB

Community
  • 1
  • 1
Mati Tucci
  • 2,826
  • 5
  • 28
  • 40