I have the following code that displays an image if you have picture.png or similar.
import cv2
def my_event(event, x, y, flags, params):
if event==cv2.EVENT_MOUSEWHEEL:
# displaying the coordinates
# on the Shell
print(x, ' ', y, event, flags, params, img.shape[0])
if flags >= 0:
width = height = 400
width = width 10
height = height 10
img_resized = cv2.resize(img, (width,height), interpolation = cv2.INTER_AREA)
cv2.imshow('image', img_resized)
if __name__=="__main__":
img = cv2.imread('picture.png', 1)
print("doug")
cv2.imshow('image', img)
cv2.setMouseCallback('image', my_event) # A call back loop
print("doug2")
cv2.waitKey(0)
cv2.destroyAllWindows()
My understanding is that setMouseCallback is an interrupt function that is active per mouse or keyboard action. In my case it calls my_event. I have initialized the dimensions of my image to 400. I would like to change image size per mousewheel motion and not have the 400 override as shown. My logic would dictate that I would put the initialization values at "doug" but it does not work there. I have tried most other places with no success. How do I initialize a variable for the interrupt?
CodePudding user response:
Callback function is not a "interrupt function" by itself.
By specifying cv2.waitKey(0)
you have a blocking call in the main thread, and imshow(...)
in the callback function can modify the context.
Following code works for me (zoom /- by scrolling):
import cv2
D = dict.fromkeys(['width', 'height'])
D['width'] = 500
D['height'] = 500
def my_event(event, x, y, flags, params):
if event == cv2.EVENT_MOUSEWHEEL:
if flags >= 0:
D['width'] = D['width'] 10
D['height'] = D['height'] 10
print(D['width'], D['height'])
img_resized = cv2.resize(img, (D['width'], D['height']), interpolation=cv2.INTER_AREA)
cv2.imshow('image', img_resized)
else:
D['width'] = D['width'] - 10
D['height'] = D['height'] - 10
print(D['width'], D['height'])
img_resized = cv2.resize(img, (D['width'], D['height']), interpolation=cv2.INTER_AREA)
cv2.imshow('image', img_resized)
if __name__ == "__main__":
img = cv2.imread('image.jpg', 1)
cv2.imshow('image', img)
cv2.setMouseCallback('image', my_event, [D['width'], D['height']]) # A call back loop
cv2.waitKey(0)
cv2.destroyAllWindows()