Search in sources :

Example 91 with Image

use of com.google.cloud.vision.v1p3beta1.Image in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method analyzeFile.

/**
 * Analyze a file and extract the features of the image specified by {@code featureTypes}.
 *
 * <p>A feature describes the kind of Cloud Vision analysis one wishes to perform on a file, such
 * as text detection, image labelling, facial detection, etc. A full list of feature types can be
 * found in {@link Feature.Type}.
 *
 * @param fileResource the file one wishes to analyze. The Cloud Vision APIs support image formats
 *     described here: https://cloud.google.com/vision/docs/supported-files. Documents with more
 *     than 5 pages are not supported.
 * @param mimeType the mime type of the fileResource. Currently, only "application/pdf",
 *     "image/tiff" and "image/gif" are supported.
 * @param featureTypes the types of image analysis to perform on the image
 * @return the results of file analyse
 * @throws CloudVisionException if the file could not be read or if a malformed response is
 *     received from the Cloud Vision APIs
 */
public AnnotateFileResponse analyzeFile(Resource fileResource, String mimeType, Feature.Type... featureTypes) {
    ByteString imgBytes;
    try {
        imgBytes = ByteString.readFrom(fileResource.getInputStream());
    } catch (IOException ex) {
        throw new CloudVisionException(READ_BYTES_ERROR_MESSAGE, ex);
    }
    InputConfig inputConfig = InputConfig.newBuilder().setMimeType(mimeType).setContent(imgBytes).build();
    List<Feature> featureList = Arrays.stream(featureTypes).map(featureType -> Feature.newBuilder().setType(featureType).build()).collect(Collectors.toList());
    BatchAnnotateFilesRequest request = BatchAnnotateFilesRequest.newBuilder().addRequests(AnnotateFileRequest.newBuilder().addAllFeatures(featureList).setInputConfig(inputConfig).build()).build();
    BatchAnnotateFilesResponse response = this.imageAnnotatorClient.batchAnnotateFiles(request);
    List<AnnotateFileResponse> annotateFileResponses = response.getResponsesList();
    if (!annotateFileResponses.isEmpty()) {
        return annotateFileResponses.get(0);
    } else {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) ByteString(com.google.protobuf.ByteString) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) IOException(java.io.IOException) Feature(com.google.cloud.vision.v1.Feature)

Example 92 with Image

use of com.google.cloud.vision.v1p3beta1.Image in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method analyzeImage.

/**
 * Analyze an image and extract the features of the image specified by {@code featureTypes}.
 *
 * <p>A feature describes the kind of Cloud Vision analysis one wishes to perform on an image,
 * such as text detection, image labelling, facial detection, etc. A full list of feature types
 * can be found in {@link Feature.Type}.
 *
 * @param imageResource the image one wishes to analyze. The Cloud Vision APIs support image
 *     formats described here: https://cloud.google.com/vision/docs/supported-files
 * @param imageContext the image context used to customize the Vision API request
 * @param featureTypes the types of image analysis to perform on the image
 * @return the results of image analyses
 * @throws CloudVisionException if the image could not be read or if a malformed response is
 *     received from the Cloud Vision APIs
 */
public AnnotateImageResponse analyzeImage(Resource imageResource, ImageContext imageContext, Feature.Type... featureTypes) {
    ByteString imgBytes;
    try {
        imgBytes = ByteString.readFrom(imageResource.getInputStream());
    } catch (IOException ex) {
        throw new CloudVisionException(READ_BYTES_ERROR_MESSAGE, ex);
    }
    Image image = Image.newBuilder().setContent(imgBytes).build();
    List<Feature> featureList = Arrays.stream(featureTypes).map(featureType -> Feature.newBuilder().setType(featureType).build()).collect(Collectors.toList());
    BatchAnnotateImagesRequest request = BatchAnnotateImagesRequest.newBuilder().addRequests(AnnotateImageRequest.newBuilder().addAllFeatures(featureList).setImageContext(imageContext).setImage(image)).build();
    BatchAnnotateImagesResponse batchResponse = this.imageAnnotatorClient.batchAnnotateImages(request);
    List<AnnotateImageResponse> annotateImageResponses = batchResponse.getResponsesList();
    if (!annotateImageResponses.isEmpty()) {
        return annotateImageResponses.get(0);
    } else {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) ByteString(com.google.protobuf.ByteString) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 93 with Image

use of com.google.cloud.vision.v1p3beta1.Image in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method extractTextFromFile.

/**
 * Extract the text out of a file and return the result as a String.
 *
 * @param fileResource the file one wishes to analyze
 * @param mimeType the mime type of the fileResource. Currently, only "application/pdf",
 *     "image/tiff" and "image/gif" are supported.
 * @return the text extracted from the pdf as a string per page
 * @throws CloudVisionException if the image could not be read or if text extraction failed
 */
public List<String> extractTextFromFile(Resource fileResource, String mimeType) {
    AnnotateFileResponse response = analyzeFile(fileResource, mimeType, Type.DOCUMENT_TEXT_DETECTION);
    List<AnnotateImageResponse> annotateImageResponses = response.getResponsesList();
    if (annotateImageResponses.isEmpty()) {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
    List<String> result = annotateImageResponses.stream().map(annotateImageResponse -> annotateImageResponse.getFullTextAnnotation().getText()).collect(Collectors.toList());
    if (result.isEmpty() && response.getError().getCode() != Code.OK.getNumber()) {
        throw new CloudVisionException(response.getError().getMessage());
    }
    return result;
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ByteString(com.google.protobuf.ByteString)

Example 94 with Image

use of com.google.cloud.vision.v1p3beta1.Image in project java-automl by googleapis.

the class VisionClassificationPredict method predict.

static void predict(String projectId, String modelId, String filePath) throws IOException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
        // Get the full path of the model.
        ModelName name = ModelName.of(projectId, "us-central1", modelId);
        ByteString content = ByteString.copyFrom(Files.readAllBytes(Paths.get(filePath)));
        Image image = Image.newBuilder().setImageBytes(content).build();
        ExamplePayload payload = ExamplePayload.newBuilder().setImage(image).build();
        PredictRequest predictRequest = PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).putParams("score_threshold", // [0.0-1.0] Only produce results higher than this value
        "0.8").build();
        PredictResponse response = client.predict(predictRequest);
        for (AnnotationPayload annotationPayload : response.getPayloadList()) {
            System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
            System.out.format("Predicted class score: %.2f\n", annotationPayload.getClassification().getScore());
        }
    }
}
Also used : ModelName(com.google.cloud.automl.v1.ModelName) ByteString(com.google.protobuf.ByteString) PredictResponse(com.google.cloud.automl.v1.PredictResponse) ExamplePayload(com.google.cloud.automl.v1.ExamplePayload) Image(com.google.cloud.automl.v1.Image) PredictRequest(com.google.cloud.automl.v1.PredictRequest) PredictionServiceClient(com.google.cloud.automl.v1.PredictionServiceClient) AnnotationPayload(com.google.cloud.automl.v1.AnnotationPayload)

Example 95 with Image

use of com.google.cloud.vision.v1p3beta1.Image in project java-automl by googleapis.

the class VisionObjectDetectionPredict method predict.

static void predict(String projectId, String modelId, String filePath) throws IOException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
        // Get the full path of the model.
        ModelName name = ModelName.of(projectId, "us-central1", modelId);
        ByteString content = ByteString.copyFrom(Files.readAllBytes(Paths.get(filePath)));
        Image image = Image.newBuilder().setImageBytes(content).build();
        ExamplePayload payload = ExamplePayload.newBuilder().setImage(image).build();
        PredictRequest predictRequest = PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).putParams("score_threshold", // [0.0-1.0] Only produce results higher than this value
        "0.5").build();
        PredictResponse response = client.predict(predictRequest);
        for (AnnotationPayload annotationPayload : response.getPayloadList()) {
            System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
            System.out.format("Predicted class score: %.2f\n", annotationPayload.getImageObjectDetection().getScore());
            BoundingPoly boundingPoly = annotationPayload.getImageObjectDetection().getBoundingBox();
            System.out.println("Normalized Vertices:");
            for (NormalizedVertex vertex : boundingPoly.getNormalizedVerticesList()) {
                System.out.format("\tX: %.2f, Y: %.2f\n", vertex.getX(), vertex.getY());
            }
        }
    }
}
Also used : ModelName(com.google.cloud.automl.v1.ModelName) ByteString(com.google.protobuf.ByteString) PredictResponse(com.google.cloud.automl.v1.PredictResponse) BoundingPoly(com.google.cloud.automl.v1.BoundingPoly) ExamplePayload(com.google.cloud.automl.v1.ExamplePayload) Image(com.google.cloud.automl.v1.Image) PredictRequest(com.google.cloud.automl.v1.PredictRequest) PredictionServiceClient(com.google.cloud.automl.v1.PredictionServiceClient) AnnotationPayload(com.google.cloud.automl.v1.AnnotationPayload) NormalizedVertex(com.google.cloud.automl.v1.NormalizedVertex)

Aggregations

AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)75 Image (com.google.cloud.vision.v1.Image)75 Feature (com.google.cloud.vision.v1.Feature)73 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)72 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)69 ArrayList (java.util.ArrayList)69 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)66 ByteString (com.google.protobuf.ByteString)52 ImageSource (com.google.cloud.vision.v1.ImageSource)41 FileInputStream (java.io.FileInputStream)32 EntityAnnotation (com.google.cloud.vision.v1.EntityAnnotation)28 WebImage (com.google.cloud.vision.v1.WebDetection.WebImage)26 IOException (java.io.IOException)20 ImageContext (com.google.cloud.vision.v1.ImageContext)14 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)11 WebDetection (com.google.cloud.vision.v1.WebDetection)11 LocationInfo (com.google.cloud.vision.v1.LocationInfo)10 Arrays (java.util.Arrays)10 Image (com.google.cloud.compute.v1.Image)9 ImagesClient (com.google.cloud.compute.v1.ImagesClient)9