Hi, I have checked the code and images you attached.
Image is very simple, but your code has complex logic.
This is gray image and we can use contour detection and get bounding box.
Of course, I can fix your script, but I want to recommend the exact solution.
Feel free to contact me anytime.
Regards.
Vadim N.