gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:01:05 25 4
gpt4 key购买 nike

我只是想知道有没有办法使用 numpy 和 PIL 在 python 中导入图像,使其成为二维数组?此外,如果我有一张黑白图像,是否可以将黑色设置为 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 数组?

最佳答案

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

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)

如果将图片转换为黑白,则数组会自动变为二维:

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

关于python - 将图像作为二维数组导入 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com