“Python-OpenCV” Display BGR Value of Clicked Position on Image

Python
higashi
higashi

Hi, I’m higahsi.

 

This page introduce how to display BGR value of clicked position on image as shown below.

カラー画像のクリック位置のBGR値を取得している様子

You can confirm R value is high when red position is clicked, G value and B value is also high when the corresponding position is clicked respectively.

 

Although above movie shows clicked position’s BGR value you can just only mouse moving is also able to apply.

 

Sponsored Links

Sample Program of Display BGR value of Clicked Position

The below program can show the BGR value of mouse clicked position.

import cv2
import numpy as np
file_name='sample.jpg'
img=cv2.imread(file_name,cv2.IMREAD_COLOR)
img=cv2.resize(img,(1000,600))
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=(0,0,0),thickness=-1)
        B,G,R=img[y,x,:]
        bgr_str='(B,G,R)=('+str(B)+','+str(G)+','+str(R)+')'
        cv2.putText(img2,bgr_str,(30, 50),cv2.FONT_HERSHEY_PLAIN,2,(0,0,0),2,cv2.LINE_AA)
        cv2.imshow('window', img2)
        
cv2.imshow('window', img)
cv2.setMouseCallback('window', click_pos)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

When you conduct this program, new window will be displayed.

And left click on the window, BGR value will display at left top.

Result of sample program

 

Sponsored Links

Sample Program of Display BGR value of Cursor Position

Next, I introduce other pattern.

This is just only mouse moving.

import cv2
import numpy as np
file_name='sample.jpg'
img=cv2.imread(file_name,cv2.IMREAD_COLOR)
img=cv2.resize(img,(1000,600))
def click_pos(event, x, y, flags, params):
    if event == cv2.EVENT_MOUSEMOVE:
        img2=np.copy(img)
        cv2.circle(img2,center=(x,y),radius=5,color=(0,0,0),thickness=-1)
        B,G,R=img[y,x,:]
        bgr_str='(B,G,R)=('+str(B)+','+str(G)+','+str(R)+')'
        cv2.putText(img2,bgr_str,(30, 50),cv2.FONT_HERSHEY_PLAIN,2,(0,0,0),2,cv2.LINE_AA)
        cv2.imshow('window', img2)
        
cv2.imshow('window', img)
cv2.setMouseCallback('window', click_pos)
cv2.waitKey(0)
cv2.destroyAllWindows()

It is just changed “cv2.EVENT_LBUTTONDOWN” to “cv2.EVENT_MOUSEMOVE” from the program introduced before .

 

Please proper use according to the situation.

 

That’s all. Thank you!!

コメント