android - 检测拍摄的图像亮度/暗度级别 - 使用 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
。还有更多的想法/方法吗?
解决方案
更有效的方法是在不将输出转换为位图的情况下计算亮度。
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();
};
推荐阅读
- python - 有没有更好的方法来确保一个夹具一个接一个地运行而不在参数中列出这些夹具?
- go - 从 Twitter 库搜索中获取数据到 Go 中的结构中
- excel - 如果一行为空,如何从其下方的行复制/粘贴数据以填充空行?
- c - 如何创建一个空矩阵并将其显示在屏幕上?
- php - 如何打印列的不同元素
- python - 使用 python 从嵌套的 Json 中获取所需的数据
- php - 如何通过行尾将文本分解为数组,然后使用 PHP 用冒号再次分解?
- sql - 如何编写将字符串与数字字段进行比较的 Crystal 报表公式
- javascript - 尝试在 ie 中将规则添加到样式表时出现无效参数错误
- django - 收到request.POST时如何将没有OnoToOneRelation的对象链接到相应的表单?