Java – Replace unsigned types in Java

Replace unsigned types in Java… here is a solution to the problem.

Replace unsigned types in Java

In OpenCV, the fastest way to use Mat is to first copy it into an array of the appropriate primitive type, as shown below

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

However, this does not work in OpenCV4Android with unsigned Mat types such as 8U because Java lacks unsigned types. I can add 256 to each element while copying to the next array of larger primitives (here short types:

).

byte[] buf = new byte[cols];
short[][] array = new short[rows][cols];
for (int i = 0; i < rows; i++) {
    mat.get(i, 0, buf);
    for (int j = 0; j < cols; j++) {
        array[i][j] = (short) (buf[i]+256);
    }
}

Is there a faster way?

Solution

Mat can actually be converted to signed bytes before extraction:

mat.convertTo(mat, CvType.CV_8S);

Related Problems and Solutions