[Python and OpenCV] Display the Coordinates of a Clicked Point

Python
higashi
higashi

Hi, I’m Higashi.

 

Here’s how to display the coordinates of a point you click in an image.

クリック位置の座標を表示するという処理内容を説明する動画

Let’s get started!

 

Sponsored Links

Required libraries

• OpenCV

• NumPy

Install these libraries if you don’t already have them.

 

Sponsored Links

Sample code for displaying clicked coordinates

The program below marks the point you click and shows its coordinates.

import cv2
import numpy as np
file_name='sample.jpg'
img=cv2.imread(file_name,cv2.IMREAD_GRAYSCALE)

def click_pos(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDOWN:
        img2 = np.copy(img)
        cv2.circle(img2,center=(x,y),radius=5,color=255,thickness=-1)
        pos_str='(x,y)=('+str(x)+','+str(y)+')'
        cv2.putText(img2,pos_str,(x+10, y+10),cv2.FONT_HERSHEY_PLAIN,2,255,2,cv2.LINE_AA)
        cv2.imshow('window', img2)
        
cv2.imshow('window', img)
cv2.setMouseCallback('window', click_pos)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here’s what it does:

  1. Load the image.
  2. Display it in a window.
  3. Read the coordinates when you click.
  4. Draw a marker and the coordinates on the image, then display it again.

 

Sponsored Links

Show the coordinates as the mouse moves

You can also show the cursor’s coordinates as it moves across the image, as in the video below.

 

Here’s the modified code.

import cv2
import numpy as np
file_name='mouse.jpg'
img=cv2.imread(file_name,cv2.IMREAD_GRAYSCALE)

def mouse_move(event, x, y, flags, params):
    if event == cv2.EVENT_MOUSEMOVE:
        img2 = np.copy(img)
        cv2.circle(img2,center=(x,y),radius=5,color=255,thickness=-1)
        pos_str='(x,y)=('+str(x)+','+str(y)+')'
        cv2.putText(img2,pos_str,(30, 30),cv2.FONT_HERSHEY_PLAIN,2,255,2,cv2.LINE_AA)
        cv2.imshow('window', img2)
     
cv2.imshow('window', img)
cv2.setMouseCallback('window', mouse_move)
cv2.waitKey(0)
cv2.destroyAllWindows()

Replace cv2.EVENT_LBUTTONDOWN, the left-click event, with cv2.EVENT_MOUSEMOVE, the mouse-movement event.

 

Use click events for points you want to mark, or mouse-move events for live coordinates.

 

Thanks for reading!

 

コメント