-
Notifications
You must be signed in to change notification settings - Fork 14
/
platerecognizer.go
76 lines (57 loc) · 1.53 KB
/
platerecognizer.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
package licenseplaterecognizer
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
type PlateRecognizer struct {
APIKey string
}
func NewPlateRecognizer(apiKey string) LicensePlateRecognizer {
return &PlateRecognizer{APIKey: apiKey}
}
func (pr *PlateRecognizer) RecognizeFromImage(base64image string) ([]string, error) {
form := url.Values{}
form.Add("upload", base64image)
form.Add("regions", "bg")
req, err := http.NewRequest("POST", "https://api.platerecognizer.com/v1/plate-reader/", strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", fmt.Sprintf("Token %s", pr.APIKey))
httpClient := http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("expected status code %d but service returned %d", http.StatusCreated, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
result := &plates{}
if err := json.Unmarshal(body, result); err != nil {
return nil, err
}
returnData := make([]string, len(result.Plates))
for i, plate := range result.Plates {
if plate.Plate == "" {
return nil, fmt.Errorf("service returned empty license plate")
}
returnData[i] = strings.ToUpper(plate.Plate)
}
return returnData, nil
}
type plates struct {
Plates []*plate `json:"results"`
}
type plate struct {
Plate string `json:"plate"`
}