简体   繁体   中英

Error when using astype('float32') in Python

I'm newbie in python and working with this code:

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')

But when runing I get error :

img_data = img_data.astype('float32') ValueError: setting an array element with a sequence.

Can anyone help me solve this?

Iterate through your list:

At the end of your code you appear to be trying to change the dtype of the images you have stored in your list. Images read with OpenCV are naturally numpy arrays.

The following example should help:

# 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM