Q:

Program to identify pixel color on mouse click using python Tkinter

I've written a small script in python, so that I can click on the image and the program returns to me the pixel position and the pixel color in BGR of the point where I click on the image.
I use the click position to access the image numpy array (via  cv.imread).
The problem is that the position returned is shifted from the original image. Somehow the actual size of the image gets modified and I get the wrong pixel color or get an index out of bounds. I tried using the same geometry of the original image, but it didn't work.
Here's the code:
# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
import Tkinter as tk
from PIL import ImageTk, Image
import sys
imgCV = cv.imread(sys.argv[1])
print(imgCV.shape)
root = tk.Tk()
geometry = "%dx%d+0+0"%(imgCV.shape[0], imgCV.shape[1])
root.geometry()
def leftclick(event):
    print("left")
    #print root.winfo_pointerxy()
    print (event.x, event.y)
    #print("BGR color")
    print (imgCV[event.x, event.y])
    # convert color from BGR to HSV color scheme
    hsv = cv.cvtColor(imgCV, cv.COLOR_BGR2HSV)
    print("HSV color")
    print (hsv[event.x, event.y])
# import image
img = ImageTk.PhotoImage(Image.open(sys.argv[1]))
panel = tk.Label(root, image = img)
panel.bind("<Button-1>", leftclick)
#panel.pack(side = "bottom", fill = "both", expand = "no")
panel.pack(fill = "both", expand = 1)
root.mainloop()

The test image I used is this:

Thanks a lot in advance for any help!

A:

An issue I have had in the past doing a very similar thing is keeping straight when the coordinates are (x, y) and when they are (row, col).
While TK is giving you back x and y coordinates, the pixel addressing scheme for OpenCV is that of the underlying numpy ndarray - image[row, col]
As such, the calls:
print (imgCV[event.x, event.y])
print (hsv[event.x, event.y])

Should be rewritten as:
print (imgCV[event.y, event.x])
print (hsv[event.y, event.x])

For more info regarding when to use each, check out this answer.

