Jupyter笔记本内联图像中的光标位置和像素值

Dan*_*ick 11 python matplotlib

我正在使用带有Jupyter Notebook的Python 2.7.x,matplotlib和%pylab后端以及内联标志 %pylab inline 来打印活动单元格下方的图像.我希望能够将光标移动到图像上并知道它的位置和像素值一个例子可能是:(x,y,val)=(123,285,230)但我并不特别关注这个例子的任何细节.

Imp*_*est 17

%matpotlib inline后端显示的情节输出作为PNG图像.可以为Jupyter笔记本编写一些JavaScript,以获取鼠标在单元格输出中的图像上的颜色和像素.

然而,使用%matplotlib notebook后端可能要容易得多,这样可以在将matplotlib绘制到输出时保持matplotlib图形的活动,因此可以使用通常的内置鼠标悬停功能.

在此输入图像描述

请注意,在图像,其中显示的右下角的选择器x,y和当前像素的值.


And*_*rea 9

要扩展 ImportanceOfBeingErnest 的答案,您可以使用mpl_connect来提供点击回调并ipywidgets显示回调的输出。如果需要,您可以分解不同单元格中的代码。

%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as wdg  # Using the ipython notebook widgets

# Create a random image
a = np.random.poisson(size=(12,15))
fig = plt.figure()
plt.imshow(a)

# Create and display textarea widget
txt = wdg.Textarea(
    value='',
    placeholder='',
    description='event:',
    disabled=False
)
display(txt)

# Define a callback function that will update the textarea
def onclick(event):
    txt.value = str(event)  # Dynamically update the text box above

# Create an hard reference to the callback not to be cleared by the garbage collector
ka = fig.canvas.mpl_connect('button_press_event', onclick)
Run Code Online (Sandbox Code Playgroud)