go版百度在线车牌识别

如果标准输入有内容(表示通过命令行输出了数据),则直接上传分析.否则通过参数base64图片

现在百度每日有限制,需要寻找更好的方法.(现在暂时的想法是多申请两个帐号,比如5个,一天就1000次,估计够了)

package main
 
import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
	"time"
 
	"github.com/soease/tools"
	"github.com/tidwall/gjson"
)
 
const (
	CLIENT_ID     = "123"
	CLIENT_SECRET = "321"
 
	BAIDU_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token"               //Token
	BAIDU_LPR_URL   = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate" //车牌识别
)
 
type BaiDuToken struct {
	ExpiresIn   int64  `json:"expires_in"`
	AccessToken string `json:"access_token"`
	RequestTime time.Time
}
 
type BaiDuError struct {
	Error       string `json:"error"`
	Description string `json:"error_description"`
}
 
//获取百度Token
func BaiDu_Token() (tk BaiDuToken, err error) {
	para := map[string]string{
		"grant_type":    "client_credentials",
		"client_id":     CLIENT_ID,
		"client_secret": CLIENT_SECRET,
	}
	ret := tools.Web_GetWithPara(BAIDU_TOKEN_URL, para)
 
	err = json.Unmarshal(ret, &tk)
	tk.RequestTime = time.Now()
	return tk, err
}
 
func GetImageBase64(filename string) string {
	fb := tools.Base64ImageFile(filename)
	fb = strings.Replace(fb, "+", "%2B", -1)
 
	return fb
}
 
func BaiDu_LPR_FileName(filename string, token string) (string, string) {
	return BaiDu_LPR(GetImageBase64(filename), token)
}
 
func BaiDu_LPR(Base64Image string, token string) (string, string) {
	data := fmt.Sprintf("access_token=%s&multi_detect=true&image=%s", token, Base64Image)
	ret := string(tools.Post(BAIDU_LPR_URL, "application/x-www-form-urlencoded", data))
	if len(ret) == 0 {
		return "", ""
	}
 
	err := gjson.Get(ret, "error_msg")
	if err.String() != "" {
		fmt.Println(err.String())
		return "", ""
	}
 
	num := gjson.Get(ret, "words_result.#.number")
	col := gjson.Get(ret, "words_result.#.color")
	return col.String(), num.String()
}
 
//读取所有标准输出
func ReadAllFrom(reader io.Reader) ([]byte, error) {
	return ReadFrom(reader, 10240)
}
 
//读取部份标准输出
func ReadFrom(reader io.Reader, num int) ([]byte, error) {
	var buffer bytes.Buffer
	p := make([]byte, num)
 
	for {
		n, err := reader.Read(p)
 
		if err == io.EOF {
			buffer.Write(p[:n])
			return buffer.Bytes(), nil
		} else if err == nil {
			if n > 0 {
				buffer.Write(p[:n])
			} else {
				buffer.Write(p)
			}
		}
 
	}
	return buffer.Bytes(), nil
}
 
func main() {
	picFile := "img/chepai.jpg"
 
	tk, err := BaiDu_Token()
	if err != nil {
		fmt.Println("获取百度Token错误")
		return
	}
 
	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 { //从stdin获取base64图片
		p, err := ReadAllFrom(os.Stdin)
		if err == nil {
			col, num := BaiDu_LPR(string(p), tk.AccessToken)
			fmt.Println(col, num)
		}
	} else {
		col, num := BaiDu_LPR_FileName(picFile, tk.AccessToken)
		fmt.Println(col, num)
	}
 
}

相关文章