本文识别的是tiff 文件中的文字```
package main
import (
"fmt"
"github.com/chai2010/tiff"
"github.com/otiai10/gosseract/v2"
"gocv.io/x/gocv"
"image"
"os"
)
func main() {
file, err := os.Open("1.tif")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
img, _ := tiff.Decode(file)
bounds := img.Bounds()
width := bounds.Dx()
height := bounds.Dy()
// 指定区域的坐标
box := image.Rect(0, 0, width, height/10*2)
text := recognizeText("1.tif", box)
fmt.Println(text)
}
func recognizeText(imagePath string, box image.Rectangle) string {
// 读取图片
img := gocv.IMRead(imagePath, gocv.IMReadColor)
// 裁剪指定区域的图片
roiImg := img.Region(box)
// 将裁剪后的图片转换为灰度图像
grayImg := gocv.NewMat()
gocv.CvtColor(roiImg, &grayImg, gocv.ColorBGRToGray)
// 将gocv的Mat格式转换为字节数组
imgBytes, _ := gocv.IMEncode(".png", grayImg)
// 识别文字
client := gosseract.NewClient()
defer client.Close()
client.SetLanguage("chi_sim")
client.SetImageFromBytes(imgBytes.GetBytes())
text, _ := client.Text()
// 返回识别到的文字
return text
}