PIL图像到数组(numpy数组到数组) - Python [英] PIL image to array (numpy array to array) - Python

查看:605
本文介绍了PIL图像到数组(numpy数组到数组) - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .jpg image that I would like to convert to Python array, because I implemented treatment routines handling plain Python arrays.

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

It seems that PIL images support conversion to numpy array, and according to the documentation I have written this:

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

print(list(np.asarray(im)))

这是返回一个列表numpy数组。另外,我尝试了

This is returning a list of numpy arrays. Also, I tried with

list([list(x) for x in np.asarray(im)])

因为失败而没有任何返回。

which is returning nothing at all since it is failing.

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

How can I convert from PIL to array, or simply from numpy array to Python array?

推荐答案

我认为你是什么寻找的是:

I think what you are looking for is:

list(im.getdata())

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

or, if the image is too big to load entirely into memory, so something like that:

for pixel in iter(im.getdata()):
    print pixel


$ b来自 PIL文档的$ b


getdata

getdata

im.getdata()=> sequence

im.getdata() => sequence

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

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

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

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

这篇关于PIL图像到数组(numpy数组到数组) - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆