I have started to learn OpenCV python library for remote sensing data processing. And when I open window by:

cv2.imshow

I can't know x,y coordinate and RGB values in current mouse position. How to realize that? How to get information about current coordinates and RGB values in OpenCV window?

I do it by standart method:

cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)           
cv2.imshow("image",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

UPD mouse event solution:

import cv2

import numpy as np from matplotlib import pyplot as plt

def momove (event,x,y,flags,param):
    if event == cv2.EVENT_MOUSEMOVE:
        strXY = str(x)+" . "+str(y)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img,strXY,(x,y), font, 1,(0,255,0),2)
        cv2.imshow('original', img)
        cv2.waitKey(300)
    if event == cv2.EVENT_LBUTTONDBLCLK:
        red = img[y,x,2]
        blue = img[y,x,0]
        green = img[y,x,1]
        print (red, green, blue)
        strRGB = str(red) + "," + str(green) + "," +str(blue)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img,strRGB,(x,y), font, 1,(255,255,255),2)
        cv2.imshow('original', img)
img=cv2.imread("C:/Users/komarov_av/Downloads/taiwan.tif",1)         
cv2.imshow('original',img)
cv2.setMouseCallback("original", momove)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • Several links immediately came up for mouse position in opencv, of which this one looks the most promising. Welcome to GIS.SE. Please take the tour, as this question isn't very hard to research. – John Powell Sep 13 at 9:23
  • Thank you for that solution! This is not what I want but as a temporary solution is OK – Tyomik_mnemonic Sep 14 at 10:31
  • If you want something different from what is in that solution, perhaps edit the question. You asked for accessing RGB values from a mouse click, which is definitely handled by that article. The RGB values are simply a numpy array after imread, after all, so accessing them is straightforward. – John Powell Sep 14 at 11:00
  • Thanks for the dialogue. Yes, I want RGB and x, y values. But the implementation of the approach does not look very good. Now I have mouseevent approach, it's EVENT_MOUSEMOVE (new code in question). And it looks like a desirable way. But i face one problem: how can I fix the text from cv2.putText to the mouse point? Without using a fixing text function to the cursor, if I move the mouse cursor RGB values and XY text, remain throughout all route of the mouse. Result looks like drawing by xy and rgb values)) – Tyomik_mnemonic Sep 14 at 12:39

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.