Skip to content

Instantly share code, notes, and snippets.

@mzucker
Created February 11, 2017 15:27
Show Gist options
  • Save mzucker/1353206a0d8b57b8ba8635a0f4501944 to your computer and use it in GitHub Desktop.
Save mzucker/1353206a0d8b57b8ba8635a0f4501944 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
######################################################################
def mouse_input(window):
'''Return an x, y location from a click in a window using cv2.'''
# mouse callback to collect input
def _on_mouse(event, x, y, flag, param):
if event == cv2.EVENT_LBUTTONDOWN:
print 'got click at ({}, {})'.format(x, y)
param[0] = x
param[1] = y
# no-op mouse callback to stop collecting input
def _null_mouse(event, x, y, flag, param):
pass
# list object to hold coords
mouse_coords = [-1, -1]
# install the callback in the window
cv2.setMouseCallback(window, _on_mouse, mouse_coords)
# collect coords
print 'click anywhere in the {} window'.format(window)
# go until valid coords or ESC hit
while mouse_coords[0] < 0:
k = cv2.waitKey(5)
if k == 27: # ESC
print 'canceled!'
break
# stop collecting coords
cv2.setMouseCallback(window, _null_mouse)
# return result
return tuple(mouse_coords)
######################################################################
image = cv2.imread('purpleflower.png')
win = 'Display'
cv2.namedWindow(win)
cv2.imshow(win, image)
x, y = mouse_input(win)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment