Android平台Bounding Box图像裁剪问题的排查与解决过程
Android平台YOLOv5目标检测后裁剪Bounding Box图像的问题解决
问题现象
在Android平台用YOLOv5完成目标检测并拿到Bounding Box后,尝试裁剪框内图像时一直失败,调试发现代码卡在边界判断的if语句里,无法执行后续裁剪逻辑。
调试过程
- 先通过硬编码裁剪参数(比如固定
left=100, top=100, width=200, height=200)验证,确认裁剪API本身能正常工作,排除了位图对象或API调用的基础问题。 - 尝试改用原始位图的副本进行裁剪,仍然出现错误,说明问题出在Bounding Box的参数计算上。
解决方法
核心问题是裁剪宽高的计算方式错误,修正为直接通过Bounding Box的左右、上下坐标差值计算宽高:
- 裁剪宽度:
location.right - location.left - 裁剪高度:
location.bottom - location.top
避免直接使用Bounding Box对象的width()或height()方法(部分场景下该方法返回值可能存在偏移或计算误差),同时补充完整的边界校验,防止越界异常。
代码示例
错误代码(导致裁剪失败)
Rect location = detectionResult.getBoundingBox(); int cropWidth = location.width(); int cropHeight = location.height(); // 边界校验无法通过,卡在if语句 if (location.left >=0 && location.top >=0 && cropWidth >0 && cropHeight >0) { Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, location.left, location.top, cropWidth, cropHeight); }
修正后的代码(成功裁剪)
Rect location = detectionResult.getBoundingBox(); // 直接通过坐标差值计算宽高 int cropWidth = location.right - location.left; int cropHeight = location.bottom - location.top; // 补充完整的边界校验,确保不超出原始位图范围 if (location.left >= 0 && location.top >= 0 && cropWidth > 0 && cropHeight > 0 && location.right <= originalBitmap.getWidth() && location.bottom <= originalBitmap.getHeight()) { Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, location.left, location.top, cropWidth, cropHeight); // 处理裁剪后的图像 }
坐标说明
以实际检测到的Bounding Box坐标截图为例:left=150, top=90, right=420, bottom=270,此时正确的裁剪宽度为420-150=270,高度为270-90=180,而非依赖Rect.width()/Rect.height()的返回值。
内容的提问来源于stack exchange,提问作者SILA
相关产品推荐
相关产品推荐

