在Python中使用astype(';float32';)时出错

在Python中使用astype(';float32';)时出错,python,Python,我是python新手,正在使用以下代码: for index, person in enumerate(people): print(index) dir_path = 'train/' + person for img_path in os.listdir(dir_path): name, ext = os.path.splitext(img_path) if ext.lower() not in valid_images: continue img_data = c

我是python新手,正在使用以下代码:

for index, person in enumerate(people):
  print(index)
  dir_path = 'train/' + person
for img_path in os.listdir(dir_path):
  name, ext = os.path.splitext(img_path)
  if ext.lower() not in valid_images:
    continue

img_data = cv2.imread(dir_path + '/' + img_path)
# convert image to gray
img_data=cv2.cvtColor(img_data, cv2.COLOR_BGR2GRAY)
img_data_list.append(img_data)
labels.append(index)

img_data = np.array(img_data_list)
img_data = img_data.astype('float32')
但在运行时,我得到一个错误:

img_data=img_data.astype('float32'))
ValueError:使用序列设置数组元素。

有人能帮我解决这个问题吗?

反复浏览您的列表: 在代码末尾,您似乎试图更改存储在列表中的图像的
dtype
。使用OpenCV读取的图像自然是
numpy
数组

下面的例子应该会有所帮助:

# create a test image list
img = np.ones((60,60), dtype=np.uint8)
img_list = [img] * 4

# use a list comp to run through the images and change dtype
changed_img_list = [img.astype(np.float32) for i in img_list]

对谢谢你的帮助