Search code examples
javaopencviris-recognition

How to convert Mat to byte array, store the value and then convert it back again? java opencv


I have a Mat image for my system and I want to be able to store it in my sqlite database. So I am thinking I need to try convert it to a byte array to be able to store it. But then Im not sure that is right because I'm unsure how to use the value I get if I was to access it from the db to be able to turn it back into its original Mat image. Below is what I have come up with so far:

static byte[] matToByte(Mat mat) throws SQLException {
    int length = (int) (mat.total()*mat.elemSize());
    byte buffer[] = new byte[length];
    int converted = mat.get(0, 0, buffer);

    IrisInitialDatabase.addFeatures(converted);

    return buffer;

}

static Mat byteToMat(byte[] value) {
    Mat m = new Mat();
    m.put(0, 0, value);

    return m;
}

thanks :)


Solution

  • Save it to the database in Base64 format.

    1. Mat to bitmap

      Bitmap image = Bitmap.createBitmap(rgba.cols(),
              rgba.rows(), Bitmap.Config.RGB_565);
      
      Utils.matToBitmap(rgba, image);
      
      Bitmap bitmap = (Bitmap) image;
      bitmap = Bitmap.createScaledBitmap(bitmap, 600, 450, false);
      
    2. bitmap to byte array

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
      byte[] byteArray = byteArrayOutputStream .toByteArray();
      

    ---save to database---

    1. get mat back

      m = Highgui.imdecode(new MatOfByte(Base64.decode(base64ImageFromDB,0)),Highgui.IMREAD_UNCHANGED);