3

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();
        }

    }
}
batuman
  • 7,066
  • 26
  • 107
  • 229

1 Answers1

6

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.

BConic
  • 8,750
  • 2
  • 29
  • 55
  • Not sure what you mean? if I switch x and y in the array access, it won't work. – batuman Mar 08 '14 at 15:47
  • Look closely, there's a difference between your line and mine with the position of `x` and `y`. You should access image data as I mentioned, not the way you did. – BConic Mar 08 '14 at 15:52