检测拍摄的图像亮度/暗度水平-使用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;
}

第二种方法是使用SensorManagerTYPE_LIGHT。还有什么想法/方法吗?

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

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测试应用程序源代码

最新更新