The Wayback Machine - https://web.archive.org/web/20240820221034/https://www.geeksforgeeks.org/displaying-the-coordinates-of-the-points-clicked-on-the-image-using-python-opencv/
Open In App

Displaying the coordinates of the points clicked on the image using Python-OpenCV

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment :

import cv2
[print(i) for i in dir(cv2) if 'EVENT' in i]

Output : 

EVENT_FLAG_ALTKEY
EVENT_FLAG_CTRLKEY
EVENT_FLAG_LBUTTON
EVENT_FLAG_MBUTTON
EVENT_FLAG_RBUTTON
EVENT_FLAG_SHIFTKEY
EVENT_LBUTTONDBLCLK
EVENT_LBUTTONDOWN
EVENT_LBUTTONUP
EVENT_MBUTTONDBLCLK
EVENT_MBUTTONDOWN
EVENT_MBUTTONUP
EVENT_MOUSEHWHEEL
EVENT_MOUSEMOVE
EVENT_MOUSEWHEEL
EVENT_RBUTTONDBLCLK
EVENT_RBUTTONDOWN
EVENT_RBUTTONUP

Now let us see how to display the coordinates of the points clicked on the image. We will be displaying both the points clicked by right-click as well as left-click.

Algorithm : 

  1. Import the cv2 module.
  2. Import the image using the cv2.imread() function.
  3. Display the image the image using the cv2.imshow() function.
  4. Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters.
  5. In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute.
  6. Display the coordinates on the Shell.
  7. Display the coordinates on the created window.
  8. Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks.
  9. Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program.

We will be using the colored version of the Lena image.  


Python3




# importing the module
import cv2
   
# function to display the coordinates of
# of the points clicked on the image 
def click_event(event, x, y, flags, params):
  
    # checking for left mouse clicks
    if event == cv2.EVENT_LBUTTONDOWN:
  
        # displaying the coordinates
        # on the Shell
        print(x, ' ', y)
  
        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, str(x) + ',' +
                    str(y), (x,y), font,
                    1, (255, 0, 0), 2)
        cv2.imshow('image', img)
  
    # checking for right mouse clicks     
    if event==cv2.EVENT_RBUTTONDOWN:
  
        # displaying the coordinates
        # on the Shell
        print(x, ' ', y)
  
        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        b = img[y, x, 0]
        g = img[y, x, 1]
        r = img[y, x, 2]
        cv2.putText(img, str(b) + ',' +
                    str(g) + ',' + str(r),
                    (x,y), font, 1,
                    (255, 255, 0), 2)
        cv2.imshow('image', img)
  
# driver function
if __name__=="__main__":
  
    # reading the image
    img = cv2.imread('lena.jpg', 1)
  
    # displaying the image
    cv2.imshow('image', img)
  
    # setting mouse handler for the image
    # and calling the click_event() function
    cv2.setMouseCallback('image', click_event)
  
    # wait for a key to be pressed to exit
    cv2.waitKey(0)
  
    # close the window
    cv2.destroyAllWindows()


Output :

 



Previous Article
Next Article

Similar Reads

OpenCV | Displaying an Image
To read an image file from videos or cameras having a wide range of types, OpenCV provides a good amount of utilities. OpenCV has such a toolkit known as HighGUI, which is a part of one of its utilities. Some of these utilities are used in this article to display and open an image on our system. Let's understand line by line execution of the progra
4 min read
Python - Displaying real time FPS at which webcam/video file is processed using OpenCV
We will be displaying the real-time processing FPS of the video file or webcam depending upon our choice.FPS or frame per second or frame rate can be defined as number of frames displayed per second. A video can be assumed as a collection of images or we can say frames which are displayed at some rate to produce motion. if you wish to identify the
4 min read
Mapping coordinates from 3D to 2D using OpenCV - Python
Mapping 3D coordinates to 2D coordinates is a common task in computer vision. This process involves transforming 3D points in a virtual space to their corresponding positions on a 2D image plane. In this article, we'll show you how to perform this task using OpenCV in Python programming. OpenCV is an open-source computer vision and machine learning
6 min read
PyQtGraph – Export Clicked Signal of Image View
In this article, we will see how we can trigger the export clicked signal of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, vi
4 min read
PyQtGraph – Menu Clicked Signal of Image View
In this article, we will see how we can trigger the menu clicked signal of the image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, vide
4 min read
PyQtGraph – ROI Clicked Signal of Image View
In this article we will see how we can trigger the roi clicked signal of image view object in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc
4 min read
Convert OpenCV image to PIL image in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a
3 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
MoviePy – Displaying a Frame of Video Clip using inbuilt display method
In this article we will see how we can show a single frame at given time of the video file clip in MoviePy using inbuilt display method. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We
2 min read
Displaying 3D images in Python
In this article, we will discuss how to display 3D images using different methods, (i.e 3d projection, view_init() method, and using a loop) in Python. Module NeededMatplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciP
5 min read
Draw lines at the respective positions clicked by the mouse using Turtle
In this article, we will learn how to draw lines at any position which is clicked by the mouse using a turtle module. Turtle graphics:  turtle.listen(): Using this then we can give keyboard inputsturtle.onscreenclick(func,1 or 3): This function is used to bind function to a mouse-click event on canvas. 1 means left click and 3 means to right-click.
3 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Tableau - Displaying data in Worksheet
After creating the visualisations or while creating the visualisations if you want to look at the data in a worksheet, then, in that case, you need to follow some steps that we will see in this article. Steps to perform: In the Tableau, connect to the databases. The data source has three data files - Product, OrderDetails, PropertyInfo. These are t
3 min read
PyCairo - Displaying Text
In this article, we will learn how we can display text using PyCairo in python. PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read-only) is with a modern web browser like Chrome, Fi
2 min read
Django project - Creating a Basic E-commerce Website for Displaying Products
Project Title - Basic Ecommerce Website using Django Django is a powerful framework based on python. Here we will see how to create a basic e-commerce website in Django. This project includes storing products in the database and show them on the website. Refer to the following articles to check how to create a project and an app in Django. How to C
3 min read
Fetching and Displaying Data with HTMX and FastAPI
HTMX allows us to utilize current AJAX methods in HTML directly, while FastAPI is a strong backend framework for quick and efficient API development. This artilce will examine the way of combining HTMX with FastAPI to develop dynamic web applications. Setting Up FastAPIStep1. First we need Python installed on your machine. To check python installed
3 min read
Why is this simple Tkinter UI not displaying the specified label
Creating user interfaces with Tkinter in Python is a popular choice due to its simplicity and ease of use. However, even simple Tkinter applications can sometimes have issues that prevent them from working as expected. One common problem is when a specified label does not display on the UI. This article will explore potential reasons for this issue
3 min read
Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
PyQt5 QCalendarWidget - Clicked signal
In this article we will see how we can get the clicked signal from the QCalendarWidget. Clicked signal is emitted when a mouse button is clicked i.e when the mouse was clicked on the specified date. The signal is only emitted when clicked on a valid date, e.g., dates are not outside the minimum date and maximum date. If the selection mode is NoSele
2 min read
PyQt5 QCommandLinkButton - Clicked Signal
In this article we will see how we can get the clicked signal of the QCommandLinkButton. This signal is emitted when the button is activated, when the shortcut key is typed, or when click or animateClick method is called. Notably, this signal is not emitted if you call setDown, setChecked or toggle method. In order to do this we use clicked method
2 min read
How to check which Button was clicked in Tkinter ?
Are you using various buttons in your app, and you are being confused about which button is being pressed? Don't know how to get rid of this solution!! Don't worry, just go through the article. In this article, we will explain in detail the procedure to know which button was pressed in Tkinter. Steps to Check which Button was clicked in TkinterStep
2 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
Image Pyramid using OpenCV | Python
Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
1 min read
Negative transformation of an image using Python and OpenCV
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest an
4 min read
Python | Image blurring using OpenCV
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in smoothing the image. Low intensity edges are remov
2 min read
Find Circles and Ellipses in an Image using OpenCV | Python
To identify circles, ellipses, or in general, any shape in which the pixels are connected we use the SimpleBlobDetector() function of OpenCV. In non-technical terms, a blob is understood as a thick liquid drop. Here, we are going to call all shapes a blob. Our task is to detect and recognize whether the blob is a circle or not. OpenCV provides a co
2 min read
Image Translation using OpenCV | Python
Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. [Tex] \begin{bmatrix} 1 & 0 & tx \\ 0 & 1 & ty \end{bmatrix} [/Tex] where tx denotes the shift along
2 min read
Python | Detect Polygons in an Image using OpenCV
Approach : The approach we would be used to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg