Ask Your Question

How to get and modify the pixel of Mat in Java?

asked 2012-06-08 08:47:00 -0500

Kirill Kornyakov gravatar image Kirill Kornyakov flag of Russian Federation
2311 10 21 48

I want to read and modify some pixels in my matrix. How can I do that in Java? Is there any equivalent for the C++ Mat::at method?

delete close flag offensive retag edit

1 Answer

Sort by ยป oldest newest most voted

answered 2012-06-08 14:02:54 -0500

Andrey Pavlenko gravatar image Andrey Pavlenko
2294 3 15 37

updated 2012-06-08 14:03:38 -0500

In Java you can use Mat::get() and Mat::put() methods. One pixel can be read by

double[] Mat::get(int row, int col)

One or few pixels can be written by

Mat::put(int row, int col, double... data)

But if you're going to work with many pixels, it's better to get all the Mat data at once to Java primitive array, work with it in Java, and then put it back to Mat with a single JNI call. The corresponding Java primitive array type depends on the Mat type:

CV_8U and CV_8S -> byte[],
CV_16U and CV_16S -> short[],
CV_32S -> int[],
CV_32F -> float[],
CV_64F-> double[].

So the code will look like following:

Mat m = ...  // assuming it's of CV_8U type
byte buff[] = new byte[ * m.channels()];
m.get(0, 0, buff);
// working with buff
// ...
m.put(0, 0, buff);
link delete flag offensive edit


Thanks for the answer. However I don't quite understand the use of the byte array. I tried, based on the above suggestion, using m.get(0, 0, buff), and m.get(0,0)[0] (for a grayscale image). The latter resulted in the expected value; the former however (using the byte array) gave a large value (exceeding 255) that I don't understand. My image is of type CV_8U.

user1446598 ( 2013-03-10 12:51:16 -0500 )edit

Login/Signup to Answer

Question tools


subscribe to rss feed


Asked: 2012-06-08 08:47:00 -0500

Seen: 9,782 times

Last updated: Jun 08 '12