Search in sources :

Example 81 with Image

use of com.google.cloud.vision.v1p4beta1.Image in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstancesAdvanced method createFromPublicImage.

// [END compute_instances_create_from_image]
// [END compute_instances_create_from_custom_image]
// [END compute_instances_create_from_image_plus_empty_disk]
// [END compute_instances_create_from_snapshot]
// [END compute_instances_create_from_image_plus_snapshot_disk]
// [END compute_instances_create_with_subnet]
// [START compute_instances_create_from_image]
/**
 * Create a new VM instance with Debian 10 operating system.
 *
 * @param project project ID or project number of the Cloud project you want to use.
 * @param zone name of the zone to create the instance in. For example: "us-west3-b"
 * @param instanceName name of the new virtual machine (VM) instance.
 * @return Instance object.
 */
public static Instance createFromPublicImage(String project, String zone, String instanceName) throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (ImagesClient imagesClient = ImagesClient.create()) {
        // List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
        Image image = imagesClient.getFromFamily("debian-cloud", "debian-10");
        String diskType = String.format("zones/%s/diskTypes/pd-standard", zone);
        Vector<AttachedDisk> disks = new Vector<>();
        disks.add(diskFromImage(diskType, 10, true, image.getSelfLink()));
        return createWithDisks(project, zone, instanceName, disks, "n1-standard-1", "global/networks/default", null);
    }
}
Also used : AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) ImagesClient(com.google.cloud.compute.v1.ImagesClient) Image(com.google.cloud.compute.v1.Image) Vector(java.util.Vector)

Example 82 with Image

use of com.google.cloud.vision.v1p4beta1.Image in project java-docs-samples by GoogleCloudPlatform.

the class CreateInstancesAdvanced method createWithAdditionalDisk.

// [END compute_instances_create_from_custom_image]
// [START compute_instances_create_from_image_plus_empty_disk]
/**
 * Create a new VM instance with Debian 10 operating system and a 11 GB additional empty disk.
 *
 * @param project project ID or project number of the Cloud project you want to use.
 * @param zone name of the zone to create the instance in. For example: "us-west3-b"
 * @param instanceName name of the new virtual machine (VM) instance.
 * @return Instance object.
 */
public static Instance createWithAdditionalDisk(String project, String zone, String instanceName) throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (ImagesClient imagesClient = ImagesClient.create()) {
        // List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
        Image image = imagesClient.getFromFamily("debian-cloud", "debian-10");
        String diskType = String.format("zones/%s/diskTypes/pd-standard", zone);
        Vector<AttachedDisk> disks = new Vector<>();
        disks.add(diskFromImage(diskType, 10, true, image.getSelfLink()));
        disks.add(emptyDisk(diskType, 11));
        return createWithDisks(project, zone, instanceName, disks, "n1-standard-1", "global/networks/default", null);
    }
}
Also used : AttachedDisk(com.google.cloud.compute.v1.AttachedDisk) ImagesClient(com.google.cloud.compute.v1.ImagesClient) Image(com.google.cloud.compute.v1.Image) Vector(java.util.Vector)

Example 83 with Image

use of com.google.cloud.vision.v1p4beta1.Image in project java-docs-samples by GoogleCloudPlatform.

the class ImageMagick method blurOffensiveImages.

// [END run_imageproc_handler_setup]
// [END cloudrun_imageproc_handler_setup]
// [START cloudrun_imageproc_handler_analyze]
// [START run_imageproc_handler_analyze]
// Blurs uploaded images that are flagged as Adult or Violence.
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()));
    }
}
Also used : SafeSearchAnnotation(com.google.cloud.vision.v1.SafeSearchAnnotation) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) BlobInfo(com.google.cloud.storage.BlobInfo) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) IOException(java.io.IOException) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse)

Example 84 with Image

use of com.google.cloud.vision.v1p4beta1.Image in project java-docs-samples by GoogleCloudPlatform.

the class OcrProcessImage method detectText.

// [END functions_ocr_process]
// [START functions_ocr_detect]
private void detectText(String bucket, String filename) {
    logger.info("Looking for text in image " + filename);
    List<AnnotateImageRequest> visionRequests = new ArrayList<>();
    String gcsPath = String.format("gs://%s/%s", bucket, filename);
    ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature textFeature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
    AnnotateImageRequest visionRequest = AnnotateImageRequest.newBuilder().addFeatures(textFeature).setImage(img).build();
    visionRequests.add(visionRequest);
    // Detect text in an image using the Cloud Vision API
    AnnotateImageResponse visionResponse;
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        visionResponse = client.batchAnnotateImages(visionRequests).getResponses(0);
        if (visionResponse == null || !visionResponse.hasFullTextAnnotation()) {
            logger.info(String.format("Image %s contains no text", filename));
            return;
        }
        if (visionResponse.hasError()) {
            // Log error
            logger.log(Level.SEVERE, "Error in vision API call: " + visionResponse.getError().getMessage());
            return;
        }
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a Cloud Function)
        logger.log(Level.SEVERE, "Error detecting text: " + e.getMessage(), e);
        return;
    }
    String text = visionResponse.getFullTextAnnotation().getText();
    logger.info("Extracted text from image: " + text);
    // Detect language using the Cloud Translation API
    DetectLanguageRequest languageRequest = DetectLanguageRequest.newBuilder().setParent(LOCATION_NAME).setMimeType("text/plain").setContent(text).build();
    DetectLanguageResponse languageResponse;
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
        languageResponse = client.detectLanguage(languageRequest);
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a function)
        logger.log(Level.SEVERE, "Error detecting language: " + e.getMessage(), e);
        return;
    }
    if (languageResponse.getLanguagesCount() == 0) {
        logger.info("No languages were detected for text: " + text);
        return;
    }
    String languageCode = languageResponse.getLanguages(0).getLanguageCode();
    logger.info(String.format("Detected language %s for file %s", languageCode, filename));
    // Send a Pub/Sub translation request for every language we're going to translate to
    for (String targetLanguage : TO_LANGS) {
        logger.info("Sending translation request for language " + targetLanguage);
        OcrTranslateApiMessage message = new OcrTranslateApiMessage(text, filename, targetLanguage);
        ByteString byteStr = ByteString.copyFrom(message.toPubsubData());
        PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
        try {
            publisher.publish(pubsubApiMessage).get();
        } catch (InterruptedException | ExecutionException e) {
            // Log error
            logger.log(Level.SEVERE, "Error publishing translation request: " + e.getMessage(), e);
            return;
        }
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) DetectLanguageResponse(com.google.cloud.translate.v3.DetectLanguageResponse) ByteString(com.google.protobuf.ByteString) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) Image(com.google.cloud.vision.v1.Image) Feature(com.google.cloud.vision.v1.Feature) DetectLanguageRequest(com.google.cloud.translate.v3.DetectLanguageRequest) PubsubMessage(com.google.pubsub.v1.PubsubMessage) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ImageSource(com.google.cloud.vision.v1.ImageSource) ExecutionException(java.util.concurrent.ExecutionException)

Example 85 with Image

use of com.google.cloud.vision.v1p4beta1.Image in project hortonmachine by TheHortonMachine.

the class GeopaparazziController method readProjectInfos.

private List<ProjectInfo> readProjectInfos(File[] projectFiles) throws Exception {
    List<ProjectInfo> infoList = new ArrayList<ProjectInfo>();
    for (File geopapDatabaseFile : projectFiles) {
        try (SqliteDb db = new SqliteDb()) {
            db.open(geopapDatabaseFile.getAbsolutePath());
            ProjectInfo resInfo = db.execOnConnection(connection -> {
                String projectInfo = GeopaparazziUtilities.getProjectInfo(connection, true);
                ProjectInfo info = new ProjectInfo();
                info.databaseFile = geopapDatabaseFile;
                info.fileName = geopapDatabaseFile.getName();
                info.metadata = projectInfo;
                List<org.hortonmachine.gears.io.geopaparazzi.geopap4.Image> imagesList = DaoImages.getImagesList(connection);
                info.images = imagesList.toArray(new org.hortonmachine.gears.io.geopaparazzi.geopap4.Image[0]);
                List<Note> notesList = DaoNotes.getNotesList(connection, null);
                info.notes = notesList;
                List<GpsLog> logsList = DaoGpsLog.getLogsList(connection);
                info.logs = logsList;
                return info;
            });
            infoList.add(resInfo);
        }
    }
    return infoList;
}
Also used : SqliteDb(org.hortonmachine.dbs.spatialite.hm.SqliteDb) ArrayList(java.util.ArrayList) LineString(org.locationtech.jts.geom.LineString) Image(org.hortonmachine.gears.io.geopaparazzi.geopap4.Image) Note(org.hortonmachine.gears.io.geopaparazzi.geopap4.Note) File(java.io.File) DaoGpsLog(org.hortonmachine.gears.io.geopaparazzi.geopap4.DaoGpsLog) GpsLog(org.hortonmachine.gears.io.geopaparazzi.geopap4.DaoGpsLog.GpsLog)

Aggregations

AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)75 Image (com.google.cloud.vision.v1.Image)75 Feature (com.google.cloud.vision.v1.Feature)73 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)72 ArrayList (java.util.ArrayList)71 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)69 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)66 ByteString (com.google.protobuf.ByteString)53 ImageSource (com.google.cloud.vision.v1.ImageSource)41 FileInputStream (java.io.FileInputStream)33 EntityAnnotation (com.google.cloud.vision.v1.EntityAnnotation)28 WebImage (com.google.cloud.vision.v1.WebDetection.WebImage)26 IOException (java.io.IOException)20 ImageContext (com.google.cloud.vision.v1.ImageContext)14 SafeSearchAnnotation (com.google.cloud.vision.v1.SafeSearchAnnotation)11 WebDetection (com.google.cloud.vision.v1.WebDetection)11 LocationInfo (com.google.cloud.vision.v1.LocationInfo)10 Arrays (java.util.Arrays)10 Image (com.google.cloud.compute.v1.Image)9 ImagesClient (com.google.cloud.compute.v1.ImagesClient)9