Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ OpenCV imread not working in Android

I am trying to read an image in my C++ code

LOGD("Loading image '%s' ...\n", (*inFile).c_str());;
Mat img = imread(*inFile, CV_LOAD_IMAGE_GRAYSCALE);
CV_Assert(img.data != 0);

and get the following output:

09-25 17:08:24.798: D/IRISREC(12120): Loading image '/data/data/com.example.irisrec/files/input/osoba1.jpg' ...
09-25 17:08:24.798: E/cv::error()(12120): OpenCV Error: Assertion failed (img.data != 0) in int wahet_main(int, char**), file jni/wahet.cpp, line 4208

The file exists. But strange is, that if I try to preview the image using Root File Browser it is just black. I copied the files there manually.

EDIT:

The code works fine under Windows with .png and .jpg format. I am just trying to port an existing C++ project for Iris Recognition to Android.

like image 661
4ndro1d Avatar asked Sep 25 '14 15:09

4ndro1d


2 Answers

imread() determines the type of file based on its content not by the file extension. If the header of the file is corrupted, it makes sense that the method fails.

Here are a few things you could try:

  • Copy those images back to the computer and see if they can be opened by other apps. There's a chance that they are corrupted in the device;
  • Make sure there is a file at that location and that your user has permission to read it;
  • Test with types of images (jpg, png, tiff, bmp, ...);

  • For testing purposes it's always better to be more direct. Get rid of inFile:

Example:

Mat img = imread("/data/data/com.example.irisrec/files/input/osoba1.jpg", CV_LOAD_IMAGE_GRAYSCALE);
if (!img.data) {
    // Print error message and quit
}
like image 83
karlphillip Avatar answered Sep 30 '22 01:09

karlphillip


When debugging, first try to get more data on the problem.

  • It's an unfortunate design that imread() doesn't provide any error info. The docs just say that it'll fail "because of missing file, improper permissions, unsupported or invalid format".
  • Use the debugger to step into the code if you can. Can you tell where it fails?
  • Search for known problems, stackoverflow.com/search?q=imread, e.g. imread not working in OpenCV.

Then generate as many hypotheses as you can. For each one, think of a way to test it. E.g.

  • The image file is malformed (as @karlphillip offered). -- See if other software can open the file.
  • The image file is not a supported format. -- Verify the file format on your desktop. Test that desktop OpenCV can read it. Check the docs to verify the image formats that AndroidCV can read.
  • The image file is not at the expected path. -- Write code to test if there's a file at that path, and verify its length.
  • The image file does not have read permission. -- Write code to open the file for reading.
  • A problem with the imread() arguments. -- Try defaulting the second argument.
like image 35
Jerry101 Avatar answered Sep 30 '22 01:09

Jerry101