PaddlePaddle / Mobile

Embedded and Mobile Deployment
Apache License 2.0
71 stars 29 forks source link

Android手机读取图像问题 #93

Closed yeyupiaoling closed 6 years ago

yeyupiaoling commented 6 years ago

@Xreki 我根据Android的Dome做了一个图像分类的,但是在读取出了点问题。在Java中,是把图像转成字节数组的,所以我也是这个样做,如下代码。但是pixels这个字节数组得到的结果是不定长的,但是图像明明都是3*32*32的。大小应该都是3072才对。这是为什么呢?


    public String infer(String img_path) {
        //把图像读取成一个Bitmap对象
        Bitmap bitmap = BitmapFactory.decodeFile(img_path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        //把图像生成一个字节数组
        byte[] pixels = baos.toByteArray();
        Log.i("datas大小为", String.valueOf(pixels.length));
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (mRgbBytes == null) {
            mRgbBytes = new byte[3072];
        }
        for (int i = 0; i < pixels.length; i++) {
            mRgbBytes[i] = pixels[i];
            Log.i("ImageRecognition", String.valueOf(mRgbBytes[i]));
        }
        // 获取预测结果
        float[] result = infer(mRgbBytes);
        // 把概率最大的结果提取出来
        float max = 0;
        int number = 0;
        for (int i = 0; i < result.length; i++) {
            if (result[i] > max) {
                max = result[i];
                number = i;
            }
        }
        String msg = "类别为:" + clasName[number] + ",可信度为:" + max;
        Log.i("ImageRecognition", msg);

        return msg;
    }

就是因为上面的大小没有充满矩阵,导致array很多都是0的。

    for (size_t c = 0; c < 3; ++c) {
        for (size_t h = 0; h < 32; ++h) {
            for (size_t w = 0; w < 32; ++w) {
                array[index] =
                        static_cast<float>(((pixels[(h * 32 + w) * 3 + c]) - means[c]) / 255.0);
                LOGI("array_src:%f", array[index]);
                index++;
            }
        }
    }

这个怎么解决???求解答。

yeyupiaoling commented 6 years ago

大体上是没错的,只是通道顺错了而已,这样读取是RGB的,但CIFAR训练时是BGR的,所以要转换一下:

    public byte[] getPixelsBGR(Bitmap bitmap) {
        int bytes = bitmap.getByteCount();
        ByteBuffer buffer = ByteBuffer.allocate(bytes);
        bitmap.copyPixelsToBuffer(buffer);
        byte[] temp = buffer.array();
        byte[] pixels = new byte[(temp.length/4) * 3];
        for (int i = 0; i < temp.length/4; i++) {
            pixels[i * 3] = temp[i * 4 + 2];        //B
            pixels[i * 3 + 1] = temp[i * 4 + 1];    //G
            pixels[i * 3 + 2] = temp[i * 4 ];       //R
        }
        return pixels;
    }