What causes the size-dependent AttributeError attribute in the PIL fromarray function?

I get an error from the following Python3 code on the specified lines. x, y and z - all simple numpy 2D arrays are identical, but for size and should work the same. However, they act differently: with errors y and z, and x works fine.

import numpy as np
from PIL import Image

a = np.ones( ( 3,3,3), dtype='uint8' )
x = a[1,:,:]
y = a[:,1,:]
z = a[:,:,1]

imx = Image.fromarray(x)  # ok
imy = Image.fromarray(y)  # error
imz = Image.fromarray(z)  # error

but it works

z1 = 1*z
imz = Image.fromarray(z1)   # ok

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python3\lib\site-packages\PIL\Image.py", line 1918, in fromarray
    obj = obj.tobytes()
AttributeError: 'numpy.ndarray' object has no attribute 'tobytes'

So what is different from x, y, z, z1? Nothing I can say.

>>> z.dtype
dtype('uint8')
>>> z1.dtype
dtype('uint8')
>>> z.shape
(3, 4)
>>> z1.shape
(3, 4)

I am using Python 3.2.3 on a Windows 7 Enterprise machine with all 64-bit versions.

+5
source share
2 answers

ubuntu 12.04 Python 3.2.3, numpy 1.6.1 PIL 1.1.7-for-Python 3 http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil. , _ x , y z :

>>> x.__array_interface__['strides']
>>> y.__array_interface__['strides']
(9, 1)
>>> z.__array_interface__['strides']
(9, 3)

:

if strides is not None:
    obj = obj.tobytes()

tostring, tobytes:

# If obj is not contiguous, then the tostring method is called
# and {@link frombuffer} is used.

Python 2 Python 1.1.7 tostring:

if strides is not None:
    obj = obj.tostring()

, , 2--3, str/bytes. tobytes() tostring() Image.py :

Python 3.2.3 (default, May  3 2012, 15:54:42) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from PIL import Image
>>> 
>>> a = np.ones( ( 3,3,3), dtype='uint8' )
>>> x = a[1,:,:]
>>> y = a[:,1,:]
>>> z = a[:,:,1]
>>> 
>>> imx = Image.fromarray(x)  # ok
>>> imy = Image.fromarray(y)  # now no error!
>>> imz = Image.fromarray(z)  # now no error!
>>> 
+6

DSM. PIL 1.17.

ndarray .

x = np.asarray(img[:, :, 0] * 255., np.uint8)
image = Image.fromarray(x)
image.save("%s.png" % imgname)

, .

: scipy.msic.msave, .

scipy.msic.imsave(imgname, x)

! ".png" .

+2

All Articles