将图像作为2D数组导入python

时间:2014-11-05 18:40:10

标签: python arrays numpy python-imaging-library

我只是想知道有没有办法在python中使用numpy和PIL导入图像以使其成为2D数组?此外,如果我有黑白图像,可以将黑色设置为1,将白色设置为零吗?

目前我正在使用:

temp=np.asarray(Image.open("test.jpg"))
frames[i] = temp #frames is a 3D array

有了这个我得到一个错误:

ValueError:操作数无法与形状(700,600)(600,700,3)一起广播

我是python的新手,但据我所知,这意味着基本上temp是一个3D数组,我将它分配给2D数组?

1 个答案:

答案 0 :(得分:4)

我不是专家,但我可以想办法,不知道你想要达到什么目的,所以你可能不喜欢我的解决方案:

from PIL import Image
from numpy import*

temp=asarray(Image.open('test.jpg'))
for j in temp:
    new_temp = asarray([[i[0],i[1]] for i in j]) # new_temp gets the two first pixel values

此外,您可以使用.resize():

from PIL import Image
from numpy import*

temp=asarray(Image.open('test.jpg'))
x=temp.shape[0]
y=temp.shape[1]*temp.shape[2]

temp.resize((x,y)) # a 2D array
print(temp)

如果您将图片转换为黑白,则数组将自动变为2D:

from PIL import Image
from numpy import*

temp=Image.open('THIS.bmp')
temp=temp.convert('1')      # Convert to black&white
A = array(temp)             # Creates an array, white pixels==True and black pixels==False
new_A=empty((A.shape[0],A.shape[1]),None)    #New array with same size as A

for i in range(len(A)):
    for j in range(len(A[i])):
        if A[i][j]==True:
            new_A[i][j]=0
        else:
            new_A[i][j]=1