简体   繁体   English

程序使用python Tkinter识别鼠标单击时的像素颜色

[英]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. 我用python编写了一个小脚本,以便可以单击图像,程序会向我返回单击图像的点的BGR中的像素位置和像素颜色。

I use the click position to access the image numpy array (via cv.imread). 我使用点击位置来访问图像numpy数组(通过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! 提前非常感谢您的帮助!

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])

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) . 我过去做过非常类似的事情的一个问题是,当坐标为(x, y)和坐标为(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] 当TK给您返回x和y坐标时,OpenCV的像素寻址方案是底层numpy ndarray的像素寻址方案-image 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 . 有关何时使用它们的更多信息,请查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM