我正在尝试从包含字典列表的python代码中加载一个数据库。对于列表中的每一项,字典包含一个文件的名称,一个子列表,它包含n个不同的字典,其中一个文件名和数据是一个大小为40x40x3的numpy矩阵,并对应于一个图像。我希望在一个for循环中将所有这些图像存储在一个大小为Nx40x40x3的numpy文件中。
for item in dataset:
print item["name"] # the name of the list
print item["data"] # a list of dictionaries
for row in item["data"]:
print row["sub_name"] # the name of the image
print row["sub_data"] # contains an numpy array (my image)
我是如何构造一个数字数组并添加所有图像的?
发布于 2018-05-02 09:18:29
NumPy数组have fixed sizes,所以除非预先知道大小,否则必须使用一些可以更改大小的东西,比如python。
import numpy as np
images = []
for item in dataset:
for row in item["data"]:
images.append(row["sub_data"]) # Add to list
images = np.array(images) # Convert list to np.array()
发布于 2018-05-02 09:53:18
为了做到这一点,您要么需要使用大小可以像我在other answer中那样发生变化的数据类型,要么您也可以在定义数组之前计算出有多少图像。(如@P.Camilleri所建议)
这里有一个例子:
# Count nuber of images
idx_count = 0
for item in dataset:
idx_count += len(item['data'])
# Create an empty numpy array that's Nx3x3
images = np.empty((count, 3, 3))
# Populate numpy array with images
idx = 0
for item in dataset:
for row in item["data"]:
images[idx] = row["sub_data"]
idx += 1
print(images)
这样做的好处是您只分配了一次空间,用于使用python列表,首先将其添加到列表中,然后复制到numpy数组。
然而,这是以不得不重复两次数据为代价的。
(注:两种不同的答案,因为我不确定哪种解决方案更好,所以它们可以分开评定。)
https://stackoverflow.com/questions/50139993
复制相似问题