使用matplotlib将数组保存为灰度'L'图像的问题?

时间:2013-01-26 05:02:50

标签: arrays matplotlib

我正在尝试使用plt.imsave()将数组保存为图像。原始图像是16灰度'L'tiff。但我一直在收到错误:

属性错误:'str'对象没有属性'shape'     figsize = [x / float(dpi)for x in(arr.shape [1],arr.shape [0])]

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np 
from PIL import Image

im2=plt.imread('C:\Documents\Image\pic.tif')
plt.imsave(im2, '*.tif')

图像为2048x2048,阵列为2048Lx2048L。我试过的一切都不起作用:shape = [2048,2048],im2.shape(2048,2048)。任何人都可以告诉我如何添加形状作为关键字参数?或者有没有更简单的方法来做到这一点,最好避免PIL,因为它似乎有16位灰度tiff的问题,我绝对必须使用那种格式?

1 个答案:

答案 0 :(得分:1)

我认为你有倒退的论点。来自help(plt.imsave)

Help on function imsave in module matplotlib.pyplot:

imsave(*args, **kwargs)
    Saves a 2D :class:`numpy.array` as an image with one pixel per element.
    The output formats available depend on the backend being used.

    Arguments:
      *fname*:
        A string containing a path to a filename, or a Python file-like object.
        If *format* is *None* and *fname* is a string, the output
        format is deduced from the extension of the filename.
      *arr*:
        A 2D array.

即:

>>> im2.shape
(256, 256)
>>> plt.imsave(im2, "pic.tif")
Traceback (most recent call last):
  File "<ipython-input-36-a7bbfaeb1a4c>", line 1, in <module>
    plt.imsave(im2, "pic.tif")
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1753, in imsave
    return _imsave(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1230, in imsave
    figsize = [x / float(dpi) for x in arr.shape[::-1]]
AttributeError: 'str' object has no attribute 'shape'

>>> plt.imsave("pic.tif", im2)
>>>