1

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: enter image description here

Thanks a lot in advance for any help!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This solved my problem and saved me a lot of time! The link is instructive too.
Glad I could help!
1

You interchanged the coordinates of the image. Make the following changes inside the function -

print (imgCV[event.y, event.x])
print (hsv[event.y, event.x])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.