Cur*_* F. 5 python numpy ipython-notebook bokeh
我有兴趣使用Bokeh将图像放入IPython笔记本中.特别是我经常与之交互的数据类型是具有3个或更多维度的多维NumPy数组.以三维数组为例.经常遇到的例子是RGB图像.这三个维度x,y以及color
我有兴趣使用Bokeh在IPython笔记本中绘制单个图像通道.我想提供一个交互式滑块,允许IPython笔记本的用户点击第三维的每个索引,在本例中为颜色.
我下面的代码(在IPython笔记本中运行时)成功显示了第一个颜色通道的图.但我无法弄清楚在我的电话中导致错误的原因interact.我ColumnDataSource是否在Bokeh图构造中正确定义并正确引用了?
# imports
import numpy as np
from scipy.misc import imread
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import ColumnDataSource
from bokeh.palettes import Greys9
from IPython.html.widgets import interact
Run Code Online (Sandbox Code Playgroud)
# enable Bokeh to plot to the notebook
output_notebook()
# Make the Bokeh plot of the "first" layer of the 3D data
## This part works
TOOLS="pan, box_zoom, reset, save"
# The image from https://windycitizensports.files.wordpress.com/2011/10/baboon.jpg?w=595
RGB_image = imread('/Users/curt/Downloads/BaboonRGB.jpg')
nx, ny, n_colors = RGB_image.shape
source = ColumnDataSource(data={'image': RGB_image[:, :, 0]})
p = figure(title="ColorChannel",
tools=TOOLS,
x_range=[0, nx],
y_range=[0, ny],
)
p.image([source.data['image'][::-1, :]-1],
x=0,
y=0,
dh=[ny],
dw=[nx],
palette=Greys9,
source=source,
)
show(p)
Run Code Online (Sandbox Code Playgroud)
# try to add interactive slider
## This part does not work & gives a JavaScript error
def update(idx=0):
global RGB_image
source.data['image'] = RGB_image[:, :, idx]
source.push_notebook()
interact(update, idx=(0, 2))
Run Code Online (Sandbox Code Playgroud)
Javascript错误是:
Javascript error adding output!
TypeError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The provided float value is non-finite.
See your browser Javascript console for more details.
Run Code Online (Sandbox Code Playgroud)
我不确定这是怎么回事.我在定义之后立即尝试强制RGB_Image执行浮动,RGB_Image = RGB_Image.astype(float)但是我得到了同样的错误.
实质上,您的预定义图像与您尝试更新的图像之间的数据格式不一致.
有效的解决方法:
def update(idx=0):
global RGB_image
source.data['image'] = RGB_image[:, :, idx]
p.image([source.data['image'][::-1, :]-1],
x=0,
y=0,
dh=[ny],
dw=[nx],
palette=Greys9,
source=source,
)
show(p)
interact(update, idx=(0, 2))
Run Code Online (Sandbox Code Playgroud)
我会承认,一遍又一遍地定义图像并不是这样做的首选方法,但至少应该让你知道在哪里看.