Search in sources :

Example 11 with ImageContext

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

the class CloudVisionTemplateTests method testAddImageContext_analyzeImage.

@Test
void testAddImageContext_analyzeImage() throws IOException {
    when(this.imageAnnotatorClient.batchAnnotateImages(any(BatchAnnotateImagesRequest.class))).thenReturn(DEFAULT_API_RESPONSE);
    ImageContext imageContext = Mockito.mock(ImageContext.class);
    this.cloudVisionTemplate.analyzeImage(FAKE_IMAGE, imageContext, Type.FACE_DETECTION);
    BatchAnnotateImagesRequest expectedRequest = BatchAnnotateImagesRequest.newBuilder().addRequests(AnnotateImageRequest.newBuilder().addFeatures(Feature.newBuilder().setType(Type.FACE_DETECTION)).setImageContext(imageContext).setImage(Image.newBuilder().setContent(ByteString.readFrom(FAKE_IMAGE.getInputStream())).build())).build();
    verify(this.imageAnnotatorClient, times(1)).batchAnnotateImages(expectedRequest);
}
Also used : BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) ImageContext(com.google.cloud.vision.v1.ImageContext) Test(org.junit.jupiter.api.Test)

Example 12 with ImageContext

use of com.google.cloud.vision.v1p3beta1.ImageContext 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 13 with ImageContext

use of com.google.cloud.vision.v1p3beta1.ImageContext 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 14 with ImageContext

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

the class DetectWebEntitiesIncludeGeoResults method detectWebEntitiesIncludeGeoResults.

// Find web entities given a local image.
public static void detectWebEntitiesIncludeGeoResults(String filePath) throws IOException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        // Read in the local image
        ByteString contents = ByteString.readFrom(new FileInputStream(filePath));
        // Build the image
        Image image = Image.newBuilder().setContent(contents).build();
        // Enable `IncludeGeoResults`
        WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder().setIncludeGeoResults(true).build();
        // Set the parameters for the image
        ImageContext imageContext = ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build();
        // Create the request with the image, imageContext, and the specified feature: web detection
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)).setImage(image).setImageContext(imageContext).build();
        // Perform the request
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));
        // Display the results
        response.getResponsesList().stream().forEach(r -> r.getWebDetection().getWebEntitiesList().stream().forEach(entity -> {
            System.out.format("Description: %s%n", entity.getDescription());
            System.out.format("Score: %f%n", entity.getScore());
        }));
    }
}
Also used : WebDetectionParams(com.google.cloud.vision.v1.WebDetectionParams) WebDetectionParams(com.google.cloud.vision.v1.WebDetectionParams) ByteString(com.google.protobuf.ByteString) Arrays(java.util.Arrays) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Type(com.google.cloud.vision.v1.Feature.Type) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Feature(com.google.cloud.vision.v1.Feature) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Image(com.google.cloud.vision.v1.Image) FileInputStream(java.io.FileInputStream) ImageContext(com.google.cloud.vision.v1.ImageContext) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 15 with ImageContext

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

the class ITSystemTest method detectWebEntitiesIncludeGeoResultsTest.

@Test
public void detectWebEntitiesIncludeGeoResultsTest() throws IOException {
    ByteString imgBytes = ByteString.readFrom(new FileInputStream(RESOURCES + "city.jpg"));
    Image img = Image.newBuilder().setContent(imgBytes).build();
    Feature feat = Feature.newBuilder().setType(Type.WEB_DETECTION).setMaxResults(MAX_RESULTS).build();
    WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder().setIncludeGeoResults(true).build();
    ImageContext imageContext = ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build();
    AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImageContext(imageContext).setImage(img).build();
    BatchAnnotateImagesResponse response = imageAnnotatorClient.batchAnnotateImages(ImmutableList.of(request));
    List<AnnotateImageResponse> responses = response.getResponsesList();
    List<String> actual = new ArrayList<>();
    for (AnnotateImageResponse imgResponse : responses) {
        for (WebDetection.WebEntity entity : imgResponse.getWebDetection().getWebEntitiesList()) {
            actual.add(entity.getDescription());
        }
    }
    List<String> expectedResults = new ArrayList<>();
    expectedResults.add("Electra Tower");
    expectedResults.add("Metropolitan area");
    assertThat(actual).containsAnyIn(expectedResults);
}
Also used : WebDetectionParams(com.google.cloud.vision.v1.WebDetectionParams) WebDetection(com.google.cloud.vision.v1.WebDetection) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) ReferenceImage(com.google.cloud.vision.v1.ReferenceImage) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) FileInputStream(java.io.FileInputStream) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageContext(com.google.cloud.vision.v1.ImageContext) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) Test(org.junit.Test)

Aggregations

ImageContext (com.google.cloud.vision.v1.ImageContext)14 ByteString (com.google.protobuf.ByteString)11 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)10 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)10 Feature (com.google.cloud.vision.v1.Feature)10 Image (com.google.cloud.vision.v1.Image)10 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)8 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)6 BatchAnnotateImagesRequest (com.google.cloud.vision.v1.BatchAnnotateImagesRequest)6 WebDetectionParams (com.google.cloud.vision.v1.WebDetectionParams)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Arrays (java.util.Arrays)6 Type (com.google.cloud.vision.v1.Feature.Type)5 ImageSource (com.google.cloud.vision.v1.ImageSource)5 FileInputStream (java.io.FileInputStream)5 WebDetection (com.google.cloud.vision.v1.WebDetection)4 List (java.util.List)3 Test (org.junit.Test)3 Block (com.google.cloud.vision.v1.Block)2