use of com.google.cloud.vision.v1p4beta1.Image in project java-automl by googleapis.
the class PredictionApi method predict.
// [START automl_vision_predict]
/**
* Demonstrates using the AutoML client to predict an image.
*
* @param projectId the Id of the project.
* @param computeRegion the Region name.
* @param modelId the Id of the model which will be used for text classification.
* @param filePath the Local text file path of the content to be classified.
* @param scoreThreshold the Confidence score. Only classifications with confidence score above
* scoreThreshold are displayed.
*/
static void predict(String projectId, String computeRegion, String modelId, String filePath, String scoreThreshold) {
// Instantiate client for prediction service.
try (PredictionServiceClient predictionClient = PredictionServiceClient.create()) {
// Get the full path of the model.
ModelName name = ModelName.of(projectId, computeRegion, modelId);
// Read the image and assign to payload.
ByteString content = ByteString.copyFrom(Files.readAllBytes(Paths.get(filePath)));
Image image = Image.newBuilder().setImageBytes(content).build();
ExamplePayload examplePayload = ExamplePayload.newBuilder().setImage(image).build();
// Additional parameters that can be provided for prediction e.g. Score Threshold
Map<String, String> params = new HashMap<>();
if (scoreThreshold != null) {
params.put("score_threshold", scoreThreshold);
}
// Perform the AutoML Prediction request
PredictResponse response = predictionClient.predict(name, examplePayload, params);
System.out.println("Prediction results:");
for (AnnotationPayload annotationPayload : response.getPayloadList()) {
System.out.println("Predicted class name :" + annotationPayload.getDisplayName());
System.out.println("Predicted class score :" + annotationPayload.getClassification().getScore());
}
} catch (IOException e) {
e.printStackTrace();
}
}
use of com.google.cloud.vision.v1p4beta1.Image in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class ImageIT method setupBeforeEach.
@BeforeEach
public void setupBeforeEach() throws ClientException {
clientlibs = Commons.CLIENTLIBS_IMAGE_V3;
imageTests = new ImageTests();
imageTests.setup(adminClient, contextPath, label, Commons.RT_IMAGE_V3, rootPage, defaultPageTemplate, clientlibs, new Image());
}
use of com.google.cloud.vision.v1p4beta1.Image in project kramerius by ceskaexpedice.
the class IiifAPI method manifest.
@GET
@Path("{pid}/manifest")
@Produces({ MediaType.APPLICATION_JSON + ";charset=utf-8" })
public Response manifest(@PathParam("pid") String pid) {
checkPid(pid);
try {
DocumentDto document = getIiifDocument(pid);
PropertyValue titleLabel = new PropertyValueSimpleImpl(document.getTitle());
Manifest manifest = new ManifestImpl(UriBuilder.fromUri(iiifUri).path(getClass(), "manifest").build(pid), titleLabel);
List<String> fieldList = new ArrayList<String>();
List<Canvas> canvases = new ArrayList<Canvas>();
List<String> children = ItemResourceUtils.solrChildrenPids(pid, fieldList, solrAccess, solrMemoization);
Map<String, Pair<Integer, Integer>> resolutions = getResolutions(children);
for (String p : children) {
String repPid = p.replace("/", "");
if (repPid.equals(pid)) {
continue;
}
DocumentDto page = getIiifDocument(repPid);
if (!"page".equals(page.getModel()))
continue;
String id = ApplicationURL.applicationURL(this.requestProvider.get()) + "/canvas/" + repPid;
Pair<Integer, Integer> resolution = resolutions.get(p);
if (resolution != null) {
Canvas canvas = new CanvasImpl(id, new PropertyValueSimpleImpl(page.getTitle()), resolution.getLeft(), resolution.getRight());
ImageResource resource = new ImageResourceImpl();
String resourceId = ApplicationURL.applicationURL(this.requestProvider.get()).toString() + "/iiif/" + repPid + "/full/full/0/default.jpg";
resource.setType("dctypes:Image");
resource.setId(resourceId);
resource.setHeight(resolution.getLeft());
resource.setWidth(resolution.getRight());
resource.setFormat("image/jpeg");
Service service = new ServiceImpl();
service.setContext("http://iiif.io/api/image/2/context.json");
service.setId(ApplicationURL.applicationURL(this.requestProvider.get()).toString() + "/iiif/" + repPid);
service.setProfile("http://iiif.io/api/image/2/level1.json");
resource.setService(service);
Image image = new ImageImpl();
image.setOn(new URI(id));
image.setResource(resource);
canvas.setImages(Collections.singletonList(image));
canvases.add(canvas);
}
}
// no pages - 500 ?
if (canvases.isEmpty()) {
throw new GenericApplicationException("cannot create manifest for pid '" + pid + "'");
}
Sequence sequence = new SequenceImpl();
sequence.setCanvases(canvases);
manifest.setSequences(Collections.singletonList(sequence));
return Response.ok().entity(toJSON(manifest)).build();
} catch (IOException e) {
throw new GenericApplicationException(e.getMessage());
} catch (URISyntaxException e) {
throw new GenericApplicationException(e.getMessage());
} catch (InterruptedException e) {
throw new GenericApplicationException(e.getMessage());
}
}
use of com.google.cloud.vision.v1p4beta1.Image in project google-cloud-java by googleapis.
the class AnnotateImage method main.
public static void main(String... args) throws Exception {
// Instantiates a client
ImageAnnotatorClient vision = ImageAnnotatorClient.create();
// The path to the image file to annotate
// for example "./resources/wakeupcat.jpg";
String fileName = "your/image/path.jpg";
// Reads the image file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString imgBytes = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.printf("Error: %s\n", res.getError().getMessage());
return;
}
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
for (Map.Entry<FieldDescriptor, Object> entry : annotation.getAllFields().entrySet()) {
System.out.printf("%s : %s\n", entry.getKey(), entry.getValue());
}
}
}
}
use of com.google.cloud.vision.v1p4beta1.Image in project TweetwallFX by TweetWallFX.
the class GoogleVisionCache method load.
private Map<String, ImageContentAnalysis> load(final Stream<String> imageUris) throws IOException {
if (null == getClient()) {
return Collections.emptyMap();
}
final List<AnnotateImageRequest> requests = imageUris.filter(Objects::nonNull).distinct().map(this::createImageRequest).peek(air -> LOG.info("Prepared {}", air)).collect(Collectors.toList());
if (requests.isEmpty()) {
return Collections.emptyMap();
}
LOG.info("Executing analysis for {} AnnotateImageRequests", requests.size());
final BatchAnnotateImagesResponse batchResponse = getClient().batchAnnotateImages(requests);
final Iterator<AnnotateImageResponse> itResponse = batchResponse.getResponsesList().iterator();
final Iterator<AnnotateImageRequest> itRequest = requests.iterator();
final Map<String, ImageContentAnalysis> result = new LinkedHashMap<>(requests.size());
while (itRequest.hasNext() && itResponse.hasNext()) {
final AnnotateImageRequest request = itRequest.next();
final AnnotateImageResponse response = itResponse.next();
final String uri = request.getImage().getSource().getImageUri();
final ImageContentAnalysis ica = new ImageContentAnalysis(response);
LOG.info("Image('{}') was evaluated as {}", uri, ica);
result.put(uri, ica);
cache.put(uri, ica);
}
if (itRequest.hasNext()) {
throw new IllegalStateException("There are still annotate Responses available!");
} else if (itRequest.hasNext()) {
throw new IllegalStateException("There are still annotate Requests available!");
} else {
return Collections.unmodifiableMap(result);
}
}
Aggregations