Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Roles required to select or create a project
Select a project: Selecting a project doesn't require a specific
IAM role—you can select any project that you've been
granted a role on.
Create a project: To create a project, you need the Project Creator
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
To enable APIs, you need the Service Usage Admin IAM
role (roles/serviceusage.serviceUsageAdmin), which
contains the serviceusage.services.enable permission. Learn how to grant
roles.
To initialize the gcloud CLI, run the following command:
gcloudinit
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Roles required to select or create a project
Select a project: Selecting a project doesn't require a specific
IAM role—you can select any project that you've been
granted a role on.
Create a project: To create a project, you need the Project Creator
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
To enable APIs, you need the Service Usage Admin IAM
role (roles/serviceusage.serviceUsageAdmin), which
contains the serviceusage.services.enable permission. Learn how to grant
roles.
// detectProperties gets image properties from the Vision API for an image at the given file path.funcdetectProperties(wio.Writer,filestring)error{ctx:=context.Background()client,err:=vision.NewImageAnnotatorClient(ctx)iferr!=nil{returnerr}f,err:=os.Open(file)iferr!=nil{returnerr}deferf.Close()image,err:=vision.NewImageFromReader(f)iferr!=nil{returnerr}props,err:=client.DetectImageProperties(ctx,image,nil)iferr!=nil{returnerr}fmt.Fprintln(w,"Dominant colors:")for_,quantized:=rangeprops.DominantColors.Colors{color:=quantized.Colorr:=int(color.Red) & 0xffg:=int(color.Green) & 0xffb:=int(color.Blue) & 0xfffmt.Fprintf(w,"%2.1f%% - #%02x%02x%02x\n",quantized.PixelFraction*100,r,g,b)}returnnil}
importcom.google.cloud.vision.v1.AnnotateImageRequest;importcom.google.cloud.vision.v1.AnnotateImageResponse;importcom.google.cloud.vision.v1.BatchAnnotateImagesResponse;importcom.google.cloud.vision.v1.ColorInfo;importcom.google.cloud.vision.v1.DominantColorsAnnotation;importcom.google.cloud.vision.v1.Feature;importcom.google.cloud.vision.v1.Image;importcom.google.cloud.vision.v1.ImageAnnotatorClient;importcom.google.protobuf.ByteString;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassDetectProperties{publicstaticvoiddetectProperties()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringfilePath="path/to/your/image/file.jpg";detectProperties(filePath);}// Detects image properties such as color frequency from the specified local image.publicstaticvoiddetectProperties(StringfilePath)throwsIOException{List<AnnotateImageRequest>requests=newArrayList<>();ByteStringimgBytes=ByteString.readFrom(newFileInputStream(filePath));Imageimg=Image.newBuilder().setContent(imgBytes).build();Featurefeat=Feature.newBuilder().setType(Feature.Type.IMAGE_PROPERTIES).build();AnnotateImageRequestrequest=AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();requests.add(request);// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(ImageAnnotatorClientclient=ImageAnnotatorClient.create()){BatchAnnotateImagesResponseresponse=client.batchAnnotateImages(requests);List<AnnotateImageResponse>responses=response.getResponsesList();for(AnnotateImageResponseres:responses){if(res.hasError()){System.out.format("Error: %s%n",res.getError().getMessage());return;}// For full list of available annotations, see http://g.co/cloud/vision/docsDominantColorsAnnotationcolors=res.getImagePropertiesAnnotation().getDominantColors();for(ColorInfocolor:colors.getColorsList()){System.out.format("fraction: %f%nr: %f, g: %f, b: %f%n",color.getPixelFraction(),color.getColor().getRed(),color.getColor().getGreen(),color.getColor().getBlue());}}}}}
constvision=require('@google-cloud/vision');// Creates a clientconstclient=newvision.ImageAnnotatorClient();/** * TODO(developer): Uncomment the following line before running the sample. */// const fileName = 'Local image file, e.g. /path/to/image.png';// Performs property detection on the local fileconst[result]=awaitclient.imageProperties(fileName);constcolors=result.imagePropertiesAnnotation.dominantColors.colors;colors.forEach(color=>console.log(color));
defdetect_properties(path):"""Detects image properties in the file."""fromgoogle.cloudimportvisionclient=vision.ImageAnnotatorClient()withopen(path,"rb")asimage_file:content=image_file.read()image=vision.Image(content=content)response=client.image_properties(image=image)props=response.image_properties_annotationprint("Properties:")forcolorinprops.dominant_colors.colors:print(f"fraction: {color.pixel_fraction}")print(f"\tr: {color.color.red}")print(f"\tg: {color.color.green}")print(f"\tb: {color.color.blue}")print(f"\ta: {color.color.alpha}")ifresponse.error.message:raiseException("{}\nFor more info on error messages, check: ""https://cloud.google.com/apis/design/errors".format(response.error.message))
// detectProperties gets image properties from the Vision API for an image at the given file path.funcdetectPropertiesURI(wio.Writer,filestring)error{ctx:=context.Background()client,err:=vision.NewImageAnnotatorClient(ctx)iferr!=nil{returnerr}image:=vision.NewImageFromURI(file)props,err:=client.DetectImageProperties(ctx,image,nil)iferr!=nil{returnerr}fmt.Fprintln(w,"Dominant colors:")for_,quantized:=rangeprops.DominantColors.Colors{color:=quantized.Colorr:=int(color.Red) & 0xffg:=int(color.Green) & 0xffb:=int(color.Blue) & 0xfffmt.Fprintf(w,"%2.1f%% - #%02x%02x%02x\n",quantized.PixelFraction*100,r,g,b)}returnnil}
importcom.google.cloud.vision.v1.AnnotateImageRequest;importcom.google.cloud.vision.v1.AnnotateImageResponse;importcom.google.cloud.vision.v1.BatchAnnotateImagesResponse;importcom.google.cloud.vision.v1.ColorInfo;importcom.google.cloud.vision.v1.DominantColorsAnnotation;importcom.google.cloud.vision.v1.Feature;importcom.google.cloud.vision.v1.Image;importcom.google.cloud.vision.v1.ImageAnnotatorClient;importcom.google.cloud.vision.v1.ImageSource;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassDetectPropertiesGcs{publicstaticvoiddetectPropertiesGcs()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringfilePath="gs://your-gcs-bucket/path/to/image/file.jpg";detectPropertiesGcs(filePath);}// Detects image properties such as color frequency from the specified remote image on Google// Cloud Storage.publicstaticvoiddetectPropertiesGcs(StringgcsPath)throwsIOException{List<AnnotateImageRequest>requests=newArrayList<>();ImageSourceimgSource=ImageSource.newBuilder().setGcsImageUri(gcsPath).build();Imageimg=Image.newBuilder().setSource(imgSource).build();Featurefeat=Feature.newBuilder().setType(Feature.Type.IMAGE_PROPERTIES).build();AnnotateImageRequestrequest=AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();requests.add(request);// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the "close" method on the client to safely clean up any remaining background resources.try(ImageAnnotatorClientclient=ImageAnnotatorClient.create()){BatchAnnotateImagesResponseresponse=client.batchAnnotateImages(requests);List<AnnotateImageResponse>responses=response.getResponsesList();for(AnnotateImageResponseres:responses){if(res.hasError()){System.out.format("Error: %s%n",res.getError().getMessage());return;}// For full list of available annotations, see http://g.co/cloud/vision/docsDominantColorsAnnotationcolors=res.getImagePropertiesAnnotation().getDominantColors();for(ColorInfocolor:colors.getColorsList()){System.out.format("fraction: %f%nr: %f, g: %f, b: %f%n",color.getPixelFraction(),color.getColor().getRed(),color.getColor().getGreen(),color.getColor().getBlue());}}}}}
// Imports the Google Cloud client librariesconstvision=require('@google-cloud/vision');// Creates a clientconstclient=newvision.ImageAnnotatorClient();/** * TODO(developer): Uncomment the following lines before running the sample. */// const bucketName = 'Bucket where the file resides, e.g. my-bucket';// const fileName = 'Path to file within bucket, e.g. path/to/image.png';// Performs property detection on the gcs fileconst[result]=awaitclient.imageProperties(`gs://${bucketName}/${fileName}`);constcolors=result.imagePropertiesAnnotation.dominantColors.colors;colors.forEach(color=>console.log(color));
defdetect_properties_uri(uri):"""Detects image properties in the file located in Google Cloud Storage or on the Web."""fromgoogle.cloudimportvisionclient=vision.ImageAnnotatorClient()image=vision.Image()image.source.image_uri=uriresponse=client.image_properties(image=image)props=response.image_properties_annotationprint("Properties:")forcolorinprops.dominant_colors.colors:print(f"frac: {color.pixel_fraction}")print(f"\tr: {color.color.red}")print(f"\tg: {color.color.green}")print(f"\tb: {color.color.blue}")print(f"\ta: {color.color.alpha}")ifresponse.error.message:raiseException("{}\nFor more info on error messages, check: ""https://cloud.google.com/apis/design/errors".format(response.error.message))