/** * This method downloads an image from a URL and sends its contents to the Vision API for label detection. * * @param imageUrl the URL of the image * @param map the model map to use * @return a string with the list of labels and percentage of certainty * @throws CloudVisionTemplate if the Vision API call produces an error */ @GetMapping("/extractLabels") public ModelAndView extractLabels(String imageUrl, ModelMap map) { AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage( this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION); Map<String, Float> imageLabels = response.getLabelAnnotationsList() .stream() .collect(Collectors.toMap( EntityAnnotation::getDescription, EntityAnnotation::getScore)); map.addAttribute("annotations", imageLabels); map.addAttribute("imageUrl", imageUrl); return new ModelAndView("result", map); }
/** * Extract the text out of an image and return the result as a String. * @param imageResource the image one wishes to analyze * @return the text extracted from the image aggregated to a String * @throws CloudVisionException if the image could not be read or if text extraction failed */ public String extractTextFromImage(Resource imageResource) { AnnotateImageResponse response = analyzeImage(imageResource, Type.TEXT_DETECTION); String result = response.getFullTextAnnotation().getText(); if (result.isEmpty() && response.getError().getCode() != Code.OK.getNumber()) { throw new CloudVisionException(response.getError().getMessage()); } return result; }
/** * Extract the text out of an image and return the result as a String. * @param imageResource the image one wishes to analyze * @return the text extracted from the image aggregated to a String * @throws CloudVisionTemplate if the image could not be read or if text extraction failed */ public String extractTextFromImage(Resource imageResource) { AnnotateImageResponse response = analyzeImage(imageResource, Type.TEXT_DETECTION); String result = response.getFullTextAnnotation().getText(); if (result.isEmpty() && response.getError().getCode() != Code.OK.getNumber()) { throw new CloudVisionException(response.getError().getMessage()); } return result; }