Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Mat(OpenCV) data type to csv file in Java or Android

Tags:

android

opencv

I like to pring Mat type data from OpenCV to a csv file. I can convert from Mat to byte array, then I write to text file and I never get full image. Always get a portion of the image. What could be wrong?

printtoTextFile(Mat d, File file_g){
   Size size = d.size();
   byte[] a = new byte[(int) (d.width * d.height)];
   d.get(0, 0, a);//I get byte array here for the whole image
   FileOutputStream fos_g = null;
    OutputStreamWriter ow = null;
    BufferedWriter fwriter = null;
    try {
        fos_g = new FileOutputStream(file_g);
        ow = new OutputStreamWriter(fos_g);
        fwriter = new BufferedWriter(ow);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   for (x = 0; x < size.height; x++){
            for (y = 0; y < size.width; y++){
                fwriter.write(String.valueOf(a[(int) (x * size.width + y)]));
                ow.flush();
                fwriter.write(","); 
                ow.flush();
            }
            fwriter.write("\n");
            ow.flush();
            //fos_g.flush();
        }
        fos_g.flush();
        try {
            fos_g.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
like image 776
batuman Avatar asked Sep 19 '26 23:09

batuman


1 Answers

OpenCV matrices are stored row by row, not column by column, hence you should swap the x and y in the array access:

fwriter.write(String.valueOf(a[(int) (y * size.width + x)]));

As a consequence, for efficiency, you should also swap your x and y loops.

like image 88
BConic Avatar answered Sep 22 '26 13:09

BConic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!