OpenCV's Java bindings Mat.get() gives weird results [closed]

asked 2015-09-16 08:45:31 -0600

Tralala gravatar image

updated 2015-09-16 09:43:29 -0600

I have a 8UC1 Mat image. I'm trying to convert it to Java 2D byte array with [x][y] coordinates. Here's what I have so far:

byte[][] arr = new byte[mat.cols()][mat.rows()];
for (int colIndex = 0; colIndex < mat.cols(); colIndex++) {
     mat.get(0, colIndex, arr[colIndex]);
 }

However, that gives me totally scrambled results. For example a mat with .dump() such as this:

[255, 255, 255, 255, 255, 255, 255, 255, 255, 255;
   0,   0,   0,   0,   0,   0,   0,   0,   0,   0;
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255;
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255;
 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]

gives me this (don't mind the -1, that's OK):

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 -1 -1 -1 -1 0 
-1 -1 -1 -1 -1 -1 -1 -1 0 0 
-1 -1 -1 -1 -1 -1 -1 0 0 0 
-1 -1 -1 -1 -1 -1 0 0 0 0
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-10-15 09:39:12.692251

Comments

1

oh wait, pixels are stored in a 1D byte[] array, not a 2D [][] one.

try:

byte[] pixels = new byte[img.total() * img.channels()];
img.get(0,0, bytes);

or , if you are interested in a single pixel only:

 double [] pixel = img.get(17,23); // b,g,r
berak gravatar imageberak ( 2015-09-16 08:49:57 -0600 )edit

This is not what i want. I want to create a 2D array.

Tralala gravatar imageTralala ( 2015-09-16 09:19:12 -0600 )edit

"I want to create a 2D array." - sorry, you must not. please understand, that the underlying c++ api is working on consecutive data, not on pointers to an array per row.

berak gravatar imageberak ( 2015-09-16 09:21:24 -0600 )edit

I don't see your point. That is one of the reasons I want to create the 2D array. I must convert it, so I can work with it easily in Java, without the sluggish JNI calls to individual pixels.

Tralala gravatar imageTralala ( 2015-09-16 09:35:27 -0600 )edit

Well I recognise that, that's why I made this question in the first place. So the bottom line is you don't know why the provided code doesn't work?

Tralala gravatar imageTralala ( 2015-09-16 09:42:40 -0600 )edit

apologies, misread your question.

it is mat.get(row,col) in opencv, not x,y. so you need: mat.get(colIndex, 0, arr[colIndex]);

berak gravatar imageberak ( 2015-09-18 02:28:45 -0600 )edit