我正在尝试使用OpenCV Java API创建一个辅助函数,该函数将处理输入图像并返回输出字节数组。输入图像是保存在计算机中的jpg文件。输入和输出图像使用Swing显示在Java UI中。

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Load image from file
Mat rgba = Highgui.imread(filePath);

Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);

// Convert back to byte[] and return
byte[] return_buff = new byte[(int) (rgba.total() * rgba.channels())];
rgba.get(0, 0, return_buff);
return return_buff;

return_buff返回并转换为BufferedImage时,我得到NULL。当我注释掉Imgproc.cvtColor函数时,return_buff被正确转换为我可以显示的BufferedImage。好像Imgproc.cvtColor返回的是Mat对象,我无法在Java中显示该对象。

这是我的从byte []转换为BufferedImage的代码:
InputStream in = new ByteArrayInputStream(inputByteArray);
BufferedImage outputImage = ImageIO.read(in);

在上面的代码中,outputImage为NULL

有人有什么建议或想法吗?

最佳答案

ImageIO.read(...)(通常是javax.imageio包)用于从文件格式读取/写入图像。您所拥有的是一个包含“原始”像素的数组。 ImageIO无法从此字节数组确定文件格式。因此,它将返回null

相反,您应该直接从字节创建BufferedImage。我不太了解OpenCV,但是我假设Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0)的结果将是灰度图像(8位/样本,1个样本/像素)。此格式与 BufferedImage.TYPE_BYTE_GRAY 相同。如果此假设正确,则您应该能够:

// Read image to Mat as before
Mat rgba = ...;
Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);

// Create an empty image in matching format
BufferedImage gray = new BufferedImage(rgba.width(), rgba.height(), BufferedImage.TYPE_BYTE_GRAY);

// Get the BufferedImage's backing array and copy the pixels directly into it
byte[] data = ((DataBufferByte) gray.getRaster().getDataBuffer()).getData();
rgba.get(0, 0, data);

这样,可以节省一个大字节数组分配和一个字节数组副本作为奖励。 :-)

10-07 18:58
查看更多