arccoder / opencvdragrect

Drag a rectangle on an image window using opencv
https://arccoder.github.io/opencvdragrect/
40 stars 21 forks source link

opencvdragrect

To drag a rectangle on an image window. Select the entire rectangle and move it around. Hold on to corner or a side and resize the rectangle.

Preview gif

Usage

Import script and Initialize the drag object

import selectinwindow
windowName = 'named window'
rectI = selectinwindow.DragRectangle(image, windowName, imageWidth, imageHeight))

Set mouse click callback function

cv2.setMouseCallback(windowName, selectinwindow.dragrect, rectI)

Double click inside the dragged rectangle to finalize the location of the rect The rectangle location can be accessed anytime through outRect

rectI.outRect

Example of the usage can be found in script.py

Update - Jan 2021

Note

You might get the following error

RuntimeError: maximum recursion depth exceeded

To avoid this error, you can add the following code.

import sys
sys.setrecursionlimit(10 ** 9)

It would help, while holding the rectangle corner or edge for resizing the rectangle the dragging is done in increments by releasing the held corner or sides intermittently.

References

  1. Implementation on how to set callbacks and the infinite loop.

    Capturing mouse click events with Python and OpenCV

  2. Mouse callback events documentation

    OpenCV 4.5.0 High-level GUI