1

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 :)

LiL
  • 31
  • 1
  • 6

1 Answers1

2

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);
    
tompadre
  • 797
  • 7
  • 22
  • thank you, I don't seem to have the Bitmap type, do you know how i can get it, I don't think it was included in my opencv lib – LiL Apr 25 '17 at 19:09
  • Bitmap is default android library https://developer.android.com/reference/android/graphics/Bitmap.html just import `import android.graphics.Bitmap;` – tompadre Apr 25 '17 at 19:33
  • I'm glad it works, please mark my answer as correct. :) – tompadre Apr 25 '17 at 20:05
  • im getting a stub error, it says is caused by the first line, do you think this would be something to do with the format/colour my mat img was originally in? – LiL Apr 25 '17 at 21:32
  • How do you get your Mat image? Try debug it and check if it's the right format. Matrix should have columns, rows, etc. – tompadre Apr 26 '17 at 07:28
  • Although this answer works, it's probably not optimal. Base64 adds about 30% overhead to the size. For small tables, that might work, but for bigger tables, it'd be best to store it as a byte array – Chad K Apr 14 '21 at 18:19