Created
August 7, 2019 01:47
-
-
Save six519/387598b85c37f7371542000084b69851 to your computer and use it in GitHub Desktop.
Google Cloud Vision (Golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"bufio" | |
"encoding/base64" | |
"encoding/json" | |
"net/http" | |
"bytes" | |
"io/ioutil" | |
) | |
//Request | |
type MainRequest struct { | |
Request []RequestArray `json:"requests"` | |
} | |
type RequestArray struct { | |
Image ImageRequest `json:"image"` | |
Feature []FeatureArray `json:"features"` | |
} | |
type ImageRequest struct { | |
Content string `json:"content"` | |
} | |
type FeatureArray struct { | |
Type string `json:"type"` | |
MaxResult int `json:"maxResults"` | |
} | |
//Response | |
type MainResponse struct { | |
Response []ResponseArray `json:"responses"` | |
} | |
type ResponseArray struct { | |
LabelAnnotation []LabelAnnotationArray `json:"labelAnnotations"` | |
} | |
type LabelAnnotationArray struct { | |
Mid string `json:"mid"` | |
Description string `json:"description"` | |
Score float64 `json:"score"` | |
Topicality float64 `json:"topicality"` | |
} | |
func main() { | |
GOOGLE_API_KEY := "<GOOGLE API KEY>" | |
GOOGLE_CLOUD_VISION_URL := "https://vision.googleapis.com/v1/images:annotate" | |
if len(os.Args) == 2 { | |
img, err := os.Open(os.Args[1]) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
defer img.Close() | |
info, _ := img.Stat() | |
size := info.Size() | |
buffer := make([]byte, size) | |
reader := bufio.NewReader(img) | |
reader.Read(buffer) | |
imgb64 := base64.StdEncoding.EncodeToString(buffer) | |
jsonRequest := MainRequest{ | |
Request: []RequestArray{ | |
{ | |
Image: ImageRequest { | |
Content: imgb64, | |
}, | |
Feature: []FeatureArray { | |
{ | |
Type: "LABEL_DETECTION", | |
MaxResult: 5, | |
}, | |
}, | |
}, | |
}, | |
} | |
request, _ := json.Marshal(&jsonRequest) | |
response, err := http.Post(GOOGLE_CLOUD_VISION_URL + "?key=" + GOOGLE_API_KEY, "application/json", bytes.NewBuffer(request)) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
defer response.Body.Close() | |
jsonResponse, _ := ioutil.ReadAll(response.Body) | |
var data MainResponse | |
json.Unmarshal(jsonResponse, &data) | |
//fmt.Printf("The image is detected as: " + data.Response[0].LabelAnnotation[0].Description) | |
fmt.Println("========================================") | |
for _, annotation := range data.Response[0].LabelAnnotation { | |
fmt.Println("The image is detected as: " + annotation.Description) | |
} | |
fmt.Println("========================================") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment