我使用JavaCV(不是OpenCV)。我的目标是从存储为资源的图像中获取Mat
对象。然后,我将Mat
传递给opencv_imgproc.matchTemplate
方法。我设法写了糟糕代码:
InputStream in = getClass().getResourceAsStream("Lenna32.png");
BufferedImage image = ImageIO.read(in);
Frame f = new Java2DFrameConverter().getFrame(image);
Mat mat = new OpenCVFrameConverter.ToMat().convert(f);
这适用于一些案例。问题是:
答案 0 :(得分:1)
我通过从InputStream中读取字节并将它们传递给imdecode函数来解决这个问题:
InputStream is = context.getResourceAsStream("Lenna32.png");
int nRead;
byte[] data = new byte[16 * 1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
byte[] bytes = buffer.toByteArray();
Mat mat = imdecode(new Mat(bytes), CV_LOAD_IMAGE_UNCHANGED);