Search in sources :

Example 56 with AnnotateImageRequest

use of com.google.cloud.vision.v1p4beta1.AnnotateImageRequest in project java-docs-samples by GoogleCloudPlatform.

the class Detect method detectPropertiesGcs.

/**
 * Detects image properties such as color frequency from the specified remote image on Google
 * Cloud Storage.
 *
 * @param gcsPath The path to the remote file on Google Cloud Storage to detect properties on.
 * @param out A {@link PrintStream} to write
 * @throws Exception on errors while closing the client.
 * @throws IOException on Input/Output errors.
 */
public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws Exception, 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.IMAGE_PROPERTIES).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
    requests.add(request);
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.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
            DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors();
            for (ColorInfo color : colors.getColorsList()) {
                out.printf("fraction: %f\nr: %f, g: %f, b: %f\n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), color.getColor().getBlue());
            }
        }
    }
}
Also used : AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ArrayList(java.util.ArrayList) ImageSource(com.google.cloud.vision.v1.ImageSource) DominantColorsAnnotation(com.google.cloud.vision.v1.DominantColorsAnnotation) WebImage(com.google.cloud.vision.v1.WebDetection.WebImage) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) ColorInfo(com.google.cloud.vision.v1.ColorInfo) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 57 with AnnotateImageRequest

use of com.google.cloud.vision.v1p4beta1.AnnotateImageRequest in project java-docs-samples by GoogleCloudPlatform.

the class Detect method detectLogosGcs.

/**
 * Detects logos in the specified remote image on Google Cloud Storage.
 *
 * @param gcsPath The path to the remote file on Google Cloud Storage to perform logo detection
 *                on.
 * @param out A {@link PrintStream} to write detected logos to.
 * @throws Exception on errors while closing the client.
 * @throws IOException on Input/Output errors.
 */
public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception, 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);
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.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());
            }
        }
    }
}
Also used : AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ArrayList(java.util.ArrayList) ImageSource(com.google.cloud.vision.v1.ImageSource) WebImage(com.google.cloud.vision.v1.WebDetection.WebImage) Image(com.google.cloud.vision.v1.Image) EntityAnnotation(com.google.cloud.vision.v1.EntityAnnotation) Feature(com.google.cloud.vision.v1.Feature) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 58 with AnnotateImageRequest

use of com.google.cloud.vision.v1p4beta1.AnnotateImageRequest in project java-docs-samples by GoogleCloudPlatform.

the class QuickstartSample method main.

public static void main(String... args) throws Exception {
    // Instantiates a client
    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.printf("Error: %s\n", res.getError().getMessage());
                return;
            }
            for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                annotation.getAllFields().forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) EntityAnnotation(com.google.cloud.vision.v1.EntityAnnotation) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 59 with AnnotateImageRequest

use of com.google.cloud.vision.v1p4beta1.AnnotateImageRequest in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagick method blurOffensiveImages.

// [END run_imageproc_handler_setup]
// [END cloudrun_imageproc_handler_setup]
// [START cloudrun_imageproc_handler_analyze]
// [START run_imageproc_handler_analyze]
// Blurs uploaded images that are flagged as Adult or Violence.
public static void blurOffensiveImages(JsonObject data) {
    String fileName = data.get("name").getAsString();
    String bucketName = data.get("bucket").getAsString();
    BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileName).build();
    // Construct URI to GCS bucket and file.
    String gcsPath = String.format("gs://%s/%s", bucketName, fileName);
    System.out.println(String.format("Analyzing %s", fileName));
    // Construct request.
    List<AnnotateImageRequest> requests = new ArrayList<>();
    ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
    requests.add(request);
    // Send request to the Vision API.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                System.out.println(String.format("Error: %s\n", res.getError().getMessage()));
                return;
            }
            // Get Safe Search Annotations
            SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
            if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
                System.out.println(String.format("Detected %s as inappropriate.", fileName));
                blur(blobInfo);
            } else {
                System.out.println(String.format("Detected %s as OK.", fileName));
            }
        }
    } catch (Exception e) {
        System.out.println(String.format("Error with Vision API: %s", e.getMessage()));
    }
}
Also used : SafeSearchAnnotation(com.google.cloud.vision.v1.SafeSearchAnnotation) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) BlobInfo(com.google.cloud.storage.BlobInfo) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) IOException(java.io.IOException) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 60 with AnnotateImageRequest

use of com.google.cloud.vision.v1p4beta1.AnnotateImageRequest in project java-docs-samples by GoogleCloudPlatform.

the class OcrProcessImage method detectText.

// [END functions_ocr_process]
// [START functions_ocr_detect]
private void detectText(String bucket, String filename) {
    logger.info("Looking for text in image " + filename);
    List<AnnotateImageRequest> visionRequests = new ArrayList<>();
    String gcsPath = String.format("gs://%s/%s", bucket, filename);
    ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature textFeature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
    AnnotateImageRequest visionRequest = AnnotateImageRequest.newBuilder().addFeatures(textFeature).setImage(img).build();
    visionRequests.add(visionRequest);
    // Detect text in an image using the Cloud Vision API
    AnnotateImageResponse visionResponse;
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        visionResponse = client.batchAnnotateImages(visionRequests).getResponses(0);
        if (visionResponse == null || !visionResponse.hasFullTextAnnotation()) {
            logger.info(String.format("Image %s contains no text", filename));
            return;
        }
        if (visionResponse.hasError()) {
            // Log error
            logger.log(Level.SEVERE, "Error in vision API call: " + visionResponse.getError().getMessage());
            return;
        }
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a Cloud Function)
        logger.log(Level.SEVERE, "Error detecting text: " + e.getMessage(), e);
        return;
    }
    String text = visionResponse.getFullTextAnnotation().getText();
    logger.info("Extracted text from image: " + text);
    // Detect language using the Cloud Translation API
    DetectLanguageRequest languageRequest = DetectLanguageRequest.newBuilder().setParent(LOCATION_NAME).setMimeType("text/plain").setContent(text).build();
    DetectLanguageResponse languageResponse;
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
        languageResponse = client.detectLanguage(languageRequest);
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a function)
        logger.log(Level.SEVERE, "Error detecting language: " + e.getMessage(), e);
        return;
    }
    if (languageResponse.getLanguagesCount() == 0) {
        logger.info("No languages were detected for text: " + text);
        return;
    }
    String languageCode = languageResponse.getLanguages(0).getLanguageCode();
    logger.info(String.format("Detected language %s for file %s", languageCode, filename));
    // Send a Pub/Sub translation request for every language we're going to translate to
    for (String targetLanguage : TO_LANGS) {
        logger.info("Sending translation request for language " + targetLanguage);
        OcrTranslateApiMessage message = new OcrTranslateApiMessage(text, filename, targetLanguage);
        ByteString byteStr = ByteString.copyFrom(message.toPubsubData());
        PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
        try {
            publisher.publish(pubsubApiMessage).get();
        } catch (InterruptedException | ExecutionException e) {
            // Log error
            logger.log(Level.SEVERE, "Error publishing translation request: " + e.getMessage(), e);
            return;
        }
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) DetectLanguageResponse(com.google.cloud.translate.v3.DetectLanguageResponse) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) DetectLanguageRequest(com.google.cloud.translate.v3.DetectLanguageRequest) PubsubMessage(com.google.pubsub.v1.PubsubMessage) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)77 Image (com.google.cloud.vision.v1.Image)71 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)69 Feature (com.google.cloud.vision.v1.Feature)69 ArrayList (java.util.ArrayList)66 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)65 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)62 ByteString (com.google.protobuf.ByteString)44 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)13 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)11 WebDetection (com.google.cloud.vision.v1.WebDetection)11 ImageContext (com.google.cloud.vision.v1.ImageContext)10 LocationInfo (com.google.cloud.vision.v1.LocationInfo)10 Test (org.junit.Test)10 CropHint (com.google.cloud.vision.v1.CropHint)9 WebPage (com.google.cloud.vision.v1.WebDetection.WebPage)9