问题描述
我使用 Tesseract API 从图像中检测阿拉伯语。我尝试了 OCR 英语并且它有效,但是当我尝试 OCR 阿拉伯语时,它在这一行崩溃并且没有显示任何日志!我真的没有得到任何日志
tessBaseApi.init(DATA_PATH,"ara",OEM_CUBE_ONLY);
我在 assets/tessdata 文件夹中添加了以下内容
ara.cube.bigrams
ara.cube.fold
ara.cube.lm
ara.cube.nn
ara.cube.params
ara.cube.size
ara.cube.word-freq
ara.traineddata
这是我的代码
公共类 TessActivity 扩展 AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
static final int PHOTO_REQUEST_CODE = 1;
private TessBaseAPI tessBaseApi;
TextView textView;
Uri outputFileUri;
private static final String lang = "eng";
String result = "empty";
private static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/TesseractSample/";
private static final String TESSDATA = "tessdata";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tess);
Button captureImg = (Button) findViewById(R.id.action_btn);
if (captureImg != null) {
captureImg.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(TessActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&&ActivityCompat.checkSelfPermission(TessActivity.this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(TessActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},111);
}
else {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startCameraActivity();
}
}
});
}
textView = (TextView) findViewById(R.id.textResult);
}
private void startCameraActivity() {
try {
String IMGS_PATH = Environment.getExternalStorageDirectory().toString() + "/TesseractSample/imgs";
prepareDirectory(IMGS_PATH);
String img_path = IMGS_PATH + "/ocr.jpg";
outputFileUri = Uri.fromFile(new File(img_path));
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent,PHOTO_REQUEST_CODE);
}
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
}
@Override
protected void onActivityResult(int requestCode,int resultCode,@Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == PHOTO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
doOCR();
} else {
Toast.makeText(this,"ERROR: Image was not obtained.",Toast.LENGTH_SHORT).show();
}
}
private void doOCR() {
prepareTesseract();
// startOCR(outputFileUri);
new AsyncLol().execute(outputFileUri);
}
/**
* Prepare directory on external storage
*
* @param path
* @throws Exception
*/
private void prepareDirectory(String path) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.e(TAG,"ERROR: Creation of directory " + path + " Failed,check does Android Manifest have permission to write to external storage.");
}
} else {
Log.i(TAG,"Created directory " + path);
}
}
private void prepareTesseract() {
try {
prepareDirectory(DATA_PATH + TESSDATA);
} catch (Exception e) {
e.printstacktrace();
}
copyTessDataFiles(TESSDATA);
}
/**
* copy tessdata files (located on assets/tessdata) to destination directory
*
* @param path - name of directory with .traineddata files
*/
private void copyTessDataFiles(String path) {
try {
String fileList[] = getAssets().list(path);
for (String fileName : fileList) {
// open file within the assets folder
// if it is not already there copy it to the sdcard
String pathToDataFile = DATA_PATH + path + "/" + fileName;
if (!(new File(pathToDataFile)).exists()) {
InputStream in = getAssets().open(path + "/" + fileName);
OutputStream out = new FileOutputStream(pathToDataFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf,len);
}
in.close();
out.close();
Log.d(TAG,"copied " + fileName + "to tessdata");
}
}
} catch (IOException e) {
Log.e(TAG,"Unable to copy files to tessdata " + e.toString());
}
}
public class AsyncLol extends AsyncTask<Uri,Void,String>{
@Override
protected String doInBackground(Uri... uris) {
Bitmap bitmap2 = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // 1 - means max size. 4 - means maxsize/4 size. Don't use value <4,because you need more memory in the heap to store your data.
Bitmap bitmap = BitmapFactory.decodeFile(uris[0].getPath(),options);
bitmap2 = getRoundedBitmap(bitmap,uris[0].getPath());
result = extractText(bitmap2);
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String bitmap) {
super.onPostExecute(bitmap);
textView.setText(bitmap);
}
}
private String extractText(Bitmap bitmap) {
try {
tessBaseApi = new TessBaseAPI();
//tessBaseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_BLOCK );
tessBaseApi.init(DATA_PATH,OEM_CUBE_ONLY);
} catch (Exception e) {
Log.e(TAG,e.getMessage());
if (tessBaseApi == null) {
Log.e(TAG,"TessBaseAPI is null. TessFactory not returning tess object.");
}
}
Log.d(TAG,"Training file loaded");
tessBaseApi.setimage(bitmap);
String extractedText = "empty result";
try {
extractedText = tessBaseApi.getUTF8Text();
} catch (Exception e) {
Log.e(TAG,"Error in recognizing text.");
}
tessBaseApi.end();
return extractedText;
}
@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if(requestCode==111&&permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
&&permissions[1].equals(Manifest.permission.CAMERA)){
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startCameraActivity();
}
}
private static int exifTodegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
public Bitmap getRoundedBitmap(Bitmap bitmap,String realPath){
Bitmap rotatedBitmap = null;
Log.e("Original dimensions",bitmap.getWidth()+" "+bitmap.getHeight());
Log.e("Original resolution",String.valueOf(bitmap.getDensity()));
try {
ExifInterface exif = new ExifInterface(realPath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_norMAL);
int rotationIndegrees = exifTodegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {matrix.preRotate(rotationIndegrees);}
rotatedBitmap = Bitmap.createBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return rotatedBitmap;
}catch(IOException ex){
Log.e("error","Failed to get Exif data",ex);
return bitmap;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)