简体   繁体   中英

numpy vstack with images

I am writing a function to read pixel data from images and store them in a numpy array to further do a train/test split.

When I run this code it throws an exception saying that all the input array dimensions except for the concatenation axis must match exactly.

I am not sure why this issue happens and how to fix it.

from PIL import Image
import numpy as np
import os

X = np.array([])
y = []

categories = {
    'A': 1,
    'B': 2
}

root = data_dir + '/cropped_resized(128,128)/'

for path, subdirs, files in os.walk(root):
    for name in files:
        img_path = os.path.join(path,name)
        category = categories[os.path.basename(path)]
        im = Image.open(img_path)
        img_pixels = list(im.getdata())
        width, height = im.size
        X = np.vstack((X, img_pixels))
        #X = np.concatenate((X, img_pixels), axis=0)
        y.append(category)

X_train, X_test, y_train, y_test = train_test_split(X, y)

Here is an example of a picture that fails

在此处输入图片说明

Decide if you want your images as RGB or Greyscale and ensure that they are so on load.

Specifically, change this line:

im = Image.open(img_path)

to

im = Image.open(img_path).convert('RGB')

or

im = Image.open(img_path).convert('L')

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