python imshow cmap_用pylab.imshow()显示图像

在尝试使用pylab.imshow()显示图像时遇到了TypeError,问题在于输入的图像数据维度不正确。解决方案是通过numpy的squeeze()函数去除额外的维度,使3D ndarray转换为2D,以便正确显示图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm relatively new to all this and I started to do the tutorial on image analysis here: http://www.pythonvision.org/basic-tutorial

I have installed all the modules but I didn't get very far before hitting a snag.

when trying to perform the pylab.imshow(dna) step it returns the following error:

In [10]: pylab.imshow(dna)

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in ()

----> 1 pylab.imshow(dna)

/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, hold, **kwargs)

2375 ax.hold(hold)

2376 try:

-> 2377 ret = ax.imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)

2378 draw_if_interactive()

2379 finally:

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)

6794 filterrad=filterrad, resample=resample, **kwargs)

6795

-> 6796 im.set_data(X)

6797 im.set_alpha(alpha)

6798 self._set_artist_props(im)

/usr/lib/pymodules/python2.7/matplotlib/image.pyc in set_data(self, A)

409 if (self._A.ndim not in (2, 3) or

410 (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):

--> 411 raise TypeError("Invalid dimensions for image data")

412

413 self._imcache =None

TypeError: Invalid dimensions for image data

Fairly certain I have followed all the instructions in the tutorial to the letter but I can't work out was is going wrong

Thanks

解决方案

"it's just what the image is saved as in dna = mahotas.imread('dna.jpeg') type(dna) gives numpy.ndarray and dna.shape gives (1024, 1344, 1) "

This is the problem, if you hand in a 3D ndarray, it expects that you will have 3 or 4 planes (RGB or RGBA). (Read the code on line 410 in the last frame of the stack trace).

You just need to get rid of the extra dimension using

dna = dna.squeeze()

or

imshow(dna.squeeze())

To see what squeeze is doing, see the following example:

a = np.arange(25).reshape(5, 5, 1)

print a.shape # (5, 5, 1)

b = a.squeeze()

print b.shape # (5, 5)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值