图像的轮廓图给出:TypeError输入必须是2D数组错误

时间:2013-11-07 12:28:06

标签: python python-2.7 numpy matplotlib scipy

我正在使用Debian Linux和python 2.7 我正在阅读图像并尝试处理它但我显示以下错误。有人可以告诉我我做错了吗?

import Image
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
import scipy.misc

img = scipy.misc.imread("/home/subhradeep/Desktop/test.jpg")
array=np.asarray(img)
plt.figure(figsize=(10, 3.6))

plt.subplot(131)
plt.imshow(array, cmap=plt.cm.gray)

plt.subplot(132)
plt.imshow(array, cmap=plt.cm.gray, vmin=10, vmax=100)
plt.axis('off')

plt.subplot(133)
plt.imshow(array, cmap=plt.cm.gray)
plt.contour(array, [160, 211])
plt.axis('off')

plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.05,right=0.99)
plt.show()

我收到以下错误消息

Traceback (most recent call last):
  File "1saveimg.py", line 22, in <module>
    plt.contour(array, [160, 211])
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2632, in contour
    ret = ax.contour(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 7976, in contour
    return mcontour.QuadContourSet(self, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1414, in __init__
    ContourSet.__init__(self, ax, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 860, in __init__
    self._process_args(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1427, in _process_args
    x, y, z = self._contour_args(args, kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1488, in _contour_args
    x, y = self._initialize_x_y(z)
  File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1573, in _initialize_x_y
    raise TypeError("Input must be a 2D array.")
TypeError: Input must be a 2D array.

我也试过了Image.open(),但这也引发了同样的错误。

1 个答案:

答案 0 :(得分:5)

这里的问题是plt.contour只绘制了2d数组,但大多数jpg文件都是3d,因为有三种颜色。你通过使用灰度色图(cm.gray)进行绘图来隐藏这一事实,这只会改变它的外观(imshow仍在显示彩色图像,只是用灰色'墨水'打印)。你有几个选择,主要是:

1)以某种方式将其转换为2d,最简单的方法是将图像设为黑白(灰度)。以下是一些方法:

gray = img.sum(-1)  # sums along the last (color) axis

gray = np.sqrt((img*img).sum(-1)) # to do a magnitude of the color vector

from PIL import Image
img = Image.open("/home/subhradeep/Desktop/test.jpg")
gray = img.convert('L')   # 'L' stands for 'luminosity'
gray = np.asarray(gray)

2)分别绘制每种颜色:

r, g, b = np.rollaxis(img, -1)
plt.contour(r, cmap=plt.cm.Reds)
plt.contour(g, cmap=plt.cm.Greens)
plt.contour(b, cmap=plt.cm.Blues)

此外,

scipy.misc.imread会返回一个数组,因此您可以跳过arr = np.asarray(img)行,并按原样使用img。如果您决定使用返回PIL.Image对象的PIL.Image对象(因此可以使用img.convert方法),则情况并非如此。

这样做是多余的,只需选择其中一个:

from scipy import misc
import scipy.misc

此处如果您转换为灰度: gray

并且,如果您分别绘制每种颜色: rgb