forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
label.go
83 lines (73 loc) · 1.7 KB
/
label.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Command label uses the Vision API's label detection capabilities to find a label based on an image's content.
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
// [START imports]
vision "cloud.google.com/go/vision/apiv1"
"golang.org/x/net/context"
// [END imports]
)
// findLabels gets labels from the Vision API for an image at the given file path.
func findLabels(file string) ([]string, error) {
// [START init]
ctx := context.Background()
// Create the client.
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return nil, err
}
// [END init]
// [START request]
// Open the file.
f, err := os.Open(file)
if err != nil {
return nil, err
}
image, err := vision.NewImageFromReader(f)
if err != nil {
return nil, err
}
// Perform the request.
annotations, err := client.DetectLabels(ctx, image, nil, 10)
if err != nil {
return nil, err
}
// [END request]
// [START transform]
var labels []string
for _, annotation := range annotations {
labels = append(labels, annotation.Description)
}
return labels, nil
// [END transform]
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s <path-to-image>\n", filepath.Base(os.Args[0]))
}
flag.Parse()
args := flag.Args()
if len(args) == 0 {
flag.Usage()
os.Exit(1)
}
labels, err := findLabels(args[0])
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
if len(labels) == 0 {
fmt.Println("No labels found.")
} else {
fmt.Println("Found labels:")
for _, label := range labels {
fmt.Println(label)
}
}
}