将相同形状的动态图像读取到Python NumPy数组中

时间:2018-06-21 10:28:55

标签: python numpy opencv image-processing glob

我有此代码:

image_list = []
for filename in glob.glob('C:\\Users\\Utilizador\\Desktop\\menu\\*.jpg'): 
    im=cv2.imread(filename)
    image_list.append(im)

这会为我创建一个图像列表,但我需要它采用形状为(num_of_images,宽度,高度,3)的数组形式

所有图像都具有相同的形状 有任何想法吗? 谢谢

1 个答案:

答案 0 :(得分:1)

由于所有图像都具有相同的形状,因此我们可以创建一个空数组,然后将每个图像读入其中。

In [103]: file_path = 'C:\\Users\\Utilizador\\Desktop\\menu\\*.jpg'
In [104]: num_imgs = len(glob.glob(file_path))
In [105]: width, height, channels = 512, 512, 3

In [106]: batch_arr = np.empty((num_imgs, width, height, channels), dtype=np.uint8)

In [107]: for idx, filename in enumerate(glob.glob(file_path)):
              img = cv2.imread(filename)
              # if img is of different width and height than defined above
              # do some resize and then insert in the array.
              batch_arr[idx] = img