我正在使用TessBaseApi开发一个简单的文本识别Android应用程序(OCR)。它由2个按钮组成。一个按钮用于从图库上传图像并将其设置为图像视图(包含一些文本的图像),第二个按钮返回该图像中的识别文本/字符串。当我在我的真实设备(三星Galaxy note 4)上运行这个应用程序时,一切正常。但是当我在android studio的模拟器上运行这个应用程序时,图库上传很好,但文本无法识别它。我的应用程序不会抛出任何异常或错误。我正在使用Android Studio 2.3和虚拟设备“Nexus 5X API 22”。这是我的代码谢谢
package com.textrecognition.nasir.textrecognitiondemo;
import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import static android.os.Environment.getExternalStorageDirectory;
public class MainActivity extends AppCompatActivity {
Button upload;
Button txtRecog;
ImageView imgView;
TextView txt;
Uri chosenImageURI;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView)findViewById(R.id.myImageView);
txtRecog = (Button) findViewById(R.id.button4);
txt = (TextView) findViewById(R.id.myTextView);
txt.setMovementMethod(new ScrollingMovementMethod());
upload = (Button) findViewById(R.id.button3);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txt.setText("Text will shown here");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 100);
}
});
txtRecog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtRecog.setClickable(false);
progress = new ProgressDialog(MainActivity.this) ;
progress.setMessage("Processing");
progress.show();
makeDirectory(); // directories will be made and language files will be copied
}
});
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, 100);
}
}
public void makeDirectory() {
String dirPathSDCard = Environment.getExternalStorageDirectory().toString() + "/TessrectFolder/";
String languageFileDir = "tessData";
//Toast.makeText(MainActivity.this,dirPathSDCard , Toast.LENGTH_SHORT).show();
try {
File dir = new File(dirPathSDCard + languageFileDir);
//Toast.makeText(MainActivity.this, dir.toString(), Toast.LENGTH_SHORT).show();
if (!dir.exists()){
if (!dir.mkdirs())
{
Log.e("Directory Creation Log", "Could not create directories");
}
} else {
Log.e("Directory Creation Log", "Directory already available");
}
} catch (Exception e) {
e.printStackTrace();
}
copyLanguageFileFromAssetsToSDCard(dirPathSDCard, languageFileDir);
recognizeText(chosenImageURI, dirPathSDCard);
}
public void copyLanguageFileFromAssetsToSDCard(String mainPath, String languageFileDir) {
// Toast.makeText(MainActivity.this, "Control reached here", Toast.LENGTH_SHORT).show();
try {
String fileList[] = getAssets().list(languageFileDir);
// Toast.makeText(MainActivity.this, "" + fileList.length, Toast.LENGTH_SHORT);
String str = "";
for(String fileName : fileList) {
String pathToDataFile = mainPath + languageFileDir + "/" + fileName;
if (!(new File(pathToDataFile)).exists()) {
InputStream in = getAssets().open(languageFileDir + "/" + 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, 0, len);
}
in.close();
out.close();
}
}}catch (Exception e)
{
e.printStackTrace();
}}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
//Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_SHORT).show();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
chosenImageURI = Uri.fromFile(new File(picturePath));
//chosenImageURI = selectedImage;
cursor.close();
Picasso.with(MainActivity.this).load(selectedImage).fit()
.into(imgView);
}
}
public void recognizeText (Uri imgUri, String data_path){
try{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imgUri.getPath(), options);
TessBaseAPI tessApi = new TessBaseAPI();
tessApi.init(data_path, "eng");
tessApi.setImage(bitmap);
String returnedText = "no text found";
returnedText = tessApi.getUTF8Text();
txt.setText(returnedText);
tessApi.end();
txtRecog.setClickable(true);
progress.dismiss();
}catch(Exception e){
e.printStackTrace();
}
}
private void askPermissions(String permissionDetail, int requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permissionDetail) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permissionDetail}, requestCode);
} else {
Toast.makeText(MainActivity.this, "Required Permisssions already granted", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 100:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Required Permisssions granted",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Required Permisssions denied",
Toast.LENGTH_SHORT).show();
}
}
}
}