-
Notifications
You must be signed in to change notification settings - Fork 1
/
ocr.go
88 lines (73 loc) · 2.17 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
80
81
82
83
84
85
86
87
88
package letterbytes
import (
"bytes"
"fmt"
"os"
"os/exec"
"github.com/tjgq/sane"
"golang.org/x/image/tiff"
)
func OCR(img *sane.Image) (string, error) {
buf, err := convertImageToBuffer(img)
if err != nil {
return "", err
}
text, err := extractTextFromBufferExec(buf)
if err != nil {
return "", err
}
return text, nil
}
func convertImageToBuffer(img *sane.Image) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
err := tiff.Encode(buf, img, nil)
if err != nil {
return nil, fmt.Errorf("error encoding PNG: %w", err)
}
return buf, nil
}
// This function uses Tesseract go package, but the ocr output is not as good as
// calling tesseract command line
//
// func extractTextFromBuffer(buf *bytes.Buffer) (string, error) {
// client := gosseract.NewClient()
// defer client.Close()
// client.SetImageFromBytes(buf.Bytes())
// client.SetLanguage("deu")
// text, err := client.Text()
// if err != nil {
// return "", fmt.Errorf("error extracting text with Tesseract: %w", err)
// }
// return text, nil
// }
// extractTextFromBuffer uses the Tesseract command-line tool to extract text from a byte buffer
func extractTextFromBufferExec(buf *bytes.Buffer) (string, error) {
// Create a temporary file for the TIFF image
tempFile, err := os.CreateTemp("", "ocr-*.tiff")
if err != nil {
return "", fmt.Errorf("error creating temporary file: %w", err)
}
defer os.Remove(tempFile.Name())
// Write the buffer to the temporary file
_, err = tempFile.Write(buf.Bytes())
if err != nil {
tempFile.Close()
return "", fmt.Errorf("error writing to temporary file: %w", err)
}
tempFile.Close()
// Define the output file for Tesseract
outputFile := tempFile.Name() + "-output"
// Call the Tesseract command
cmd := exec.Command("tesseract", tempFile.Name(), outputFile, "-l", "deu")
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("error running Tesseract command: %w", err)
}
// Read the output file generated by Tesseract
outputTextFile := outputFile + ".txt"
text, err := os.ReadFile(outputTextFile)
if err != nil {
return "", fmt.Errorf("error reading Tesseract output file: %w", err)
}
defer os.Remove(outputTextFile)
return string(text), nil
}