使用CameraX与MediaPipe实现人脸检测时遇Buffer过小错误求助
解决CameraX+MediaPipe人脸检测中“buffer is too small for the pixels”错误
错误原因
你直接使用ImageProxy的第一个Plane(Y通道,单灰度通道)填充ARGB_8888格式的Bitmap,两者数据大小完全不匹配:
- ARGB_8888格式每个像素占4字节,Bitmap总字节数为
width * height * 4 - CameraX输出的YUV_420_888格式中,Y通道每个像素仅1字节,Buffer总大小为
width * height,远小于Bitmap所需的字节数,直接触发“buffer is too small”错误。 - 此外,只取Y通道数据会丢失色彩信息,即使不报错也无法让MediaPipe正确检测人脸。
修复方案
需要将CameraX输出的YUV_420_888格式图像完整转换为ARGB格式Bitmap,再进行后续处理。
1. 新增ImageProxy转Bitmap扩展函数
通过Android原生YuvImage类完成YUV到RGB的转换,避免手动处理多Plane数据的复杂度:
private fun ImageProxy.toBitmap(): Bitmap? { val image = this.image ?: return null // 将YUV_420_888转换为NV21格式的YuvImage val yuvImage = YuvImage( image.planes[0].buffer, ImageFormat.NV21, image.width, image.height, null ) val outputStream = ByteArrayOutputStream() // 压缩为JPEG字节数组,再解码为Bitmap yuvImage.compressToJpeg(Rect(0, 0, image.width, image.height), 100, outputStream) val imageBytes = outputStream.toByteArray() return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) }
2. 修改detectLivestreamFrame方法
替换原有的错误像素复制逻辑,使用上面的扩展函数获取正确的ARGB Bitmap:
fun detectLivestreamFrame(imageProxy: ImageProxy) { if (runningMode != RunningMode.LIVE_STREAM) { throw IllegalArgumentException( "Attempting to call detectLivestreamFrame while not using RunningMode.LIVE_STREAM" ) } val frameTime = SystemClock.uptimeMillis() // 获取转换后的ARGB Bitmap val bitmap = imageProxy.toBitmap() ?: run { imageProxy.close() return } // 保持原有旋转和前置摄像头镜像逻辑 val matrix = Matrix().apply { postRotate(imageProxy.imageInfo.rotationDegrees.toFloat()) postScale(-1f, 1f, bitmap.width.toFloat(), bitmap.height.toFloat()) } val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) bitmap.recycle() // 回收临时Bitmap,避免内存泄漏 // 转换为MediaPipe的MPImage并执行检测 val mpImage = BitmapImageBuilder(rotatedBitmap).build() detectAsync(mpImage, frameTime) imageProxy.close() // 确保ImageProxy资源被释放 }
3. 同步ImageAnalysis与Preview的分辨率
在ImageAnalysis构建时添加和Preview相同的分辨率选择器,避免图像缩放带来的性能损耗:
val imageAnalyzer = ImageAnalysis.Builder() .setResolutionSelector(resolutionSelector) // 和Preview共用同一个分辨率配置 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) .build() .also { it.setAnalyzer(executor, faceDetectorHelper::detectLivestreamFrame) }
额外注意事项
- 确保在处理完ImageProxy后调用
close(),避免CameraX的图像队列阻塞。 - 及时回收不再使用的Bitmap,防止内存溢出。
内容的提问来源于stack exchange,提问作者Lode
相关产品推荐
相关产品推荐

