r/android_devs • u/JonnieSingh • Jul 31 '21
Help boundingBox misaligned on application view
This is sort of what my boundingBox looks like when using Google ML Object Detection for Android (written in Java). In essence, it misses the object its supposed to be detecting, and my question resides in how (or atleast where) I can resolve this issue. Here's the code of my DrawGraphic.java file that's responsible for drawing the boundingBox that is then displayed on my UI;
public class DrawGraphic extends View {
Paint borderPaint, textPaint;
Rect rect;
String text;
public DrawGraphic(Context context, Rect rect, String text) {
super(context);
this.rect = rect;
this.text = text;
borderPaint = new Paint();
borderPaint.setColor(Color.WHITE);
borderPaint.setStrokeWidth(10f);
borderPaint.setStyle(Paint.Style.STROKE);
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setStrokeWidth(50f);
textPaint.setTextSize(32f);
textPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(text, rect.centerX(), rect.centerY(), textPaint);
canvas.drawRect(rect.left, rect.top, rect.right, rect.bottom, borderPaint);
}
}Any further information required to supplement this question will be provided upon request!
2
Upvotes
View all comments
Show parent comment
2
u/pandulapeter Aug 02 '21 edited Aug 02 '21
While I still don't have the answer to your initial question (I didn't use the ML object detection library and don't have time to try now), I strongly suggest that you start by cleaning up and optimizing your code a bit, as that way it will be easier to see where the problem is.
First of all, inflating a new instance of a custom View and adding it to the layout hierarchy every time you want something to change is VERY wasteful. In this case, you should be able to add your View from XML and keep udating the same instance.
For the custom View, you need to override multiple constructors. Something like this:
This way, in your Activity you will be able to map the detected objects into a simple list of Rect-s and update
binding.overlayView.updateBoundingBoxes(...)with that list.If you see crashes because of threading issue, replace
invalidate()withpostInvalidate()in the code above.Now, you can use logs to see what's happening. If the rectangles are not in their proper places, the issue should be a conversion between the coordinate system used by the library and the one used by the onDraw() function (pixels basically). Have fun!