OCR text recognition wrong text displaying - java

I am new to tess-two library. I am able to add that library and getting image from drawable and its even converting, but I am getting wrong text as below:
Here is my complete code:
Bitmap image;
private TessBaseAPI mTess;
String datapath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init image
image = BitmapFactory.decodeResource(getResources(), R.drawable.test_image);
//initialize Tesseract API
String language = "eng";
datapath = getFilesDir()+ "/tesseract/";
mTess = new TessBaseAPI();
checkFile(new File(datapath + "tessdata/"));
mTess.init(datapath, language);
}
private void checkFile(File file) {
if (!file.exists()&& file.mkdirs()){
copyFiles();
}
if(file.exists()) {
String datafilepath = datapath+ "/tessdata/eng.traineddata";
File datafile = new File(datafilepath);
if (!datafile.exists()) {
copyFiles();
}
}
}
public void processImage(View view){
String OCRresult = null;
mTess.setImage(image);
OCRresult = mTess.getUTF8Text();
TextView OCRTextView = (TextView) findViewById(R.id.OCRTextView);
OCRTextView.setText(OCRresult);
}
private void copyFiles() {
try {
String filepath = datapath + "/tessdata/eng.traineddata";
AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("tessdata/eng.traineddata");
OutputStream outstream = new FileOutputStream(filepath);
byte[] buffer = new byte[1024];
int read;
while ((read = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, read);
}
outstream.flush();
outstream.close();
instream.close();
File file = new File(filepath);
if (!file.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am getting text like:
mmmm.and,mmm,1111 etc
Any help is appreciated.

I had the same issue. It have fixed it 2 minutes ago, you have to resize your image to a bigger size. I used thumbnailator library to do the job:
BufferedImage bigger = Thumbnails.of(oldImage).size(700, 500).asBufferedImage();
I hope it helps and apologise for my awful English.
Note: more information about resizing here

Possible Isuues that may have:
Incorrect OCR-ed text
Add the keywords in your training data
Follow the tutorial Tesseract Tutorial Page

Related

How can I take Screenshots using Arcore?

I am trying to take a screenshot of my Augmented Reality Screen and pass it as a bitmap to another activity.
This is the code that I am using to take the screenshot:
Function to take screen shot
public static void tmpScreenshot(Bitmap bmp, Context context){
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(context, CostActivity.class);
in1.putExtra("image", filename);
context.startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
Function to receive screenshot
private void loadTmpBitmap() {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.test);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 120, 120, false));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Even though the Screenshot was taken, it was black when it is passed to another activity.
In addition, the Screenshot only appeared after I pressed the back button
Can anyone help me with the code to take a screenshot with ARCore? Or what am I doing wrong?
It is not possible to take a screenshot of a SurfaceView using your method. If you do then the screenshot will be black, as it only works for regular views.
What you need to use is pixelcopy.
private void takePhoto() {
ArSceneView view = arFragment.getArSceneView();
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap);
} catch (IOException e) {
Toast toast = Toast.makeText(VisualizerActivity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Screenshot saved in /Pictures/Screenshots");
} else {
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Failed to take screenshot");
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
public void saveBitmapToDisk(Bitmap bitmap) throws IOException {
// String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots/";
if (videoDirectory == null) {
videoDirectory =
new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Screenshots");
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String formattedDate = df.format(c.getTime());
File mediaFile = new File(videoDirectory, "FieldVisualizer"+formattedDate+".jpeg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

How to use readFileToByteArray with image from gallery

I'm trying to implement in my app the haystack.ai API. I read the documentation. I need help to change something in my code.
In the example code in the documentation, you provide the path of your image. I need to let the user choose a picture from the gallery(I know how to do that) and then convert the picture into an array of byte.
That's what I tried:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate);
backBtn = findViewById(R.id.back_btn);
image = findViewById(R.id.imageRated);
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("uri"));
image.setImageURI(imageUri);
}
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RateActivity.this, MainActivity.class);
startActivity(intent);
}
});
try {
getScore();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getScore() throws IOException {
URL url = new URL("https://api.haystack.ai/api/image/analyze?output=json&apikey=myapikey");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.toString()));
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(imageData);
os.close();
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
while (true) {
int n = is.read(buffer, 0, buffer.length);
if (n <= 0) {
break;
}
responseBuffer.write(buffer, 0, n);
}
String response = responseBuffer.toString("UTF-8");
Log.v("Score", response);
}
}
The logcat says :
RateActivity.getScore(Unknown Source:12) at line 62 --->
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.toString()));
I also tried:
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.getPath()));
The original code in the documentation is:
byte[] imageData = Files.readAllBytes(Paths.get("testImage4.jpg"));
I need to convert the selected picture for the imageData array.
How can I do that?
From your question it seems that you want to convert image URI to
byteArray.
If it is the case you can try the code below.
public void convertUriToByteArray(String uri)
{
ByteArrayOutputStream bArray = new ByteArrayOutputStream();
FileInputStream fIn = null;
try {
fIn = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
int n;
try {
while (-1 != (n = fIn.read(buf)))
bArray.write(buf, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = bArray.toByteArray();
}

Android copy file from internal storage to external

I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here

downloaded files not visible in user media apps?

i need to make downloaded files such as mp3 picture etc, to be visible in Media apps like album or media player
is it of file chmod or is not readable ? every thing is ok in this class but its show downloaded files inside download folder only
this is my class
public class Download extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog;
Context context;
String file_url,file_name;
public Download(Context context,String url , String file_name) {
this.context = context;
this.file_url = url;
this.file_name = file_name;
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "",
"Please wait, Download …");
}
protected String doInBackground(String... params) {
// //////////////////////
try {
URL url = new URL(file_url);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String mp3 = path[path.length - 1];
int lengthOfFile = c.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/downloads/" ;
File file = new File(PATH);
file.mkdirs();
String fileName = file_name;
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
protected void onPostExecute(String result) {
if (result.equals("done")) {
mProgressDialog.dismiss();
}
}
}
any idea ??
You need to call the MediaScannerConnection and tell it to scan your file. Documentation here.

Android: Sharing an image from raw folder. Wrong image being shared

I have an Activity where the user can share an image from the raw folder.
The raw folder has 70 images, all named alphabetically. The first one is R.raw.recipe01 and the last is R.raw.recipe70.
I get the image int I would like to share from a Bundle and I have a method which copies the image from the raw folder to a accessible file.
I call startActivity(createShareIntent()); in the ActionBar MenuItem, which works successfully.
PROBLEM
The share intent will always select R.raw.recipe01 as the image, even if the int from the Bundle is for image for exmaple R.raw.recipe33.
I have shared my code below. Can anyone spot what I am doing wrong?
CODE:
private int rawphoto = 0;
private static final String SHARED_FILE_NAME = "shared.png";
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
rawphoto = bundle.getInt("rawphoto");
int savedphoto = rawphoto;
// COPY IMAGE FROM RAW
copyPrivateRawResourceToPubliclyAccessibleFile(savedphoto);
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "IMAGE TO SHARE: ");
Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
}
private void copyPrivateRawResourceToPubliclyAccessibleFile(int photo) {
System.out.println("INT PHOTO: " +photo);
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(photo);
outputStream = openFileOutput(SHARED_FILE_NAME,
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
}
finally {
try {
inputStream.close();
} catch (IOException ioe) {
}
try {
outputStream.close();
} catch (IOException ioe) {
}
}
}
Remove Context.MODE_APPEND so that the file gets overwritten if it already exists.

Categories

Resources