将图像作为二维数组导入python

Ben*_*Ben 5 python arrays numpy python-imaging-library

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

目前我正在使用:

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

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

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

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

Pan*_*pas 5

我不是专家,但我可以想到一些方法,但不确定您想要实现的目标,因此您可能不喜欢我的解决方案:

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
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用 .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)
Run Code Online (Sandbox Code Playgroud)

如果将图片转换为黑白,则数组会自动变为 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
Run Code Online (Sandbox Code Playgroud)