-
Notifications
You must be signed in to change notification settings - Fork 3
/
ocr.go
79 lines (73 loc) · 2.12 KB
/
ocr.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
77
78
79
package ocrKit
import (
"github.com/richelieu-yang/chimera/v2/src/cmdKit"
"github.com/richelieu-yang/chimera/v2/src/core/errorKit"
"github.com/richelieu-yang/chimera/v2/src/core/fileKit"
"github.com/richelieu-yang/chimera/v2/src/core/pathKit"
"github.com/richelieu-yang/chimera/v2/src/core/sliceKit"
"github.com/richelieu-yang/chimera/v2/src/idKit"
)
//// GetText1 通过 第三方依赖otiai10/gosseract 实现
//// Deprecated Mac(M1)环境没跑通
///*
//!!!: 使用此函数,必须确保"CGO_ENABLED=1",否则go run或go build会报错: undefined: gosseract.NewClient
//*/
//func GetText1(imgPath string, languages ...string) (string, error) {
// if err := fileAssert.AssertExistAndIsFile(imgPath); err != nil {
// return "", err
// }
//
// client := gosseract.NewClient()
// defer client.Close()
// err := client.SetImage(imgPath)
// if err != nil {
// return "", err
// }
// err = client.SetLanguage(languages...)
// if err != nil {
// return "", err
// }
// return client.Text()
//}
// GetText 通过 命令行 实现
/*
PS:
(1) 实际上依赖于tesseract;
(2) 初步测试,此方法是并发安全的;
(3) 识别并不精确,有些图片可能识别不到文本(e.g.图片很小且就一两个字符).
*/
func GetText(imgPath string, languages ...string) (string, error) {
if err := fileKit.AssertExistAndIsFile(imgPath); err != nil {
return "", err
}
tempDir, err := pathKit.GetTempDir()
if err != nil {
return "", err
}
uuid := idKit.NewUUID()
filePath := pathKit.Join(tempDir, uuid+".txt")
defer fileKit.Remove(filePath)
var lang string
languages = sliceKit.RemoveEmpty(languages, true)
if len(languages) == 0 {
// 默认值
lang = "chi_sim"
} else {
lang = sliceKit.Join(languages, "+")
}
result, err := cmdKit.ExecuteToString("tesseract", imgPath, pathKit.Join(tempDir, uuid), "-l", lang)
if err != nil {
return "", err
}
if !fileKit.Exists(filePath) {
return "", errorKit.New(result)
}
if fileKit.IsDir(filePath) {
return "", errorKit.New("filePath(%s) is a directory", filePath)
}
data, err := fileKit.ReadFile(filePath)
if err != nil {
return "", err
}
return string(data), nil
}