本帖最后由 dongzzu 于 2021-3-9 21:12 编辑
参数1,参数2,去百度云申请,参数3为文件路径,参数4为识别的种类
举例:text_ocr = BaiDuOCR(文字识别APIKey, 文字识别SecretKey, 存储位置 & ".bmp", "通用文字识别")
[按键精灵] 纯文本查看 复制代码 Function BaiDuOCR(APIKey, SecretKey, ImgPath, OcrType)
Dim http, ReJson, url, formStr, token, PhotoBS, httpBody
Dim xml_dom, Node, FileByteArrs, Stream, ReExpObj, Matches
Dim adTypeBinary, adModeReadWrite, adTypeText
adTypeBinary = 1
adModeReadWrite = 3
adTypeText = 2
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
Set sStream = CreateObject("ADODB.Stream")
url = "https://aip.baidubce.com/oauth/2.0/token?"
formStr = "grant_type=client_credentials&" & _
"client_id=" & APIKey & "&" & _
"client_secret=" & SecretKey & "&"
With http
.Open "POST", url
.SetRequestHeader "Conent-Length", Len(formStr)
.Send formStr
End With
ReJson = http.ResponseText
Set ReExpObj = CreateObject("VBScript.RegExp")
ReExpObj.[Global] = True
ReExpObj.Pattern = "access_token"":""(.+?)"""
If ReExpObj.Test(ReJson) Then
Set Matches = ReExpObj.Execute(ReJson)
token = Matches(0).SubMatches(0)
Else
MsgBox "获取Token失败!" & vbcrlf & ReJson
End If
With sStream
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.LoadFromFile (ImgPath)
.Position = 0
FileByteArr = .Read
.Close
End With
Set xml_dom = CreateObject("Microsoft.XMLDOM")
With xml_dom
.loadXML ("")
Set Node = .createElement("HTML")
With Node
.dataType = "bin.base64"
.nodeTypedValue = FileByteArr
PhotoBS = .Text
End With
End With
PhotoBS = Replace(PhotoBS,"+","%2b")
PhotoBS = Replace(PhotoBS, "/", "%2f")
PhotoBS = Replace(PhotoBS,"=","%3d")
With http
If OcrType = "通用文字识别" Then
formStr = "image=" & PhotoBS & "&image_url="
.Open "POST", "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" & CStr(token), False
ElseIf OcrType = "通用图像识别" Then
formStr = "image=" & PhotoBS
.Open "POST", "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" & CStr(token), False
End If
.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.SetRequestHeader "Conent-Length", Len(formStr)
.Send formStr
httpBody = .ResponseBody
End With
With sStream
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.Write httpBody
.Position = 0
.Type = adTypeText
.Charset = "utf-8"
BaiDuOCR = .ReadText
.Close
End With
Set Node = Nothing
Set xml_dom = Nothing
Set sStream = Nothing
End Function |