首页 > 解决方案 > 检测拍摄的图像亮度/暗度级别 - 使用 Android CameraX

问题描述

我正在使用CameraX在 Android 上捕获图像。我想实现可以分析捕获的图像亮度/暗度级别的功能 - 如果图像太暗/太亮。

有没有一些优雅的方式来做到这一点?也许是为此而设计的一些强大的灯光库?

当前的方法是在 Stackoverflow 某处找到的代码片段:

public static boolean isDark(Bitmap bitmap){
    boolean dark=false;

    float darkThreshold = bitmap.getWidth()*bitmap.getHeight()*0.45f;
    int darkPixels=0;

    int[] pixels = new int[bitmap.getWidth()*bitmap.getHeight()];
    bitmap.getPixels(pixels,0,bitmap.getWidth(),0,0,bitmap.getWidth(),bitmap.getHeight());

    for(int pixel : pixels){
        int color = pixels[i];
        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);
        double luminance = (0.299*r+0.0f + 0.587*g+0.0f + 0.114*b+0.0f);
        if (luminance<150) {
            darkPixels++;
        }
    }

    if (darkPixels >= darkThreshold) {
        dark = true;
    }
    long duration = System.currentTimeMillis()-s;
    return dark;
}

第二种方法是使用 SensorManager TYPE_LIGHT。还有更多的想法/方法吗?

标签: androidimageandroid-camerax

解决方案


更有效的方法是在不将输出转换为位图的情况下计算亮度。

private final ImageAnalysis.Analyzer mAnalyzer = image -> {
    byte[] bytes = new byte[image.getPlanes()[0].getBuffer().remaining()];
    image.getPlanes()[0].getBuffer().get(bytes);
    int total = 0;
    for (byte value : bytes) {
        total += value & 0xFF;
    }
    if (bytes.length != 0) {
        final int luminance = total / bytes.length;
        // luminance is the value you need.
    }
    image.close();
};

来源:CameraX 测试应用源代码


推荐阅读