Reputation: 874
I'm using this library
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.3.2</version>
</dependency>
OpenCV version appears to be 3.2
I found same question with accepted answer here on stackoverflow, but it appears to be relevant to older versions of API or other library.
This code doesn't work for me...
public Mat bufferedImageToMat(BufferedImage bi) {
Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
mat.put(0, 0, data);
return mat;
}
...because Mat class doesn't have method
mat.put(0, 0, data);
How to achieve same goal with bytedeco javacv 1.3.2 ?
p.s. can somebody guide me to documentation that I can use to find answers myself, so far I wasn't able to find good API reference.
Upvotes: 0
Views: 2472
Reputation: 874
I ended up with this method (works for color BufferedImage)
public Mat bufferedImageToMat(BufferedImage bi) {
Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CV_8UC(3));
int r, g, b;
UByteRawIndexer indexer = mat.createIndexer();
for (int y = 0; y < bi.getHeight(); y++) {
for (int x = 0; x < bi.getWidth(); x++) {
int rgb = bi.getRGB(x, y);
r = (byte) ((rgb >> 0) & 0xFF);
g = (byte) ((rgb >> 8) & 0xFF);
b = (byte) ((rgb >> 16) & 0xFF);
indexer.put(y, x, 0, r);
indexer.put(y, x, 1, g);
indexer.put(y, x, 2, b);
}
}
indexer.release();
return mat;
}
Upvotes: 1