Android:相机、onSurfaceTextureUpdated、Bitmap.getPixels - 帧率从 30 下降到 3

标签 android performance bitmap camera

在尝试获取相机预览的像素时,我的表现非常糟糕。

图像格式约为 600x900。 在我的 HTC one 上,预览速率非常稳定,为 30fps。

一旦我尝试获取图像的像素,帧率就会下降到 5 以下!

public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
    Bitmap bmp = mTextureView.getBitmap();
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    int[] pixels = new int[bmp.getHeight() * bmp.getWidth()];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
}

性能太慢了,实在受不了。

现在我唯一的“简单”解决方案是跳帧以至少保持一些视觉性能。 但我实际上想让该代码执行得更快。

如果有任何想法和建议,我将不胜感激,也许有人已经解决了这个问题?

更新

getbitmap: 188.341ms
array: 122ms 
getPixels: 12.330ms
recycle: 152ms

仅仅获取位图就需要 190 毫秒!!这就是问题所在

最佳答案

我深入研究了几个小时。

如此简短的回答:我没有找到避免 getBitmap() 和提高性能的方法。 已知该功能很慢,我找了很多类似的问题都没有结果。

但是我找到了另一种解决方案,它的速度快了大约 3 倍,并且为我解决了这个问题。 我一直在使用 TextureView 方法,我使用它是因为它在如何显示相机预览方面提供了更多自由(例如,我可以在我自己的宽高比的小窗口中显示相机实时预览而不会失真)

但是为了处理图像数据,我不再使用 onSurefaceTextureUpdated()。

我注册了 cameraPreviewFrame 的回调,它提供了我需要的像素数据。 所以不再需要 getBitmap,而且速度更快。

快速的新代码:

myCamera.setPreviewCallback(preview);

Camera.PreviewCallback preview = new Camera.PreviewCallback()
{
    public void onPreviewFrame(byte[] data, Camera camera)
    {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = parameters.getPreviewSize();
        Image img = new Image(size.width, size.height, "Y800");
    }
};

慢:

private int[] surface_pixels=null;
private int surface_width=0;
private int surface_height=0;
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture)
{
    int width,height;

    Bitmap bmp= mTextureView.getBitmap();
    height=barcodeBmp.getHeight();
    width=barcodeBmp.getWidth();
    if (surface_pixels == null)
    {
        surface_pixels = new int[height * width];
    } else
    {
        if ((width != surface_width) || (height != surface_height))
        {
            surface_pixels = null;
            surface_pixels = new int[height * width];
        }
    }
    if ((width != surface_width) || (height != surface_height))
    {
        surface_height = barcodeBmp.getHeight();
        surface_width = barcodeBmp.getWidth();
    }

    bmp.getPixels(surface_pixels, 0, width, 0, 0, width, height);
    bmp.recycle();

    Image img = new Image(width, height, "RGB4");
 }

我希望这能帮助一些遇到同样问题的人。

如果有人找到在 onSurfaceTextureUpdated 中快速创建位图的方法,请提供代码示例。

关于Android:相机、onSurfaceTextureUpdated、Bitmap.getPixels - 帧率从 30 下降到 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22573830/

相关文章:

android - 是否可以将 Activity 和 fragment 与底部导航一起使用?

java - Bitmap.decodeResource 调整图像大小

wpf - 除了 c# 中选定的控件之外,使桌面屏幕变灰

android - 大位图内存不足异常

Javascript 和 CSS 解析性能

.net - .NET 程序集大小会影响性能吗?

android - Delphi RX 中 Android 服务中的 IdHTTP

android - E/Volley:[194] BasicNetwork.performRequest : Unexpected response code 307 for url

android - Shape Drawable gradientRadius 仅适用于像素。这不是没用吗? % 值不起作用

python - Scrapy 导入 100mb 的 XML 提要 - 内存错误