com.google.cloud.vision.v1.ImageSource Java Examples
The following examples show how to use
com.google.cloud.vision.v1.ImageSource.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DetectLandmarksUrl.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectLandmarksUrl(String uri) throws IOException { List<AnnotateImageRequest> requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setImageUri(uri).build(); Image img = Image.newBuilder().setSource(imgSource).build(); Feature feat = Feature.newBuilder().setType(Feature.Type.LANDMARK_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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.getLandmarkAnnotationsList()) { LocationInfo info = annotation.getLocationsList().listIterator().next(); System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } }
Example #2
Source File: GoogleVisionCache.java From TweetwallFX with MIT License | 5 votes |
private AnnotateImageRequest createImageRequest(final String imageUri) { final AnnotateImageRequest.Builder builder = AnnotateImageRequest.newBuilder() .setImage(Image.newBuilder() .setSource(ImageSource.newBuilder() .setImageUri(imageUri))); GOOGLE_SETTINGS.getCloudVision().getFeatureTypes().stream() .map(GoogleVisionCache::convertFeatureType) .forEach(builder.addFeaturesBuilder()::setType); return builder.build(); }
Example #3
Source File: ImageMagick.java From java-docs-samples with Apache License 2.0 | 5 votes |
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())); } }
Example #4
Source File: DetectFacesGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectFacesGcs(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.FACE_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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 (FaceAnnotation annotation : res.getFaceAnnotationsList()) { System.out.format( "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", annotation.getAngerLikelihood(), annotation.getJoyLikelihood(), annotation.getSurpriseLikelihood(), annotation.getBoundingPoly()); } } } }
Example #5
Source File: DetectLogosGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
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); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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()); } } } }
Example #6
Source File: SetEndpoint.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void setEndpoint() throws IOException { // [START vision_set_endpoint] ImageAnnotatorSettings settings = ImageAnnotatorSettings.newBuilder().setEndpoint("eu-vision.googleapis.com:443").build(); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. ImageAnnotatorClient client = ImageAnnotatorClient.create(settings); // [END vision_set_endpoint] ImageSource imgSource = ImageSource.newBuilder() .setGcsImageUri("gs://cloud-samples-data/vision/text/screen.jpg") .build(); Image image = Image.newBuilder().setSource(imgSource).build(); Feature feature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(image).build(); List<AnnotateImageRequest> requests = new ArrayList<>(); requests.add(request); BatchAnnotateImagesResponse batchResponse = client.batchAnnotateImages(requests); for (AnnotateImageResponse response : batchResponse.getResponsesList()) { for (EntityAnnotation annotation : response.getTextAnnotationsList()) { System.out.format("Text: %s%n", annotation.getDescription()); System.out.println("Position:"); System.out.format("%s%n", annotation.getBoundingPoly()); } } client.close(); }
Example #7
Source File: DetectLabelsGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectLabelsGcs(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.LABEL_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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.getLabelAnnotationsList()) { annotation .getAllFields() .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); } } } }
Example #8
Source File: DetectSafeSearchGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectSafeSearchGcs(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(Type.SAFE_SEARCH_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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 SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); System.out.format( "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), annotation.getSpoof(), annotation.getViolence(), annotation.getRacy()); } } }
Example #9
Source File: CloudVision.java From beam with Apache License 2.0 | 5 votes |
/** * Maps the {@link String} with encoded image data and the optional {@link ImageContext} into an * {@link AnnotateImageRequest}. * * @param uri Input element. * @param ctx optional image context. * @return a valid request. */ @Override public AnnotateImageRequest mapToRequest(String uri, @Nullable ImageContext ctx) { AnnotateImageRequest.Builder builder = AnnotateImageRequest.newBuilder(); if (ctx != null) { builder.setImageContext(ctx); } ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(uri).build(); return builder .addAllFeatures(featureList) .setImage(Image.newBuilder().setSource(imgSource).build()) .build(); }
Example #10
Source File: DetectPropertiesGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectPropertiesGcs(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.IMAGE_PROPERTIES).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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 DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); for (ColorInfo color : colors.getColorsList()) { System.out.format( "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), color.getColor().getBlue()); } } } }
Example #11
Source File: DetectLandmarksGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectLandmarksGcs(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.LANDMARK_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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.getLandmarkAnnotationsList()) { LocationInfo info = annotation.getLocationsList().listIterator().next(); System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } }
Example #12
Source File: DetectCropHintsGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectCropHintsGcs(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.CROP_HINTS).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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 CropHintsAnnotation annotation = res.getCropHintsAnnotation(); for (CropHint hint : annotation.getCropHintsList()) { System.out.println(hint.getBoundingPoly()); } } } }
Example #13
Source File: DetectTextGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectTextGcs(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.TEXT_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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.getTextAnnotationsList()) { System.out.format("Text: %s%n", annotation.getDescription()); System.out.format("Position : %s%n", annotation.getBoundingPoly()); } } } }
Example #14
Source File: DetectWebEntitiesGcs.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void detectWebEntitiesGcs(String gcsPath) throws IOException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Set the image source to the given gs uri ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); // Build the image Image image = Image.newBuilder().setSource(imageSource).build(); // Create the request with the image and the specified feature: web detection AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(Feature.newBuilder().setType(Feature.Type.WEB_DETECTION)) .setImage(image) .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()); })); } }
Example #15
Source File: Detect.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Detects localized objects in a remote image on Google Cloud Storage. * * @param gcsPath The path to the remote file on Google Cloud Storage to detect localized objects * on. * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ public static void detectLocalizedObjectsGcs(String gcsPath) throws IOException { List<AnnotateImageRequest> requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); Image img = Image.newBuilder().setSource(imgSource).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) .setImage(img) .build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Perform the request BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List<AnnotateImageResponse> responses = response.getResponsesList(); client.close(); // Display the results for (AnnotateImageResponse res : responses) { for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) { System.out.format("Object name: %s%n", entity.getName()); System.out.format("Confidence: %s%n", entity.getScore()); System.out.format("Normalized Vertices:%n"); entity .getBoundingPoly() .getNormalizedVerticesList() .forEach(vertex -> System.out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); } } } }
Example #16
Source File: CloudVision.java From beam with Apache License 2.0 | 5 votes |
/** * Maps {@link KV} of {@link String} (GCS URI to the image) and {@link ImageContext} to a valid * {@link AnnotateImageRequest}. * * @param input Input element. * @param ctx optional image context, ignored here since the input holds context. * @return a valid request. */ @Override public AnnotateImageRequest mapToRequest( KV<String, ImageContext> input, @Nullable ImageContext ctx) { ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(input.getKey()).build(); Image image = Image.newBuilder().setSource(imageSource).build(); AnnotateImageRequest.Builder builder = AnnotateImageRequest.newBuilder().setImage(image).addAllFeatures(featureList); if (input.getValue() != null) { builder.setImageContext(input.getValue()); } return builder.build(); }
Example #17
Source File: DetectWebEntitiesIncludeGeoResultsGcs.java From java-docs-samples with Apache License 2.0 | 4 votes |
public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath) throws IOException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Set the image source to the given gs uri ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); // Build the image Image image = Image.newBuilder().setSource(imageSource).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(Feature.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()); })); } }
Example #18
Source File: AsyncBatchAnnotateImages.java From java-docs-samples with Apache License 2.0 | 4 votes |
public static void asyncBatchAnnotateImages(String inputImageUri, String outputUri) throws IOException, ExecutionException, InterruptedException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) { // You can send multiple images to be annotated, this sample demonstrates how to do this with // one image. If you want to use multiple images, you have to create a `AnnotateImageRequest` // object for each image that you want annotated. // First specify where the vision api can find the image ImageSource source = ImageSource.newBuilder().setImageUri(inputImageUri).build(); Image image = Image.newBuilder().setSource(source).build(); // Set the type of annotation you want to perform on the image // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); // Build the request object for that one image. Note: for additional images you have to create // additional `AnnotateImageRequest` objects and store them in a list to be used below. AnnotateImageRequest imageRequest = AnnotateImageRequest.newBuilder().setImage(image).addFeatures(feature).build(); // Set where to store the results for the images that will be annotated. GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputUri).build(); OutputConfig outputConfig = OutputConfig.newBuilder() .setGcsDestination(gcsDestination) .setBatchSize(2) // The max number of responses to output in each JSON file .build(); // Add each `AnnotateImageRequest` object to the batch request and add the output config. AsyncBatchAnnotateImagesRequest request = AsyncBatchAnnotateImagesRequest.newBuilder() .addRequests(imageRequest) .setOutputConfig(outputConfig) .build(); // Make the asynchronous batch request. AsyncBatchAnnotateImagesResponse response = imageAnnotatorClient.asyncBatchAnnotateImagesAsync(request).get(); // The output is written to GCS with the provided output_uri as prefix String gcsOutputUri = response.getOutputConfig().getGcsDestination().getUri(); System.out.format("Output written to GCS with prefix: %s%n", gcsOutputUri); } }
Example #19
Source File: ProductSearch.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** * Search similar products to image in Google Cloud Storage. * * @param projectId - Id of the project. * @param computeRegion - Region name. * @param productSetId - Id of the product set. * @param productCategory - Category of the product. * @param gcsUri - GCS 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 Exception - on errors. */ public static void getSimilarProductsGcs( String projectId, String computeRegion, String productSetId, String productCategory, String gcsUri, String filter) throws Exception { try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) { // Get the full path of the product set. String productSetPath = ProductSetName.of(projectId, computeRegion, productSetId).toString(); // Get the image from Google Cloud Storage ImageSource source = ImageSource.newBuilder().setGcsImageUri(gcsUri).build(); // Create annotate image request along with product search feature. Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build(); Image image = Image.newBuilder().setSource(source).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())); } } }
Example #20
Source File: ImageMagick.java From java-docs-samples with Apache License 2.0 | 4 votes |
@Override // Blurs uploaded images that are flagged as Adult or Violence. public void accept(GcsEvent gcsEvent, Context context) { // Validate parameters if (gcsEvent.getBucket() == null || gcsEvent.getName() == null) { logger.severe("Error: Malformed GCS event."); return; } BlobInfo blobInfo = BlobInfo.newBuilder(gcsEvent.getBucket(), gcsEvent.getName()).build(); // Construct URI to GCS bucket and file. String gcsPath = String.format("gs://%s/%s", gcsEvent.getBucket(), gcsEvent.getName()); logger.info(String.format("Analyzing %s", gcsEvent.getName())); // Construct request. 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(); List<AnnotateImageRequest> requests = List.of(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()) { logger.info(String.format("Error: %s", res.getError().getMessage())); return; } // Get Safe Search Annotations SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) { logger.info(String.format("Detected %s as inappropriate.", gcsEvent.getName())); blur(blobInfo); } else { logger.info(String.format("Detected %s as OK.", gcsEvent.getName())); } } } catch (IOException e) { logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e); } }
Example #21
Source File: Detect.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** * Performs document text detection on a remote image on Google Cloud Storage. * * @param gcsPath The path to the remote file on Google Cloud Storage to detect document text on. * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ // [START vision_fulltext_detection_gcs] public static void detectDocumentTextGcs(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(Type.DOCUMENT_TEXT_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // 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(); client.close(); 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 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(); System.out.format( "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } System.out.format( "Word text: %s (confidence: %f)%n%n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: System.out.println("%nParagraph: %n" + paraText); System.out.format("Paragraph Confidence: %f%n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } System.out.println("%nComplete annotation:"); System.out.println(annotation.getText()); } } }