This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
Loading img from resources in OpenCV
David Miguel Lozano edited this page Oct 10, 2016
·
2 revisions
First you have to add permissions in your AndroidManifest.xml
to read the image:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Second, to load a resource in Android with OpenCV you should use the method Utils.loadResource()
(see JavaDoc). So, your method should be something like this:
private Mat readImageFromResources() {
Mat img = null;
try {
img = Utils.loadResource(this, R.drawable.see);
Imgproc.cvtColor(img, img, Imgproc.COLOR_RGB2BGRA);
} catch (IOException e) {
Log.e(TAG,Log.getStackTraceString(e));
}
return img;
}
We need to convert the image because OpenCV stores its matrix internally in the BGR (blue, green, and red) format.
You can add a flags as third parameter to open the image in a particular way:
Imgcodecs.CV_LOAD_IMAGE_UNCHANGED
Imgcodecs.CV_LOAD_IMAGE_ANYCOLOR
Imgcodecs.CV_LOAD_IMAGE_ANYDEPTH
Imgcodecs.CV_LOAD_IMAGE_COLOR
Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE
For example:
Utils.loadResource(this, R.drawable.see, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
If you then want to show the image in an ImageView, you can do:
private void showImg(Mat img) {
Bitmap bm = Bitmap.createBitmap(img.cols(), img.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(img, bm);
ImageView imageView = (ImageView) findViewById(R.id.img_view);
imageView.setImageBitmap(bm);
}