How to get the Mat object from the Byte[] in openCV android?
opencv has a neat way to writing Mats to files - it can generate different formats based on the file extension provided. Here is a minimal example:
public void writeImageToFile(Mat image, String filename) {
File root = Environment.getExternalStorageDirectory();
File file = new File(root, filename);
Highgui.imwrite(file.getAbsolutePath(), image);
if (DEBUG)
Log.d(TAG,
"writing: " + file.getAbsolutePath() + " (" + image.width()
+ ", " + image.height() + ")");
}
if red and blue is swapped then it sounds like your byte data from onPictureTaken() is in BGRA format. You can swap it to RGBA using:
Imgproc.cvtColor(bgrImg, rgbImg, Imgproc.COLOR_BGR2RGB);
the format is actually device specific - on one device I had it comes through as YUV.
You have to specify width and height of the image/Mat and channels depth.
Mat mat = new Mat(width, height, CvType.CV_8UC3);
mat.put(0, 0, data);
Make sure you are using correct type of Mat. Maybe your data is not in 3 bytes RGB format and you should use another type e.g. CvType.CV_8UC1
.
Good luck!
The best and easiest way is like this:
byte[] bytes = FileUtils.readFileToByteArray(new File("aaa.jpg"));
Mat mat = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);