Search code examples
androidtensorflowtensorgesturebytebuffer

java.lang.IllegalArgumentException: The size of byte buffer and the shape do not match


        TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.UINT8);
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4* imageSize * imageSize * 3);
        byteBuffer.order(ByteOrder.nativeOrder());
        inputFeature0.loadBuffer(byteBuffer);

java.lang.IllegalArgumentException: The size of byte buffer and the shape do not match. Ideally how to define the exact buffer size? The input image size is 224*224.


Solution

  • Once I faced similar issue solved by using below code.

    Solution 1

    TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.UINT8);
    
                Bitmap input=Bitmap.createScaledBitmap(imageBitmap,224,224,true);
                TensorImage image=new TensorImage(DataType.UINT8);
                image.load(input);
                ByteBuffer byteBuffer=image.getBuffer();
                inputFeature0.loadBuffer(byteBuffer);
    

    Solution 2

     ByteBuffer byteBuffer = bitmapToByteBuffer(imageBitmap, 224, 224)
    
     public ByteBuffer bitmapToByteBuffer(Bitmap image, int width, int height) {
                ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * width * height * 3);
                byteBuffer.order(ByteOrder.nativeOrder());
                // get 1D array of width * height pixels in image
                int[] intValues = new int[width * height];
                image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
        
                // iterate over pixels and extract R, G, and B values. Add to bytebuffer.
                int pixel = 0;
                for (int i = 0; i < width; i++) {
                    for (int j = 0; j < height; j++) {
                        int val = intValues[pixel++]; // RGB
                        byteBuffer.putFloat(((val >> 16) & 0xFF) * (1.f / 255.f));
                        byteBuffer.putFloat(((val >> 8) & 0xFF) * (1.f / 255.f));
                        byteBuffer.putFloat((val & 0xFF) * (1.f / 255.f));
                    }
                }
                return byteBuffer;
            }