androidimageopencvhighgui

Android - Read image using opencv


I tried reading an image from drawable folder. I am using eclipse ide. I ran the below code but the image was not loaded. The code is taken from 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!");
            }

My Screenshot of my drawable folder is below : enter image description here

How can I load this image?


Solution

  • I found an example for this work.

    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;
    }