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);
}
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());
}
}
}
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()));
}
}
}
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());
}));
}
}
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);
}
Aggregations