我尝试从 drawable 文件夹中读取图片。我正在使用 eclipse ide。我运行下面的代码,但没有加载图像。代码取自here
Mat image = new Mat(new Size(500,500 ),CvType.CV_8U);// Change CvType as you need.
image = Highgui.imread("icon.png");
if(image.empty()) {
Log.i(TAG, "Empty image!");
}
我 我的drawable文件夹的屏幕截图如下:
如何加载此图片?
答案 0 :(得分:5)
你可以简单地做到这一点
Mat m = Utils.loadResource(MainActivity.this, R.drawable.img, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
Bitmap bm = Bitmap.createBitmap(m.cols(), m.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(m, bm);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(bm);
答案 1 :(得分:1)
我找到了这项工作的一个例子。
InputStream inpT = getResources().openRawResource(R.drawable.imgt);
mTemp = readInputStreamIntoMat(inpT);
private static Mat readInputStreamIntoMat(InputStream inputStream) throws IOException {
// Read into byte-array
byte[] temporaryImageInMemory = readStream(inputStream);
// Decode into mat. Use any IMREAD_ option that describes your image appropriately
Mat outputImage = Highgui.imdecode(new MatOfByte(temporaryImageInMemory), Highgui.IMREAD_GRAYSCALE);
return outputImage;
}
private static byte[] readStream(InputStream stream) throws IOException {
// Copy content of the image to byte-array
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] temporaryImageInMemory = buffer.toByteArray();
buffer.close();
stream.close();
return temporaryImageInMemory;
}
答案 2 :(得分:0)
应该做的是:
Mat m = Highgui.imread(file.getAbsolutePath());