matplotlib的imshow中的颜色值?
我想知道当我在使用matplotlib的imshow()时,点击的那个点的颜色值。有没有办法通过matplotlib的事件处理器来获取这个信息?就像我可以获取点击的x和y坐标一样。如果没有,那我该怎么找到这个信息呢?
具体来说,我在想这样的情况:
imshow(np.random.rand(10,10)*255, interpolation='nearest')
谢谢!
--Erin
4 个回答
1
如果你说的“颜色值”是指在图表上点击某个点时,那个点对应的数组值,那么这个功能是很有用的。
from matplotlib import pyplot as plt
import numpy as np
class collect_points():
omega = []
def __init__(self,array):
self.array = array
def onclick(self,event):
self.omega.append((int(round(event.ydata)), int(round(event.xdata))))
def indices(self):
plot = plt.imshow(self.array, cmap = plt.cm.hot, interpolation = 'nearest', origin= 'upper')
fig = plt.gcf()
ax = plt.gca()
zeta = fig.canvas.mpl_connect('button_press_event', self.onclick)
plt.colorbar()
plt.show()
return self.omega
使用方法大概是这样的:
from collect_points import collect_points
import numpy as np
array = np.random.rand(10,10)*255
indices = collect_points(array).indices()
会出现一个绘图窗口,你可以点击一些点,然后会返回这些点在numpy数组中的索引。
1
上面的解决方案只适用于单张图片。如果你在同一个脚本中绘制两张或更多的图片,"inaxes"事件就无法区分这两个坐标轴。你永远不知道你点击的是哪个坐标轴,所以也就不知道应该显示哪张图片的数值。
10
这里有一个可以用的解决方案。它只适用于 interpolation = 'nearest'
这种情况。我还在寻找一种更简单的方法来从图像中获取插值值(而不是对选定的 x 和 y 进行四舍五入,然后从原始数组中选择)。总之:
from matplotlib import pyplot as plt
import numpy as np
im = plt.imshow(np.random.rand(10,10)*255, interpolation='nearest')
fig = plt.gcf()
ax = plt.gca()
class EventHandler:
def __init__(self):
fig.canvas.mpl_connect('button_press_event', self.onpress)
def onpress(self, event):
if event.inaxes!=ax:
return
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
color = im.cmap(im.norm(value))
print xi,yi,value,color
handler = EventHandler()
plt.show()