android-studio - 如何进行 Android 测试 - Tesseract OCR?如何在 Junit 中访问 MainActivity 上下文?
问题描述
您好,我正在尝试测试我的 Tesseract OCR 方法
这是我班级的代码
public class TessTextRecognizer {
private final TessBaseAPI mTess;
private final String TAG = "Exception";
public TessTextRecognizer(Context context, String language) {
mTess = new TessBaseAPI();
boolean fileExistFlag = false;
AssetManager assetManager = context.getAssets();
String dstPathDir = "/tesseract/tessdata/";
String srcFile = "ell.traineddata";
InputStream inFile = null;
dstPathDir = context.getFilesDir() + dstPathDir;
String dstInitPathDir = context.getFilesDir() + "/tesseract";
String dstPathFile = dstPathDir + srcFile;
FileOutputStream outFile = null;
try {
inFile = assetManager.open(srcFile);
File f = new File(dstPathDir);
if (!f.exists()) {
if (!f.mkdirs()) {
Toast.makeText(context, srcFile + " can't be created.", Toast.LENGTH_SHORT).show();
}
outFile = new FileOutputStream(new File(dstPathFile));
} else {
fileExistFlag = true;
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
} finally {
if (fileExistFlag) {
try {
if (inFile != null) inFile.close();
mTess.init(dstInitPathDir, language);
return;
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
if (inFile != null && outFile != null) {
try {
//copy file
byte[] buf = new byte[1024];
int len;
while ((len = inFile.read(buf)) != -1) {
outFile.write(buf, 0, len);
}
inFile.close();
outFile.close();
mTess.init(dstInitPathDir, language);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
} else {
Toast.makeText(context, srcFile + " can't be read.", Toast.LENGTH_SHORT).show();
}
}
}
public TessTextRecognizer() {
mTess = null;
}
public String getOCRResult(Bitmap bitmap) {
mTess.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψως" +
"ϊάόέώίύήΆΌΈΏΊΎΪ ");
mTess.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!@#$%^&*()_+=-[]}{;:\"\\|~,./<>?0123456789" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
mTess.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SPARSE_TEXT_OSD);
mTess.setImage(bitmap);
return mTess.getUTF8Text();
}
}
我的问题是,要创建此类的对象,我需要将该上下文传递给构造函数。这就是我在 MainActivity 中的称呼。
tessTextRecognizer = new TessTextRecognizer( this, DEFAULT_LANGUAGE);
在我的 Junit 测试中,我不知道将什么作为上下文传递给构造函数。
我在Junit中尝试做的是在src/androidTest/res中创建了一个 res 文件夹,并在其中放置了一个可绘制对象。现在我想使用assertEquals来检查可绘制的文本是否等于我的结果TessTextRecognizer.getOCRresult(bitmap).
我会很感激任何帮助谢谢
解决方案
推荐阅读
- powerbi - power bi 表中的逗号分隔值
- android - 如何在 Sqlite 数据库中保存回收站视图的值
- templates - 如何在 go 模板调用中使用 $variable
- azure-sql-database - Azure SQL 数据库:从池中获取连接之前经过的超时时间
- ios - 导航到 ViewController 并关闭 VC
- javascript - OpenCV Rect 约定——什么是 x、y、宽度、高度?
- c# - 泛型类的非泛型列表上的 C# 调用方法
- formio - Formio 连接除 mongodb 以外的其他数据库
- android - 如何避免参数可能为空
- crystal-reports - 水晶报表:如何删除一个值并替换一个新值