我有一个针对最新 JavaCV 的解决方案。实际上,有几个。我在处理某些图像时遇到了问题,因此我第二次尝试转换为字节数组时产生了更一致的结果。
这里的解决方案在 Scala 中。
要将图像数据转换为字节数组,您需要获取字节。
Mat m = new Mat(iplImage);
ByteBuffer buffer = this.image.asByteBuffer();
Mat m = new Mat(this.image);
int sz = (m.total() * m.channels());
byte[] barr = new byte[sz]();
m.data().get(barr);
转换为 java.nio.ByteBuffer,使用图像的总大小(我转换为垫子),然后获取数据。我忘记了 m.total * m.channels 是否返回 double、long、int 或 float。我在 Scala 中使用 .toInt。
另一种选择是使用 BufferedImage。我的一些图像仅使用 JavaCV 就显得有些奇怪。
BufferedImage im = new Java2DFrameConverter().convert(new OpenCVFrameConverter.ToIplImage().convert(this.image))
BytearrayOutputstream baos = new ByteArrayOutputStream();
byte[] barr = null;
try{
ImageIO.write(im,"jpg",baos);
baos.flush();
barr = baos.toByteArray();
}finally{
baos.close();
}
//This could be try with resources but the original was in Scala.
为了从字节数组转换为 IplImage,我实际上使用了缓冲图像以提高可靠性。
ImplImage im = null;
InputStream in = new ByteArrayInputStream(bytes);
try {
Mat m = new Mat(image.getHeight,image.getWidth,image.getType,new BytePointer(ByteBuffer.wrap(image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData)));
im = new IplImage(m);
}finally{
in.close();
}
//Again this could be try with resources but the original example was in Scala