如何将IplImage转换为BufferedImage

如何将IplImage转换为BufferedImage

本文介绍了JavaCv:如何将IplImage转换为BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将IplImage转换为BufferedImage ...对我来说,应该是一个简单的任务变得非常复杂.我在Mac OSX(与OpenCV 3.0链接)上使用JavaCv 1.0.

I have to convert an IplImage to a BufferedImage... what should be a simple task is becoming very intricate for me. I'm using JavaCv 1.0 on Mac OSX (which links with OpenCV 3.0).

在旧的JavaCV API中,有IplImage方法#getBufferedImage,但在新的1.0 API中我再也找不到它了.因此,我尝试将IplImage转换为字节数组,并将字节数组转换为BufferedImage.我发现此解决方案可以执行这种转换:

In the old JavaCV API there was the IplImage method #getBufferedImage, but I can't find it anymore in new 1.0 API. So I tried to convert IplImage to byte array and byte array to BufferedImage. I found this solution to perform such conversion:

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:

where IplImageToByteArray can be defined in one of the following ways:

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始终返回null值.我不知道我要怎么做.

The returned byte array is the same in both cases, but ImageIO.read returns always null value. I've no idea about what I'm getting wrong.

推荐答案

public static BufferedImage IplImageToBufferedImage(IplImage src) {
    OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();
    Java2DFrameConverter paintConverter = new Java2DFrameConverter();
    Frame frame = grabberConverter.convert(src);
    return paintConverter.getBufferedImage(frame,1);
}

这篇关于JavaCv:如何将IplImage转换为BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 14:44