-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
120 lines (98 loc) · 2.48 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"flag"
"fmt"
"image"
"image/color"
"log"
"os"
"path"
"path/filepath"
"regexp"
"github.com/otiai10/gosseract/v2"
"gocv.io/x/gocv"
)
func main() {
var showWindow bool
parseCmdLineArgs(&showWindow)
webcam, err := gocv.OpenVideoCapture(0)
if err != nil {
log.Fatalf("Error opening capture device: %v\n", err)
}
defer webcam.Close()
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
imagePath := path.Join(dirname, "Pictures", "captured_image.jpg")
_, err = createDirIfNotExists(imagePath)
if err != nil {
log.Fatal("Failed to create directory:", err)
}
if err := captureImage(webcam, imagePath, showWindow); err != nil {
log.Fatal("Failed to capture image:", err)
}
text, err := readTextFromImage(imagePath)
if err != nil {
log.Fatal("Failed to read text from image:", err)
}
r := regexp.MustCompile(`\d{4,}`)
match := r.Find([]byte(text))
fmt.Println("Matched string:", text)
fmt.Println("=====================")
fmt.Println("OTP:", string(match))
}
func createDirIfNotExists(p string) (*os.File, error) {
if err := os.MkdirAll(filepath.Dir(p), 0770); err != nil {
return nil, err
}
return os.Create(p)
}
func parseCmdLineArgs(showWindow *bool) {
flag.BoolVar(showWindow, "show-window", false, "flag to show window")
flag.BoolVar(showWindow, "sw", false, "flag to show window (shorthand)")
flag.Parse()
}
// Capture image from webcam and save to file
func captureImage(webcam *gocv.VideoCapture, imagePath string, showWindow bool) error {
var window *gocv.Window
if showWindow {
fmt.Println("show window set to true")
window = gocv.NewWindow("Captura")
defer window.Close()
}
for {
img := gocv.NewMat()
defer img.Close()
if ok := webcam.Read(&img); !ok {
return fmt.Errorf("cannot read from device")
}
var key int
if showWindow {
gocv.PutText(&img, "Press Space to capture", image.Point{X: 10, Y: 30}, gocv.FontHersheyPlain, 2, color.RGBA{255, 0, 0, 0}, 5)
window.IMShow(img)
key = window.WaitKey(1)
if key == 27 { // Press 'Esc' key to exit the loop
break
}
}
if !showWindow || key == 32 {
if ok := gocv.IMWrite(imagePath, img); !ok {
return fmt.Errorf("failed to write image to disk")
}
break
}
}
return nil
}
func readTextFromImage(imagePath string) (string, error) {
client := gosseract.NewClient()
defer client.Close()
client.SetLanguage("eng")
client.SetImage(imagePath)
text, err := client.Text()
if err != nil {
return "", err
}
return text, nil
}