use of com.google.cloud.vision.v1p3beta1.Image in project java-docs-samples by GoogleCloudPlatform.
the class CreateWindowsOsImage method createWindowsOsImage.
// Creates a new Windows image from the specified source disk.
public static void createWindowsOsImage(String project, String zone, String sourceDiskName, String imageName, String storageLocation, boolean forceCreate) throws IOException, ExecutionException, InterruptedException, TimeoutException {
try (ImagesClient imagesClient = ImagesClient.create();
InstancesClient instancesClient = InstancesClient.create();
DisksClient disksClient = DisksClient.create()) {
Disk disk = disksClient.get(project, zone, sourceDiskName);
// Getting instances where source disk is attached.
for (String fullInstanceName : disk.getUsersList()) {
Map<String, String> instanceInfo = parseInstanceName(fullInstanceName);
Instance instance = instancesClient.get(instanceInfo.get("instanceProjectId"), instanceInfo.get("instanceZone"), instanceInfo.get("instanceName"));
// Сhecking whether the instances is stopped.
if (!Arrays.asList("TERMINATED", "STOPPED").contains(instance.getStatus()) && !forceCreate) {
throw new IllegalStateException(String.format("Instance %s should be stopped. Please stop the instance using GCESysprep command or set forceCreate parameter to true (not recommended). More information here: https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image#api.", instanceInfo.get("instanceName")));
}
}
if (forceCreate) {
System.out.println("Warning: forceCreate option compromise the integrity of your image. " + "Stop the instance before you create the image if possible.");
}
// Create Image.
Image image = Image.newBuilder().setName(imageName).setSourceDisk(String.format("/zones/%s/disks/%s", zone, sourceDiskName)).addStorageLocations(storageLocation.isEmpty() ? "" : storageLocation).build();
InsertImageRequest insertImageRequest = InsertImageRequest.newBuilder().setProject(project).setForceCreate(forceCreate).setImageResource(image).build();
Operation response = imagesClient.insertAsync(insertImageRequest).get(3, TimeUnit.MINUTES);
if (response.hasError()) {
System.out.println("Windows OS Image creation failed ! ! " + response);
return;
}
System.out.println("Image created.");
}
}
use of com.google.cloud.vision.v1p3beta1.Image in project java-docs-samples by GoogleCloudPlatform.
the class ImageMagick method accept.
// [END functions_imagemagick_setup]
// [START functions_imagemagick_analyze]
@Override
public // Blurs uploaded images that are flagged as Adult or Violence.
void accept(CloudEvent event) {
// Extract the GCS Event data from the CloudEvent's data payload.
GcsEvent data = getEventData(event);
// Validate parameters
if (data.getBucket() == null || data.getName() == null) {
logger.severe("Error: Malformed GCS event.");
return;
}
BlobInfo blobInfo = BlobInfo.newBuilder(data.getBucket(), data.getName()).build();
// Construct URI to GCS bucket and file.
String gcsPath = String.format("gs://%s/%s", data.getBucket(), data.getName());
logger.info(String.format("Analyzing %s", data.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.", data.getName()));
blur(blobInfo);
} else {
logger.info(String.format("Detected %s as OK.", data.getName()));
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
}
}
use of com.google.cloud.vision.v1p3beta1.Image in project java-docs-samples by GoogleCloudPlatform.
the class ImageMagick method accept.
// [END functions_imagemagick_setup]
// [START functions_imagemagick_analyze]
@Override
public // Blurs uploaded images that are flagged as Adult or Violence.
void accept(GcsEvent event, Context context) {
// Validate parameters
if (event.getBucket() == null || event.getName() == null) {
logger.severe("Error: Malformed GCS event.");
return;
}
BlobInfo blobInfo = BlobInfo.newBuilder(event.getBucket(), event.getName()).build();
// Construct URI to GCS bucket and file.
String gcsPath = String.format("gs://%s/%s", event.getBucket(), event.getName());
logger.info(String.format("Analyzing %s", event.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.", event.getName()));
blur(blobInfo);
} else {
logger.info(String.format("Detected %s as OK.", event.getName()));
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
}
}
use of com.google.cloud.vision.v1p3beta1.Image in project java-vision by googleapis.
the class DetectBeta method detectLocalizedObjectsGcs.
// [END vision_localize_objects_beta]
// [START vision_localize_objects_gcs_beta]
/**
* 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.
* @param out A {@link PrintStream} to write detected objects to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
public static void detectLocalizedObjectsGcs(String gcsPath, PrintStream out) throws Exception, 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);
// Perform the request
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
client.close();
// Display the results
for (AnnotateImageResponse res : responses) {
for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) {
out.format("Object name: %s\n", entity.getName());
out.format("Confidence: %s\n", entity.getScore());
out.format("Normalized Vertices:\n");
entity.getBoundingPoly().getNormalizedVerticesList().forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY()));
}
}
}
}
use of com.google.cloud.vision.v1p3beta1.Image in project java-vision by googleapis.
the class DetectBeta method detectHandwrittenOcr.
// [END vision_localize_objects_gcs_beta]
// [START vision_handwritten_ocr_beta]
/**
* Performs handwritten text detection on a local image file.
*
* @param filePath The path to the local file 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 detectHandwrittenOcr(String filePath, PrintStream out) throws Exception {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
// Set the Language Hint codes for handwritten OCR
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());
}
}
}
Aggregations