Draggable rectangle in OpenCV (Python)

Akshay Chavan
2 min readMar 4, 2019

If you use OpenCV then you probably are interested in computer vision and image processing. Many times you need a area or a region on an image as a starting value or region of interest. For instance, while collecting data for object detection you might want to known the location of the object on the image which can be used as ground truth for calculating the accuracy of the classification algorithm. Another instance is if you want to provide a seed region for a tracking algorithm. In such scenarios, it is very useful if this region selection can be accomplished by a simple user interface preferably by dragging a rectangle on the image.

I have already implemented a rectangle dragging algorithm in javascript ‘selectincanvas’. Here I have implemented the same algorithm using OpenCV in python. Some time back I learned about the OpenCV’s User Interface module and I always wanted a quick way of dragging a rectangle on an image using OpenCV. I was finally able to implement dragging and adjusting a rectangle on an image window within OpenCV and get the coordinates of the rectangle.

The implementation and the documentation can be found in this repo (https://github.com/arccoder/opencvdragrect).

One issue I faced with the python implementation is that if you drag the rectangle for a long time then the stack overflows.

--

--