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

查看:68
本文介绍了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

来自PIL 文档:

获取数据

im.getdata() => 序列

im.getdata() => sequence

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

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天全站免登陆