我想将多个RGB图像读取为numpy数组。我的所有图像都是分辨率(32,32,3)。我在文件夹中有10个图像,我想要我的最终"图像" numpy数组为(10,32,32,3)。我试过下面的代码。
import matplotlib.image as mpimg
import os
folder = 'test_images'
images = np.array([(mpimg.imread(os.path.join(folder, filename))) for filename in os.listdir('test_images')], dtype='uint8')
我得到以下错误
ValueError Traceback (most recent call last)
<ipython-input-109-0c5d51212e48> in <module>()
3
4 folder = 'test_images'
----> 5 images = np.array([(mpimg.imread(os.path.join(folder, filename))) for filename in os.listdir('test_images')], dtype='uint8')
6
7 print(len(images))
ValueError: could not broadcast input array from shape (32,32,3) into shape (32,32)
答案 0 :(得分:1)
总结一下解决方案,我会做以下几点:
from PIL import Image
import os, numpy as np
folder = 'test_images'
read = lambda imname: np.asarray(Image.open(imname).convert("RGB"))
ims = [read(os.path.join(folder, filename)) for filename in os.listdir(folder)]
im_array = np.array(ims, dtype='uint8')