Skip to content

Instantly share code, notes, and snippets.

@frkout
Created February 22, 2016 15:36
Show Gist options
  • Save frkout/e75fc5ed34e77e099fc3 to your computer and use it in GitHub Desktop.
Save frkout/e75fc5ed34e77e099fc3 to your computer and use it in GitHub Desktop.
GoogleCloudVisionAPI
package main
import(
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"google.golang.org/api/vision/v1"
"io/ioutil"
"log"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"os"
"io"
"encoding/binary"
"crypto/rand"
"strconv"
)
func main() {
//設定ファイル読み込み
confFile, err := ioutil.ReadFile("resources/google_credentials.json")
if err != nil{
log.Fatalln("failed to read configuration file" ,err)
}
//画像ファイル読み込み
localPath, err := ImgFileDownload("http://www.skyarc.co.jp/assets_c/2016/02/interview_sasakura_s-thumb-260x260-7537.png")
imgData, err := ioutil.ReadFile(localPath)
if err != nil{
log.Fatalln("failed to read image file" ,err)
}
cfg, err := google.JWTConfigFromJSON([]byte(confFile), vision.CloudPlatformScope)
client := cfg.Client(context.Background())
svc, err := vision.New(client)
enc := base64.StdEncoding.EncodeToString([]byte(imgData))
img := &vision.Image{Content: enc}
// Possible values:
// "TYPE_UNSPECIFIED" - Unspecified feature type.
// "FACE_DETECTION" - Run face detection.
// "LANDMARK_DETECTION" - Run landmark detection.
// "LOGO_DETECTION" - Run logo detection.
// "LABEL_DETECTION" - Run label detection.
// "TEXT_DETECTION" - Run OCR.
// "SAFE_SEARCH_DETECTION" - Run various computer vision models to
// "IMAGE_PROPERTIES" - compute image safe-search properties.
feature := &vision.Feature{
Type: "FACE_DETECTION",
MaxResults: 5,
}
req := &vision.AnnotateImageRequest{
Image: img,
Features: []*vision.Feature{feature},
}
batch := &vision.BatchAnnotateImagesRequest{
Requests: []*vision.AnnotateImageRequest{req},
}
res, err := svc.Images.Annotate(batch).Do()
body, err := json.MarshalIndent(res.Responses[0], "", "\t")
fmt.Println(string(body))
}
func ImgFileDownload(url string) (path string, err error) {
imgFilePath := "imgs/img_" + Random() + ".jpg"
response, err := http.Get(url)
if err != nil {
log.Fatalln("failed to get image file" ,err)
}
defer response.Body.Close()
file, err := os.Create(imgFilePath)
if err != nil {
log.Fatalln("failed to create image file" ,err)
}
defer file.Close()
io.Copy(file, response.Body)
return imgFilePath, err
}
func Random() string {
var n uint64
binary.Read(rand.Reader, binary.LittleEndian, &n)
return strconv.FormatUint(n, 36)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment