PIL图像到数组(numpy数组到数组) - Python

kir*_*off 21 python arrays numpy image python-imaging-library

我有一个.jpg图像,我想转换为Python数组,因为我实现了处理普通Python数组的处理例程.

似乎PIL图像支持转换为numpy数组,并且根据我写的文档:

from PIL import Image
im = Image.open("D:\Prototype\Bikesgray.jpg")
im.show()

print(list(np.asarray(im)))
Run Code Online (Sandbox Code Playgroud)

这将返回一个numpy数组列表.另外,我试过了

list([list(x) for x in np.asarray(im)])
Run Code Online (Sandbox Code Playgroud)

由于它失败了,它什么都没有返回.

如何从PIL转换为数组,或者简单地从numpy数组转换为Python数组?

小智 18

我强烈建议您使用tobytesImage对象的功能.经过一些时间检查后,这会更有效率.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr
Run Code Online (Sandbox Code Playgroud)

我在笔记本电脑上播放的时间显示

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop
Run Code Online (Sandbox Code Playgroud)

```


zen*_*poy 16

我认为你在寻找的是:

list(im.getdata())
Run Code Online (Sandbox Code Playgroud)

或者,如果图像太大而无法完全加载到内存中,那么类似的东西:

for pixel in iter(im.getdata()):
    print pixel
Run Code Online (Sandbox Code Playgroud)

来自PIL文档:

的GetData

im.getdata()=>序列

将图像的内容作为包含像素值的序列对象返回.序列对象被展平,因此第一行的值紧跟在第0行的值之后,依此类推.

请注意,此方法返回的序列对象是内部PIL数据类型,它仅支持某些序列操作,包括迭代和基本序列访问.要将其转换为普通序列(例如用于打印),请使用list(im.getdata()).


Mar*_*oma 6

根据zenpoy的回答:

import Image
import numpy

def image2pixelarray(filepath):
    """
    Parameters
    ----------
    filepath : str
        Path to an image file

    Returns
    -------
    list
        A list of lists which make it simple to access the greyscale value by
        im[y][x]
    """
    im = Image.open(filepath).convert('L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map
Run Code Online (Sandbox Code Playgroud)