【问题标题】:Get pixels matrix from YUV byte array从 YUV 字节数组中获取像素矩阵
【发布时间】:2016-05-18 11:21:18
【问题描述】:

我需要从 onPreviewFrame 函数中从相机预览中获得的 YUV byte[] 数组中获取像素矩阵。我需要矩阵形式的像素才能实现进一步的图像处理。 我正在通过以下方式执行此操作:

  1. byte[] 数组到 YUV 图像
  2. YUV 图像转 JPEG。
  3. JPEG 到位图。
  4. 位图到像素数组。
  5. 像素数组到像素矩阵。

有没有达到相同结果的最佳方法? 目前,我的实现如下。

@Override
public void onPreviewFrame(byte[] data, Camera camera) {

try {
    final YuvImage image = new YuvImage(data, ImageFormat.NV21,
            size.width, size.height, null);
    final File file = new File(Environment.getExternalStorageDirectory()
            .getPath() + "/" + String.valueOf(br) + "out.jpg");
    final FileOutputStream file_o_s = new FileOutputStream(file);
    Thread comp_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                image.compressToJpeg(
                        new Rect(0, 0, size.width, size.height), 40,
                        file_o_s);
                file_o_s.flush();
                file_o_s.close();

                Bitmap bMap = BitmapFactory.decodeFile(file.getPath());
                int[] pixels_array = new int[bMap.getHeight()*bMap.getWidth()];
                bMap.getPixels(pixels_array, 0, bMap.getWidth(), 0, 0, bMap.getWidth(), bMap.getHeight());
                int[][] pixels_matrix = new int[bMap.getHeight()][bMap.getWidth()];

                int start = 0;
                for (int r = 0; r < bMap.getHeight(); r++) {
                    int L = Math.min(bMap.getWidth(), pixels_array.length - start);
                    pixels_matrix[r] = java.util.Arrays.copyOfRange(pixels_array, start, start + L);
                    start += L;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
    comp_thread.start();

} catch (Exception e) {
    Log.e(tag, e.getMessage());
}
}

【问题讨论】:

    标签: java android android-camera yuv


    【解决方案1】:

    只需指定相机预览必须提供 RGB 图像

    Camera.Parameters.setPreviewFormat(ImageFormat.RGB_565);

    【讨论】:

    • 我正在三星 Galaxy S4 上测试我的代码,它不支持 RGB_565,所以我使用的是 NV21 格式。此外,official documentation 建议使用它。因此,如果我尝试使用 RGB_565 格式应用程序停止并且 Android 监视器显示“致命异常”。
    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多