implementation 'com.rmtheis:tess-two:9.1.0'
下载导入训练数据
下载地址https://github.com/tesseract-ocr/tessdata大多数情况只需要识别简体中文和英文对应数据包:chi_sim.traineddata,eng.traineddata项目中创建assets把对应的数据包导入
调用
object TessUtil {
// 指定识别的语言英文加中文
private const val LANGUAGE = "eng+chi_sim"
// 指定数据包在设备中路径
private val mDataPath = PathUtils.getExternalAppCachePath() + File.separator + "tesseract" + File.separator
/**
* @param imagePath 识别的图片地址
* @param callback 结果回调
*/
fun textRecognition(imagePath: String, callback: Callback) {
textRecognition(ImageUtils.getBitmap(imagePath), callback)
}
/**
* @param bitmap 识别的图片
* @param callback 结果回调
*/
fun textRecognition(bitmap: Bitmap, callback: Callback) {
ThreadUtils.getSinglePool()
.execute {
try {
// 复制字体库到手机sd卡中
val path = "${mDataPath}tessdata"
copyFont(path, "chi_sim.traineddata")
copyFont(path, "eng.traineddata")
// 开启文字识别
val tessBaseAPI = TessBaseAPI()
tessBaseAPI.init(mDataPath, LANGUAGE)
tessBaseAPI.setImage(ImageUtils.toGray(bitmap))
val utF8Text = tessBaseAPI.utF8Text
ThreadUtils.runOnUiThread {
callback.success(utF8Text)
}
tessBaseAPI.clear()
} catch (e: Exception) {
ThreadUtils.runOnUiThread {
callback.failure(e)
}
}
}
}
private fun copyFont(path: String, fontName: String) {
FileUtils.createOrExistsDir(path)
val fontPath = path + File.separator + fontName
if (!FileUtils.isFileExists(fontPath)) {
ResourceUtils.copyFileFromAssets(fontName, fontPath)
}
}
interface Callback {
fun success(result: String)
fun failure(e: Exception) {
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)