url: https://travelnoire.com/best-carnival-celebrations-around-the-world/, pageTitle: Best \u003cb\u003eCarnival\u003c/b\u003e Celebrations Around The World - Travel Noire, fullMatchingImages: [{url: https://travelnoire.com/wp-content/uploads/2019/02/quinten-de-graaf-278848-unsplash.jpg}]
url:https://bespokebrazil.com/rio-carnival-2019/, pageTitle:Visit \u003cb\u003eRio Carnival 2019\u003c/b\u003e with the Brazil Specialists - Bespoke Brazil, partialMatchingImages:[{ url:https://bespoke-brazil-2018-bespokebrazil.netdna-ssl.com/wp-content/uploads/2019/01/Carnival-1.jpg}]
登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎
建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
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 role
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
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 role
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
// detectWeb gets image properties from the Vision API for an image at the given file path.funcdetectWeb(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}web,err:=client.DetectWeb(ctx,image,nil)iferr!=nil{returnerr}fmt.Fprintln(w,"Web properties:")iflen(web.FullMatchingImages)!=0{fmt.Fprintln(w,"\tFull image matches:")for_,full:=rangeweb.FullMatchingImages{fmt.Fprintf(w,"\t\t%s\n",full.Url)}}iflen(web.PagesWithMatchingImages)!=0{fmt.Fprintln(w,"\tPages with this image:")for_,page:=rangeweb.PagesWithMatchingImages{fmt.Fprintf(w,"\t\t%s\n",page.Url)}}iflen(web.WebEntities)!=0{fmt.Fprintln(w,"\tEntities:")fmt.Fprintln(w,"\t\tEntity\t\tScore\tDescription")for_,entity:=rangeweb.WebEntities{fmt.Fprintf(w,"\t\t%-14s\t%-2.4f\t%s\n",entity.EntityId,entity.Score,entity.Description)}}iflen(web.BestGuessLabels)!=0{fmt.Fprintln(w,"\tBest guess labels:")for_,label:=rangeweb.BestGuessLabels{fmt.Fprintf(w,"\t\t%s\n",label.Label)}}returnnil}
importcom.google.cloud.vision.v1.AnnotateImageRequest;importcom.google.cloud.vision.v1.AnnotateImageResponse;importcom.google.cloud.vision.v1.BatchAnnotateImagesResponse;importcom.google.cloud.vision.v1.Feature;importcom.google.cloud.vision.v1.Feature.Type;importcom.google.cloud.vision.v1.Image;importcom.google.cloud.vision.v1.ImageAnnotatorClient;importcom.google.cloud.vision.v1.WebDetection;importcom.google.cloud.vision.v1.WebDetection.WebEntity;importcom.google.cloud.vision.v1.WebDetection.WebImage;importcom.google.cloud.vision.v1.WebDetection.WebLabel;importcom.google.cloud.vision.v1.WebDetection.WebPage;importcom.google.protobuf.ByteString;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassDetectWebDetections{publicstaticvoiddetectWebDetections()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringfilePath="path/to/your/image/file.jpg";detectWebDetections(filePath);}// Finds references to the specified image on the web.publicstaticvoiddetectWebDetections(StringfilePath)throwsIOException{List<AnnotateImageRequest>requests=newArrayList<>();ByteStringimgBytes=ByteString.readFrom(newFileInputStream(filePath));Imageimg=Image.newBuilder().setContent(imgBytes).build();Featurefeat=Feature.newBuilder().setType(Type.WEB_DETECTION).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;}// Search the web for usages of the image. You could use these signals later// for user input moderation or linking external references.// For a full list of available annotations, see http://g.co/cloud/vision/docsWebDetectionannotation=res.getWebDetection();System.out.println("Entity:Id:Score");System.out.println("===============");for(WebEntityentity:annotation.getWebEntitiesList()){System.out.println(entity.getDescription()+" : "+entity.getEntityId()+" : "+entity.getScore());}for(WebLabellabel:annotation.getBestGuessLabelsList()){System.out.format("%nBest guess label: %s",label.getLabel());}System.out.println("%nPages with matching images: Score%n==");for(WebPagepage:annotation.getPagesWithMatchingImagesList()){System.out.println(page.getUrl()+" : "+page.getScore());}System.out.println("%nPages with partially matching images: Score%n==");for(WebImageimage:annotation.getPartialMatchingImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}System.out.println("%nPages with fully matching images: Score%n==");for(WebImageimage:annotation.getFullMatchingImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}System.out.println("%nPages with visually similar images: Score%n==");for(WebImageimage:annotation.getVisuallySimilarImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}}}}}
// Imports the Google Cloud client libraryconstvision=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';// Detect similar images on the web to a local fileconst[result]=awaitclient.webDetection(fileName);constwebDetection=result.webDetection;if(webDetection.fullMatchingImages.length){console.log(`Full matches found: ${webDetection.fullMatchingImages.length}`);webDetection.fullMatchingImages.forEach(image=>{console.log(` URL: ${image.url}`);console.log(` Score: ${image.score}`);});}if(webDetection.partialMatchingImages.length){console.log(`Partial matches found: ${webDetection.partialMatchingImages.length}`);webDetection.partialMatchingImages.forEach(image=>{console.log(` URL: ${image.url}`);console.log(` Score: ${image.score}`);});}if(webDetection.webEntities.length){console.log(`Web entities found: ${webDetection.webEntities.length}`);webDetection.webEntities.forEach(webEntity=>{console.log(` Description: ${webEntity.description}`);console.log(` Score: ${webEntity.score}`);});}if(webDetection.bestGuessLabels.length){console.log(`Best guess labels found: ${webDetection.bestGuessLabels.length}`);webDetection.bestGuessLabels.forEach(label=>{console.log(` Label: ${label.label}`);});}
// detectWeb gets image properties from the Vision API for an image at the given file path.funcdetectWebURI(wio.Writer,filestring)error{ctx:=context.Background()client,err:=vision.NewImageAnnotatorClient(ctx)iferr!=nil{returnerr}image:=vision.NewImageFromURI(file)web,err:=client.DetectWeb(ctx,image,nil)iferr!=nil{returnerr}fmt.Fprintln(w,"Web properties:")iflen(web.FullMatchingImages)!=0{fmt.Fprintln(w,"\tFull image matches:")for_,full:=rangeweb.FullMatchingImages{fmt.Fprintf(w,"\t\t%s\n",full.Url)}}iflen(web.PagesWithMatchingImages)!=0{fmt.Fprintln(w,"\tPages with this image:")for_,page:=rangeweb.PagesWithMatchingImages{fmt.Fprintf(w,"\t\t%s\n",page.Url)}}iflen(web.WebEntities)!=0{fmt.Fprintln(w,"\tEntities:")fmt.Fprintln(w,"\t\tEntity\t\tScore\tDescription")for_,entity:=rangeweb.WebEntities{fmt.Fprintf(w,"\t\t%-14s\t%-2.4f\t%s\n",entity.EntityId,entity.Score,entity.Description)}}iflen(web.BestGuessLabels)!=0{fmt.Fprintln(w,"\tBest guess labels:")for_,label:=rangeweb.BestGuessLabels{fmt.Fprintf(w,"\t\t%s\n",label.Label)}}returnnil}
importcom.google.cloud.vision.v1.AnnotateImageRequest;importcom.google.cloud.vision.v1.AnnotateImageResponse;importcom.google.cloud.vision.v1.BatchAnnotateImagesResponse;importcom.google.cloud.vision.v1.Feature;importcom.google.cloud.vision.v1.Image;importcom.google.cloud.vision.v1.ImageAnnotatorClient;importcom.google.cloud.vision.v1.ImageSource;importcom.google.cloud.vision.v1.WebDetection;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassDetectWebDetectionsGcs{publicstaticvoiddetectWebDetectionsGcs()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringfilePath="gs://your-gcs-bucket/path/to/image/file.jpg";detectWebDetectionsGcs(filePath);}// Detects whether the remote image on Google Cloud Storage has features you would want to// moderate.publicstaticvoiddetectWebDetectionsGcs(StringgcsPath)throwsIOException{List<AnnotateImageRequest>requests=newArrayList<>();ImageSourceimgSource=ImageSource.newBuilder().setGcsImageUri(gcsPath).build();Imageimg=Image.newBuilder().setSource(imgSource).build();Featurefeat=Feature.newBuilder().setType(Feature.Type.WEB_DETECTION).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;}// Search the web for usages of the image. You could use these signals later// for user input moderation or linking external references.// For a full list of available annotations, see http://g.co/cloud/vision/docsWebDetectionannotation=res.getWebDetection();System.out.println("Entity:Id:Score");System.out.println("===============");for(WebDetection.WebEntityentity:annotation.getWebEntitiesList()){System.out.println(entity.getDescription()+" : "+entity.getEntityId()+" : "+entity.getScore());}for(WebDetection.WebLabellabel:annotation.getBestGuessLabelsList()){System.out.format("%nBest guess label: %s",label.getLabel());}System.out.println("%nPages with matching images: Score%n==");for(WebDetection.WebPagepage:annotation.getPagesWithMatchingImagesList()){System.out.println(page.getUrl()+" : "+page.getScore());}System.out.println("%nPages with partially matching images: Score%n==");for(WebDetection.WebImageimage:annotation.getPartialMatchingImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}System.out.println("%nPages with fully matching images: Score%n==");for(WebDetection.WebImageimage:annotation.getFullMatchingImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}System.out.println("%nPages with visually similar images: Score%n==");for(WebDetection.WebImageimage:annotation.getVisuallySimilarImagesList()){System.out.println(image.getUrl()+" : "+image.getScore());}}}}}
// 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';// Detect similar images on the web to a remote fileconst[result]=awaitclient.webDetection(`gs://${bucketName}/${fileName}`);constwebDetection=result.webDetection;if(webDetection.fullMatchingImages.length){console.log(`Full matches found: ${webDetection.fullMatchingImages.length}`);webDetection.fullMatchingImages.forEach(image=>{console.log(` URL: ${image.url}`);console.log(` Score: ${image.score}`);});}if(webDetection.partialMatchingImages.length){console.log(`Partial matches found: ${webDetection.partialMatchingImages.length}`);webDetection.partialMatchingImages.forEach(image=>{console.log(` URL: ${image.url}`);console.log(` Score: ${image.score}`);});}if(webDetection.webEntities.length){console.log(`Web entities found: ${webDetection.webEntities.length}`);webDetection.webEntities.forEach(webEntity=>{console.log(` Description: ${webEntity.description}`);console.log(` Score: ${webEntity.score}`);});}if(webDetection.bestGuessLabels.length){console.log(`Best guess labels found: ${webDetection.bestGuessLabels.length}`);webDetection.bestGuessLabels.forEach(label=>{console.log(` Label: ${label.label}`);});}
defdetect_web_uri(uri):"""Detects web annotations in the file located in Google Cloud Storage."""fromgoogle.cloudimportvisionclient=vision.ImageAnnotatorClient()image=vision.Image()image.source.image_uri=uriresponse=client.web_detection(image=image)annotations=response.web_detectionifannotations.best_guess_labels:forlabelinannotations.best_guess_labels:print(f"\nBest guess label: {label.label}")ifannotations.pages_with_matching_images:print("\n{} Pages with matching images found:".format(len(annotations.pages_with_matching_images)))forpageinannotations.pages_with_matching_images:print(f"\n\tPage url : {page.url}")ifpage.full_matching_images:print("\t{} Full Matches found: ".format(len(page.full_matching_images)))forimageinpage.full_matching_images:print(f"\t\tImage url : {image.url}")ifpage.partial_matching_images:print("\t{} Partial Matches found: ".format(len(page.partial_matching_images)))forimageinpage.partial_matching_images:print(f"\t\tImage url : {image.url}")ifannotations.web_entities:print("\n{} Web entities found: ".format(len(annotations.web_entities)))forentityinannotations.web_entities:print(f"\n\tScore : {entity.score}")print(f"\tDescription: {entity.description}")ifannotations.visually_similar_images:print("\n{} visually similar images found:\n".format(len(annotations.visually_similar_images)))forimageinannotations.visually_similar_images:print(f"\tImage url : {image.url}")ifresponse.error.message:raiseException("{}\nFor more info on error messages, check: ""https://cloud.google.com/apis/design/errors".format(response.error.message))