【发布时间】:2018-03-13 17:10:45
【问题描述】:
我必须将 IplImage 转换为 BufferedImage... 对我来说应该是一个简单的任务变得非常复杂。我在 Mac OSX 上使用 JavaCv 1.0(与 OpenCV 3.0 链接)。
在旧的 JavaCV API 中有 IplImage 方法#getBufferedImage,但我在新的 1.0 API 中找不到它了。所以我尝试将 IplImage 转换为字节数组,将字节数组转换为 BufferedImage。我找到了执行这种转换的解决方案:
IplImage inputImg = cvLoadImage(imgName); //imgName is a JPEG absolute path
byte[] imageData = IplImageToByteArray( inputImg); //defined below
ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
BufferedImage inputImage = ImageIO.read(bais); //Always return null
其中 IplImageToByteArray 可以通过以下方式之一定义:
public static byte[] IplImageToByteArray(IplImage src) {
ByteBuffer byteBuffer = src.getByteBuffer();
byte[] barray = new byte[byteBuffer.remaining()];
byteBuffer.get(barray);
return barray;
}
public static byte[] IplImageToByteArray2(IplImage src) {
byte[] barray = new byte[src.imageSize()];
src.getByteBuffer().get(barray);
return barray;
}
两种情况下返回的字节数组都是一样的,但是 ImageIO.read 总是返回空值。我不知道我做错了什么。
【问题讨论】:
-
我自己找到的。可能 ImageIO.read 总是返回 null 的原因是 IplImage 的字节具有 BufferedImage 无法读取的格式。不同于常用的PNG、JPG、BMP、ecc。