I’m currently trying to migrate a bit of legacy code from iPhone to Android. This code uses the OpenCV library to do some image processing. Overall it goes well, but I’m stuck on one line of code I have no idea how can be converted into Java code:
Scalar dMean;
Scalar scalar;
std::vector<Mat> channels;
split(mat, channels);
for(int i=0; i<3; ++i) {
channels[i] += dMean[i];
}
The question is – what should be used instead of the += operator in Java code to add a Scalar object to a Mat?
Note: take this answer with a grain of salt, I haven’t fully tested this 😉
OPTION1:
The most direct way, and if you are only going to process a few pixels, is by using your_mat.put(row, col, data) and your_mat.get(row, col).
Because the
put()method does not acceptScalarobjects as the data parameter, you have to convert theScalarto something thatput()accepts.So if your
Scalaris (1,2,3) maybe an int array int[] scalar = {1,2,3}; should do the trick.OPTION2:
But the recommended way, for a lot of pixel processing, is to first convert a
Matto a Java primitive, process the primitive and then convert it back toMat. This is to avoid too many JNI calls, this method does 2 JNI calls while the former makes one per put/get.The corresponding Java primitive array type depends on the Mat type:
So the code will be something like this:
OPTION 3:
Ok so those solutions are pretty ugly, this one is not the most effective but it’s a little less ugly, in a Java way:
Now that I think about it option 3 is quite similar to option 2, if OpenCV’s
Converterswork similar internally as the option 2 conversion.