GarudaAiacos
GarudaAiacos

Reputation: 181

opencv user drawing rectangle to crop

I am trying to get a user to be able to draw a rectangle around an object and crop it-

with this code--

def click_and_crop(event, x, y, flags, param):

global refPt, drawing, cropping

if event == cv2.EVENT_LBUTTONDOWN:
    drawing = True
    refPt = [(x, y)]
    cropping = True

elif event == cv2.EVENT_MOUSEMOVE:
    if drawing == True:
        cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)


elif event == cv2.EVENT_LBUTTONUP:
    drawing = False
    refPt.append((x, y))
    cropping = False

    cv2.rectangle(closeres, refPt[0], refPt[1], (0, 255, 0), 2)
    cv2.imshow("image", closeres)

it draws multiple rectangles not just one that changes size, it ends up looking like this-

enter image description here

anyone know how to fix this so it changes size instead? if I change code to this-

elif event == cv2.EVENT_MOUSEMOVE:
    if drawing == True:
        closeres = cloneclone
        cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)

to try to erase the rectangle each time it changes i end up seeing nothing , no rectangle and get this message-

Traceback (most recent call last): File "project2.py", line 38, in click_and_crop cv2.rectangle(closeres, refPt[0], refPt1, (0, 255, 0), 2) UnboundLocalError: local variable 'closeres' referenced before assignment

Upvotes: 0

Views: 956

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

You have to draw the image each time at the start of your event hanling routine instead of inside the last if condition. THEN draw the sizer rectangle. Otherwise the previous rectangle is not deleted. Image is progressively destroyed. The higher the refresh rate, the greener your image becomes.

A possible optimization is to use a XOR mode so if you draw previous rectangle again it restores the image (but rectangle cannot be plain green in that case) but it is more complex

Upvotes: 2

Related Questions