我正在尝试使用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
正在返回我在Java中无法显示的Mat对象。
这是我的从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);
这样,可以节省一个大字节数组分配和一个字节数组副本作为奖励。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句