Skip to content Skip to sidebar Skip to footer

Initial Value Numpy Array Before Starting The Function In Python

I want to put data of a image in a numpy array, but every time I get the error ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2

Solution 1:

The use of np.append in this function is a bad idea. (any use of np.append is bad):

X_test = np.empty((4,1), np.float32)
def load_images_to_data(image_label, image_directory, features_data, label_data):
    list_of_files = os.listdir(image_directory)
    for file in list_of_files:
        image_file_name = os.path.join(image_directory, file)
        if ".png" in image_file_name:
            img = Image.open(image_file_name).convert("L")
            img = np.resize(img, (28,28,1))
            im2arr = np.array(img)
            im2arr = im2arr.reshape(1,28,28,1)
            features_data = np.append(features_data, im2arr, axis=0)
            label_data = np.append(label_data, [image_label], axis=0)
    return features_data, label_data

As you found out it is hard to get the initial value of features_data right. And it is slow, creating a whole new array each call.

np.append(A,B, axis=0) just does np.concatenate([A,B], axis=0). Give it the whole list of arrays, rather than doing the concatenate one by one.

def load_images_to_data(image_label, image_directory):
    list_of_files = os.listdir(image_directory)
    alist = []; blist = []
    for file in list_of_files:
        image_file_name = os.path.join(image_directory, file)
        if ".png" in image_file_name:
            img = Image.open(image_file_name).convert("L")
            img = np.resize(img, (28,28,1))
            im2arr = np.array(img)
            im2arr = im2arr.reshape(1,28,28,1)
            alist.append(im2arr)
            blist.append([image_label]
    features_data = np.concatenate(alist, axis=0)
    label_data = np.concatenate(blist, axis=0)
    return features_data, label_data

Post a Comment for "Initial Value Numpy Array Before Starting The Function In Python"