我正在尝试使用 google-mlkit 开发人脸检测。按照 google-mlkit 的文档设置相机、分析仪、检测器等后 https://developers.google.com/ml-kit/vision/face-detection/android ,我能够检测到人脸。检测到人脸后,我正在尝试提取检测到的人脸图像。
获取检测到的人脸边界框,使用边界框将完整位图提取到检测到的人脸位图中。代码如下。
Bitmap bmp = Bitmap.createBitmap(mediaImage.getWidth(), mediaImage.getHeight(), Bitmap.Config.ARGB_8888);
YuvToRgbConverter converter = new YuvToRgbConverter(context);
converter.yuvToRgb(mediaImage, bmp);
Bitmap extractedBmp = extractFace(
bmp,
(int) (face.getBoundingBox().exactCenterX() / 2),
(int) (face.getBoundingBox().exactCenterY() / 2),
face.getBoundingBox().width(),
face.getBoundingBox().height()
);
private Bitmap extractFace(Bitmap bmp, int x, int y, int width, int height) {
return Bitmap.createBitmap(bmp, x, y, width, height);
}
有时是成功的,有时也是失败的。调试后我发现错误是因为 x + width must be <= bitmap.width()
.
我做错了什么?
最佳答案
异常是正确的。
发生这种情况是因为人脸边界框可以超出图像(位图)范围。
对于 x 和 y 也是可能的。试试这个简单的重新计算。
private fun extractFace(bmp: Bitmap, x: Int, y: Int, width: Int, height: Int): Bitmap? {
val originX = if (x + width > bmp.width) (bmp.width - width) else x
val originY = if (y + height > bmp.height) (bmp.height - height) else y
return Bitmap.createBitmap(bmp, originX, originY, width, height)
}
PS:请检查此计算有人,它应该工作,谢谢
关于android - x + 宽度必须 <= bitmap.width(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64711144/
相关文章:
vue.js - 使用 vue 的故事书 - SassError : Undefined varia
perl - 我怎样才能确保函数永远不会在 perl 中同时执行?
node.js - Kubernetes Crashloopbackoff 与 Minikube
python - 在 matplotlib 中分段更改 x 轴刻度
github - 避免从 raw.githubusercontent.com 获取缓存内容
android - 在 Dart 上将相机从一个屏幕传递到另一个屏幕
angular - 从 - "createAction"函数获取类型