Note:对这个答案持保留态度,我还没有完全测试过这个;)
OPTION1:
如果您只想处理几个像素,最直接的方法是使用your_mat.put(行,列,数据) and your_mat.get(行,列).
因为put()
方法不接受Scalar
对象作为数据参数,您必须将Scalar
到某事put()
接受。
所以如果你的Scalar
是 (1,2,3) 可能是一个 int 数组int[] 标量 = {1,2,3};应该可以解决问题。
int[] scalar = ... // convert from Scalar object
// assuming the result of get() is an int[], sum both arrays:
int[] data = your_mat.get(row, col) + scalar // <- pseudo-code alert :D
your_mat.put(row, col, data);
OPTION2:
但对于大量像素处理,推荐的方法是首先将Mat
转换为 Java 原语,处理该原语,然后将其转换回Mat
。这是为了避免过多的 JNI 调用,该方法执行 2 次 JNI 调用,而前者每次 put/get 调用一次。
相应的 Java 原始数组类型取决于 Mat 类型:
CV_8U and CV_8S -> byte[];
CV_16U and CV_16S -> short[];
CV_32S -> int[];
CV_32F -> float[];
CV_64F-> double[];
所以代码将是这样的:
// assuming Mat it's of CV_32S type
int buff[] = new int[your_mat.total() * your_mat.channels()];
your_mat.get(0, 0, buff);
// buff is now Mat converted to int[]
your_mat.put(0, 0, buff); // after processing buff, convert it back to Mat type
选项 3:
好吧,这些解决方案相当丑陋,这个不是最有效的,但它以 Java 的方式稍微不那么丑陋:
List<Integer> scalarList = ... // your conversion from a Scalar to a List
List<Integer> channelsList = new ArrayList<Integer>();
Converters.Mat_to_vector_int(channels, channelsList); // this is an existing OpenCV4Android converter
// process channelsList and scalarList, store in channelsList
channels = Converters.vector_int_to_Mat(channelsList); // after processing, convert it back to Mat type
现在我想起来了option 3非常类似于option 2,如果 OpenCV 的Converters
内部工作原理与option 2转换。