Android中YOLO检测对象裁剪:Bitmap填充后无法触发if块问题
问题描述
在Android中基于YOLO实现检测对象裁剪时,遇到以下异常情况:
- 首次运行无法进入裁剪逻辑的
if代码块,此时croppedBitmap为透明状态 - 执行图像重获代码后:
rgbFrameBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight);
第二次运行仍无法进入if块,Bitmap显示为黑色;第三次运行时Bitmap成功填充图像,但依旧无法进入if块,需再次执行图像重获代码。
裁剪核心逻辑代码如下:
if ((int)location.left > 0 && (int)location.top > 0 && ((int)location.left + (int)location.width()) < croppedBitmap.getWidth() && ((int)location.top + (int)location.height()) < croppedBitmap.getHeight() ) { mycroppedBitmap = Bitmap.createBitmap(croppedBitmap, (int) location.left, (int) location.top, (int) location.width(), (int) location.height() ); mycroppedBitmap = Bitmap.createScaledBitmap(mycroppedBitmap, TF_OD_API_INPUT_SIZEE, TF_OD_API_INPUT_SIZEE, true); }
排查与解决建议
- 打印关键参数定位坐标问题:在
if条件前添加日志,输出*location*的left、top、width、height数值,以及*croppedBitmap*的宽高,确认是否存在检测坐标超出图像范围、坐标为负或宽高为0的无效情况。 - 确保
croppedBitmap图像加载完成:检查croppedBitmap的创建与赋值时机,避免在图像未填充完成时就执行裁剪逻辑。可在裁剪前通过判断croppedBitmap.getConfig()是否非空,或获取任意像素点颜色值,确认图像数据是否有效。 - 调整边界判断逻辑:当前
if条件使用严格小于<判断坐标边界,可改为小于等于<=,因为Bitmap.createBitmap允许裁剪区域的右下角刚好贴合图像边缘(即left + width <= 图像宽度、top + height <= 图像高度均为合法范围),修改后的条件如下:
if ((int)location.left >= 0 && (int)location.top >= 0 && ((int)location.left + (int)location.width()) <= croppedBitmap.getWidth() && ((int)location.top + (int)location.height()) <= croppedBitmap.getHeight()) { // 原有裁剪逻辑 }
- 同步图像更新与检测流程:确保
rgbFrameBitmap.setPixels(...)执行完成并将图像数据同步到croppedBitmap后,再触发YOLO检测与裁剪操作。可通过回调或状态标记,避免检测逻辑与图像更新不同步导致的无效检测。 - 校验YOLO检测时机:确认YOLO模型是在图像完全填充后才执行检测,避免图像未加载完成时输出无效的
location坐标。
内容的提问来源于stack exchange,提问作者SILA
相关产品推荐
相关产品推荐

