Search in sources :

Example 61 with BatchAnnotateImagesResponse

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse in project java-vision by googleapis.

the class AsyncBatchAnnotateImagesGcs method asyncBatchAnnotateImagesGcs.

// Performs asynchronous batch annotation of images on Google Cloud Storage
public static void asyncBatchAnnotateImagesGcs(String gcsSourcePath, String gcsDestinationPath) throws Exception {
    // String gcsDestinationPath = "gs://YOUR_BUCKET_ID/path_to_store_annotation";
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        List<AnnotateImageRequest> requests = new ArrayList<>();
        ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsSourcePath).build();
        Image image = Image.newBuilder().setSource(imgSource).build();
        // Set the GCS destination path for where to save the results.
        GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(gcsDestinationPath).build();
        // Create the configuration for the output with the batch size.
        // The batch size sets how many pages should be grouped into each json output file.
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(2).build();
        // Select the Features required by the vision API
        Feature features = Feature.newBuilder().setType(Type.LABEL_DETECTION).setType(Type.TEXT_DETECTION).setType(Type.IMAGE_PROPERTIES).build();
        // Build the request
        AnnotateImageRequest annotateImageRequest = AnnotateImageRequest.newBuilder().setImage(image).addFeatures(features).build();
        requests.add(annotateImageRequest);
        AsyncBatchAnnotateImagesRequest request = AsyncBatchAnnotateImagesRequest.newBuilder().addAllRequests(requests).setOutputConfig(outputConfig).build();
        OperationFuture<AsyncBatchAnnotateImagesResponse, OperationMetadata> response = client.asyncBatchAnnotateImagesAsync(request);
        System.out.println("Waiting for the operation to finish.");
        // we're not processing the response, since we'll be reading the output from GCS.
        response.get(180, TimeUnit.SECONDS);
        // Once the request has completed and the output has been
        // written to GCS, we can list all the output files.
        Storage storage = StorageOptions.getDefaultInstance().getService();
        // Get the destination location from the gcsDestinationPath
        Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)");
        Matcher matcher = pattern.matcher(gcsDestinationPath);
        if (matcher.find()) {
            String bucketName = matcher.group(1);
            String prefix = matcher.group(2);
            // Get the list of objects with the given prefix from the GCS bucket
            Bucket bucket = storage.get(bucketName);
            Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix));
            Blob firstOutputFile = null;
            // List objects with the given prefix.
            System.out.println("Output files:");
            for (Blob blob : pageList.iterateAll()) {
                System.out.println(blob.getName());
                // the first two image requests
                if (firstOutputFile == null) {
                    firstOutputFile = blob;
                }
            }
            // Get the contents of the file and convert the JSON contents to an
            // BatchAnnotateImagesResponse
            // object. If the Blob is small read all its content in one request
            // (Note: the file is a .json file)
            // Storage guide: https://cloud.google.com/storage/docs/downloading-objects
            String jsonContents = new String(firstOutputFile.getContent());
            Builder builder = BatchAnnotateImagesResponse.newBuilder();
            JsonFormat.parser().merge(jsonContents, builder);
            // Build the AnnotateFileResponse object
            BatchAnnotateImagesResponse batchAnnotateImagesResponse = builder.build();
            // Here we print the response for the first image
            // The response contains more information:
            // annotation/pages/blocks/paragraphs/words/symbols/colors
            // including confidence score and bounding boxes
            System.out.format("\nResponse: %s\n", batchAnnotateImagesResponse.getResponses(0));
        } else {
            System.out.println("No MATCH");
        }
    } catch (Exception e) {
        System.out.println("Error during asyncBatchAnnotateImagesGcs: \n" + e.toString());
    }
}
Also used : Pattern(java.util.regex.Pattern) Blob(com.google.cloud.storage.Blob) AsyncBatchAnnotateImagesRequest(com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest) Matcher(java.util.regex.Matcher) ImageAnnotatorClient(com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient) Builder(com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse.Builder) ArrayList(java.util.ArrayList) Image(com.google.cloud.vision.v1p4beta1.Image) Feature(com.google.cloud.vision.v1p4beta1.Feature) AnnotateImageRequest(com.google.cloud.vision.v1p4beta1.AnnotateImageRequest) OutputConfig(com.google.cloud.vision.v1p4beta1.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) AsyncBatchAnnotateImagesResponse(com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse) ImageSource(com.google.cloud.vision.v1p4beta1.ImageSource) GcsDestination(com.google.cloud.vision.v1p4beta1.GcsDestination) OperationMetadata(com.google.cloud.vision.v1p4beta1.OperationMetadata) AsyncBatchAnnotateImagesResponse(com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse) BatchAnnotateImagesResponse(com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse)

Example 62 with BatchAnnotateImagesResponse

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse in project java-vision by googleapis.

the class DetectBeta method detectHandwrittenOcrGcs.

// [END vision_handwritten_ocr_beta]
// [START vision_handwritten_ocr_gcs_beta]
/**
 * Performs handwritten text detection on a remote image on Google Cloud Storage.
 *
 * @param gcsPath The path to the remote file on Google Cloud Storage to detect handwritten text
 *     on.
 * @param out A {@link PrintStream} to write the results to.
 * @throws Exception on errors while closing the client.
 * @throws IOException on Input/Output errors.
 */
public static void detectHandwrittenOcrGcs(String gcsPath, PrintStream out) throws Exception {
    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.DOCUMENT_TEXT_DETECTION).build();
    // Set the parameters for the image
    ImageContext imageContext = ImageContext.newBuilder().addLanguageHints("en-t-i0-handwrit").build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).setImageContext(imageContext).build();
    requests.add(request);
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        client.close();
        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
            TextAnnotation annotation = res.getFullTextAnnotation();
            for (Page page : annotation.getPagesList()) {
                String pageText = "";
                for (Block block : page.getBlocksList()) {
                    String blockText = "";
                    for (Paragraph para : block.getParagraphsList()) {
                        String paraText = "";
                        for (Word word : para.getWordsList()) {
                            String wordText = "";
                            for (Symbol symbol : word.getSymbolsList()) {
                                wordText = wordText + symbol.getText();
                                out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(), symbol.getConfidence());
                            }
                            out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence());
                            paraText = String.format("%s %s", paraText, wordText);
                        }
                        // Output Example using Paragraph:
                        out.println("\nParagraph: \n" + paraText);
                        out.format("Paragraph Confidence: %f\n", para.getConfidence());
                        blockText = blockText + paraText;
                    }
                    pageText = pageText + blockText;
                }
            }
            out.println("\nComplete annotation:");
            out.println(annotation.getText());
        }
    }
}
Also used : Word(com.google.cloud.vision.v1p3beta1.Word) Symbol(com.google.cloud.vision.v1p3beta1.Symbol) ImageAnnotatorClient(com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) Page(com.google.cloud.vision.v1p3beta1.Page) ByteString(com.google.protobuf.ByteString) Image(com.google.cloud.vision.v1p3beta1.Image) Feature(com.google.cloud.vision.v1p3beta1.Feature) Paragraph(com.google.cloud.vision.v1p3beta1.Paragraph) AnnotateImageRequest(com.google.cloud.vision.v1p3beta1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1p3beta1.AnnotateImageResponse) Block(com.google.cloud.vision.v1p3beta1.Block) ImageSource(com.google.cloud.vision.v1p3beta1.ImageSource) TextAnnotation(com.google.cloud.vision.v1p3beta1.TextAnnotation) ImageContext(com.google.cloud.vision.v1p3beta1.ImageContext) BatchAnnotateImagesResponse(com.google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse)

Example 63 with BatchAnnotateImagesResponse

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse in project java-vision by googleapis.

the class DetectBeta method detectLocalizedObjects.

// [START vision_localize_objects_beta]
/**
 * Detects localized objects in the specified local image.
 *
 * @param filePath The path to the file to perform localized object detection on.
 * @param out A {@link PrintStream} to write detected objects to.
 * @throws Exception on errors while closing the client.
 * @throws IOException on Input/Output errors.
 */
public static void detectLocalizedObjects(String filePath, PrintStream out) throws Exception, IOException {
    List<AnnotateImageRequest> requests = new ArrayList<>();
    ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
    Image img = Image.newBuilder().setContent(imgBytes).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)).setImage(img).build();
    requests.add(request);
    // Perform the request
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        // Display the results
        for (AnnotateImageResponse res : responses) {
            for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) {
                out.format("Object name: %s\n", entity.getName());
                out.format("Confidence: %s\n", entity.getScore());
                out.format("Normalized Vertices:\n");
                entity.getBoundingPoly().getNormalizedVerticesList().forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY()));
            }
        }
    }
}
Also used : AnnotateImageRequest(com.google.cloud.vision.v1p3beta1.AnnotateImageRequest) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient) AnnotateImageResponse(com.google.cloud.vision.v1p3beta1.AnnotateImageResponse) ArrayList(java.util.ArrayList) LocalizedObjectAnnotation(com.google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation) Image(com.google.cloud.vision.v1p3beta1.Image) FileInputStream(java.io.FileInputStream) BatchAnnotateImagesResponse(com.google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse)

Example 64 with BatchAnnotateImagesResponse

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse in project java-vision by googleapis.

the class ProductSearch method getSimilarProductsFile.

// [START vision_product_search_get_similar_products]
/**
 * Search similar products to image in local file.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @param productCategory - Category of the product.
 * @param filePath - Local file path of the image to be searched
 * @param filter - Condition to be applied on the labels. Example for filter: (color = red OR
 *     color = blue) AND style = kids It will search on all products with the following labels:
 *     color:red AND style:kids color:blue AND style:kids
 * @throws IOException - on I/O errors.
 */
public static void getSimilarProductsFile(String projectId, String computeRegion, String productSetId, String productCategory, String filePath, String filter) throws IOException {
    try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) {
        // Get the full path of the product set.
        String productSetPath = ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);
        // Read the image as a stream of bytes.
        File imgPath = new File(filePath);
        byte[] content = Files.readAllBytes(imgPath.toPath());
        // Create annotate image request along with product search feature.
        Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build();
        // The input image can be a HTTPS link or Raw image bytes.
        // Example:
        // To use HTTP link replace with below code
        // ImageSource source = ImageSource.newBuilder().setImageUri(imageUri).build();
        // Image image = Image.newBuilder().setSource(source).build();
        Image image = Image.newBuilder().setContent(ByteString.copyFrom(content)).build();
        ImageContext imageContext = ImageContext.newBuilder().setProductSearchParams(ProductSearchParams.newBuilder().setProductSet(productSetPath).addProductCategories(productCategory).setFilter(filter)).build();
        AnnotateImageRequest annotateImageRequest = AnnotateImageRequest.newBuilder().addFeatures(featuresElement).setImage(image).setImageContext(imageContext).build();
        List<AnnotateImageRequest> requests = Arrays.asList(annotateImageRequest);
        // Search products similar to the image.
        BatchAnnotateImagesResponse response = queryImageClient.batchAnnotateImages(requests);
        List<Result> similarProducts = response.getResponses(0).getProductSearchResults().getResultsList();
        System.out.println("Similar Products: ");
        for (Result product : similarProducts) {
            System.out.println(String.format("\nProduct name: %s", product.getProduct().getName()));
            System.out.println(String.format("Product display name: %s", product.getProduct().getDisplayName()));
            System.out.println(String.format("Product description: %s", product.getProduct().getDescription()));
            System.out.println(String.format("Score(Confidence): %s", product.getScore()));
            System.out.println(String.format("Image name: %s", product.getImage()));
        }
    }
}
Also used : AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ByteString(com.google.protobuf.ByteString) Image(com.google.cloud.vision.v1.Image) File(java.io.File) Feature(com.google.cloud.vision.v1.Feature) ImageContext(com.google.cloud.vision.v1.ImageContext) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) Result(com.google.cloud.vision.v1.ProductSearchResults.Result)

Example 65 with BatchAnnotateImagesResponse

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse in project java-vision by googleapis.

the class DetectLogosGcs method detectLogosGcs.

// Detects logos in the specified remote image on Google Cloud Storage.
public static void detectLogosGcs(String gcsPath) 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(Feature.Type.LOGO_DETECTION).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
    requests.add(request);
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();
        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                System.out.format("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()) {
                System.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) 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)

Aggregations

BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)72 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)69 Image (com.google.cloud.vision.v1.Image)68 Feature (com.google.cloud.vision.v1.Feature)66 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)64 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)63 ArrayList (java.util.ArrayList)63 ByteString (com.google.protobuf.ByteString)44 ImageSource (com.google.cloud.vision.v1.ImageSource)37 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 ImageContext (com.google.cloud.vision.v1.ImageContext)12 WebDetection (com.google.cloud.vision.v1.WebDetection)11 LocationInfo (com.google.cloud.vision.v1.LocationInfo)10 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)10 WebPage (com.google.cloud.vision.v1.WebDetection.WebPage)9 Block (com.google.cloud.vision.v1.Block)8 ColorInfo (com.google.cloud.vision.v1.ColorInfo)8