0% found this document useful (0 votes)
96 views8 pages

Python 2.7 - Opencv - Detect Mouse Position Clicking Over A Picture - Stack Overflow

The document is a Stack Overflow post asking how to detect the mouse position when clicking on an image displayed using OpenCV in Python. Several responses are provided: 1. The top response gives a sample callback function that stores the mouse position in global variables on double click, and prints the position when a key is pressed. 2. Other responses improve on this by removing the need to store the position, just printing it directly, or collecting click positions in a list for later use. 3. One response provides a minimal code example to display an image, set a mouse callback, and draw a circle on click. So in summary, the responses provide code examples for detecting and handling mouse clicks on OpenCV images

Uploaded by

Angel Saez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views8 pages

Python 2.7 - Opencv - Detect Mouse Position Clicking Over A Picture - Stack Overflow

The document is a Stack Overflow post asking how to detect the mouse position when clicking on an image displayed using OpenCV in Python. Several responses are provided: 1. The top response gives a sample callback function that stores the mouse position in global variables on double click, and prints the position when a key is pressed. 2. Other responses improve on this by removing the need to store the position, just printing it directly, or collecting click positions in a list for later use. 3. One response provides a minimal code example to display an image, set a mouse callback, and draw a circle on click. So in summary, the responses provide code examples for detecting and handling mouse clicks on OpenCV images

Uploaded by

Angel Saez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

15/8/2021 python 2.

7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

Opencv: detect mouse position clicking over a picture


Asked
6 years, 6 months ago Active
3 months ago Viewed
54k times

I have this code in which I simply display an image using OpenCV:

18 import numpy as np

import cv2

class LoadImage:

def loadImage(self):

self.img=cv2.imread('photo.png')

4 cv2.imshow('Test',self.img)

self.pressedkey=cv2.waitKey(0)

# Wait for ESC key to exit

if self.pressedkey==27:

cv2.destroyAllWindows()

# Start of the main program here

if __name__=="__main__":

LI=LoadImage()

LI.loadImage()

Once the window displayed with the photo in it, I want to display on the console (terminal) the position of the mouse when I click over
the picture. I have no idea how to perform this. Any help please?

python-2.7 opencv mouse

Share Improve this question Follow edited Mar 15 '18 at 7:58 asked Feb 4 '15 at 16:55
mpour user4519127
516 4 16 369 1 6 20

Join Stack Overflow to learn, share knowledge, and build your career.

@berak it isSign
not same question
up with email , i am beginner

Sign up in python
with and opencv
Sign
Google
–  user4519127
Feb 4 '15 at
Sign
up with GitHub 16:59up with Facebook

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 1/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

1 just go there again, print out all values, and see..


– berak
Feb 4 '15 at 17:03

7 Answers Active Oldest Votes

Here is an example mouse callback function, that captures the left button double-click

30 def draw_circle(event,x,y,flags,param):

global mouseX,mouseY

if event == cv2.EVENT_LBUTTONDBLCLK:

cv2.circle(img,(x,y),100,(255,0,0),-1)

mouseX,mouseY = x,y

You then need to bind that function to a window that will capture the mouse click

img = np.zeros((512,512,3), np.uint8)

cv2.namedWindow('image')

cv2.setMouseCallback('image',draw_circle)

then, in a infinite processing loop (or whatever you want)

while(1):

cv2.imshow('image',img)

k = cv2.waitKey(20) & 0xFF

if k == 27:

break

elif k == ord('a'):

print mouseX,mouseY

What Does This Code Do?

It stores the mouse position in global variables mouseX & mouseY every time you double click inside the black window and press the a
key that will be created.
Join Stack Overflow to learn, share knowledge, and build your career.

elif k == ord('a'):

Sign up with email


print mouseX,mouseY

Sign up with Google
Sign up with GitHub
Sign up with Facebook

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 2/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

will print the current stored mouse click location every time you press the a button.

Code "Borrowed" from here.

Share Improve this answer Follow edited Apr 23 '20 at 7:15 answered Feb 4 '15 at 20:29
GPPK
6,100 4 29 54

@MasoudPourbozorg press the escape key


– GPPK
Mar 16 '18 at 8:42

also @MasoudPourbozorg I have provided a link to the source where I have taken the code from as it provides much more additional detail to my
answer along with attribution to the original code author as well as detail such as any potential licensing issues.
– GPPK
Mar 16 '18 at 8:43

1 @GPPK thanks for providing the link but I am unable to open it. Therefore, I suggest an updated link or removing it altogether. Please check the
source link.
– mpour
Mar 16 '18 at 12:54

1 In the first block of code, within line global mouseX,mouseY you might want to add img as well. Otherwise you will not be able to pass it to
cv2.circle(img,(x,y),100,(255,0,0),-1)
– Alexey Antonenko
Aug 2 '18 at 16:16

1 This is really helpful. Suggested edit: if you double click in the image, and press the letter a , the system will print the mouse coordinates.
– mherzog
Apr 20 '20 at 17:57

Below is my implementation:

7 No need to store the click position, ONLY display it:

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

if event == cv2.EVENT_LBUTTONDOWN:

# draw circle here (etc...)

print('x = %d, y = %d'%(x, y))

cv2.setMouseCallback('WindowName', onMouse)

If you want to use the positions in other places of your code, you can use below way to obtain the coordinates:
Join Stack Overflow to learn, share knowledge, and build your career.

posList = []

Sign up with email


Sign up with Google
Sign up with GitHub
Sign up with Facebook
def onMouse(event, x, y, flags, param):

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 3/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow
global posList

if event == cv2.EVENT_LBUTTONDOWN:

posList.append((x, y))

cv2.setMouseCallback('WindowName', onMouse)

posNp = np.array(posList) # convert to NumPy for later use

Share Improve this answer Follow edited May 4 at 8:15 answered Mar 17 '18 at 14:56
btomelleri smh
3 3 358 2 7

import cv2

2 cv2.imshow("image", img)

cv2.namedWindow('image')

cv2.setMouseCallback('image', on_click)

def on_click(event, x, y, p1, p2):

if event == cv2.EVENT_LBUTTONDOWN:

cv2.circle(lastImage, (x, y), 3, (255, 0, 0), -1)

Share Improve this answer Follow answered Oct 3 '19 at 18:56


Omer Meshy
21 2

1 Welcome to SO. Please can you explain why this is the answer in addition to the code you shared.
– Mike Poole
Oct 3 '19 at 19:07

You can detect mouse position clicking over a picture via performing the various mouse click events.

1 You just to remember one thing while performing the mouse clicks events is that, you should have to use the same window name at
all places wherever you are using the cv2.imshow or cv2.namedWindow

I given the working code in answer that uses python 3.x and opencv in the following the stackoverflow post:
Join Stack Overflow to learn, share knowledge, and build your career.
https://stackoverflow.com/a/60445099/11493115
Sign up with email
Sign up with Google
Sign up with GitHub
Sign up with Facebook
You can refer the above link for better explanation.
https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 4/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

Code:

import cv2

import numpy as np

#This will display all the available mouse click events

events = [i for i in dir(cv2) if 'EVENT' in i]

print(events)

#This variable we use to store the pixel location

refPt = []

#click event function

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

if event == cv2.EVENT_LBUTTONDOWN:

print(x,",",y)

refPt.append([x,y])

font = cv2.FONT_HERSHEY_SIMPLEX

strXY = str(x)+", "+str(y)

cv2.putText(img, strXY, (x,y), font, 0.5, (255,255,0), 2)

cv2.imshow("image", img)

if event == cv2.EVENT_RBUTTONDOWN:

blue = img[y, x, 0]

green = img[y, x, 1]

red = img[y, x, 2]

font = cv2.FONT_HERSHEY_SIMPLEX

strBGR = str(blue)+", "+str(green)+","+str(red)

cv2.putText(img, strBGR, (x,y), font, 0.5, (0,255,255), 2)

cv2.imshow("image", img)

#Here, you need to change the image name and it's path according to your directory
img = cv2.imread("D:/pictures/abc.jpg")

cv2.imshow("image", img)

#calling the mouse click event

cv2.setMouseCallback("image", click_event)

cv2.waitKey(0)

cv2.destroyAllWindows()

Join Stack Overflow to learn, share knowledge, and build your career.
Share Improve this answer Follow answered Feb 28 '20 at 4:14

Sign up with email


Sign up with Google
Sign up with GitHub
Sign up with Facebook Ankit Lad
129 1 5

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 5/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

I have ported the PyIgnition library from Pygame to opencv2. Find the code at https://github.com/bunkahle/particlescv2
There also
several examples on how to use the particle engine for Python.
0
Share Improve this answer Follow answered Feb 18 '19 at 2:42
bunkus
745 9 15

Here is class based implementation of OpenCV mouse call back for getting point on an image,

0 import cv2

import numpy as np

#events = [i for i in dir(cv2) if 'EVENT' in i]

#print (events)

class MousePts:

def __init__(self,windowname,img):

self.windowname = windowname

self.img1 = img.copy()

self.img = self.img1.copy()

cv2.namedWindow(windowname,cv2.WINDOW_NORMAL)

cv2.imshow(windowname,img)

self.curr_pt = []

self.point = []

def select_point(self,event,x,y,flags,param):

if event == cv2.EVENT_LBUTTONDOWN:

self.point.append([x,y])

#print(self.point)

cv2.circle(self.img,(x,y),5,(0,255,0),-1)

elif event == cv2.EVENT_MOUSEMOVE:

self.curr_pt = [x,y]

#print(self.point)

def getpt(self,count=1,img=None):

if img is not None:

self.img = img

else:
Join Stack Overflow to learn, share knowledge, and build your career.
self.img = self.img1.copy()

cv2.namedWindow(self.windowname,cv2.WINDOW_NORMAL)

Sign up with email


Sign up with Google
cv2.imshow(self.windowname,self.img)

Sign up with GitHub
Sign up with Facebook
cv2.setMouseCallback(self.windowname,self.select_point)

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 6/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow
self.point = []

while(1):

cv2.imshow(self.windowname,self.img)

k = cv2.waitKey(20) & 0xFF

if k == 27 or len(self.point)>=count:

break

#print(self.point)

cv2.setMouseCallback(self.windowname, lambda *args : None)

#cv2.destroyAllWindows()

return self.point, self.img

if __name__=='__main__':

img = np.zeros((512,512,3), np.uint8)

windowname = 'image'

coordinateStore = MousePts(windowname,img)

pts,img = coordinateStore.getpt(3)

print(pts)

pts,img = coordinateStore.getpt(3,img)

print(pts)

cv2.imshow(windowname,img)

cv2.waitKey(0)

Share Improve this answer Follow answered Apr 19 '20 at 17:07


Jerin
11 3

In case, you want to get the coordinates by hovering over the image in Python 3, you could try this:

0 import numpy as np

import cv2 as cv

import os

import sys

# Reduce the size of image by this number to show completely in screen

descalingFactor = 2

Join Stack
# mouse callback function, which Overflow
will print to learn, share
the coordinates knowledge,
in console
and build your career.
def print_coord(event,x,y,flags,param):

if event == cv.EVENT_MOUSEMOVE:

Sign up with email


Sign up with Google
Sign up with GitHub
Sign up with Facebook
print(f'{x*descalingFactor, y*descalingFactor}\r', end="")

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 7/8
15/8/2021 python 2.7 - Opencv: detect mouse position clicking over a picture - Stack Overflow

img = cv.imread(cv.samples.findFile('TestImage.png'))

imgheight, imgwidth = img.shape[:2]

resizedImg = cv.resize(img,(int(imgwidth/descalingFactor),
int(imgheight/descalingFactor)), interpolation = cv.INTER_AREA)

cv.namedWindow('Get Coordinates')

cv.setMouseCallback('Get Coordinates',print_coord)

cv.imshow('Get Coordinates',resizedImg)

cv.waitKey(0)

Share Improve this answer Follow edited Sep 25 '20 at 12:32 answered Sep 25 '20 at 12:08
Fawaz Ahmed
451 5 16

Join Stack Overflow to learn, share knowledge, and build your career.

Sign up with email


Sign up with Google
Sign up with GitHub
Sign up with Facebook

https://stackoverflow.com/questions/28327020/opencv-detect-mouse-position-clicking-over-a-picture 8/8

You might also like