0

Say I have a for loop which runs 10 times, and each loop generates a NumPy array of shape (32, 128). How do I iteratively combine them in the loop to finally get a NumPy array of shape (10, 32, 128, 1)?

Here I'm working on the IAM Database for handwriting recognition. So here I want the numpy array to store all my images as pixels

file = open(path, 'rb')
l = file.readlines()
y_train = np.array([])
x_train = np.array([])
count = 0
for x in l:
    a = x.split()
    y_train = np.append(y_train, str(a[-1].decode("utf-8")))
    path1 = a[0].decode("utf-8").split('-')
    os.chdir(path_toimages + path1[0] + '/' + path1[0] + '-' + path1[1])
    try:
        im = Image.open(a[0].decode("utf-8") + ".png")
        np_im = np.array(im)

        np_im = preprocess(np_im, (32, 128))

        x_train = np.append((x_train, np_im))
        print(np_im.shape)

    except OSError:
        continue
    count += 1
    print(count)
    if count == 10:
        break
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 1
    It's better to collect them in a list, and make one array at the end. List append is faster and easier to use than np.append – hpaulj Sep 30 '19 at 04:12
  • Possible duplicate of [What is the fastest way to stack numpy arrays in a loop?](https://stackoverflow.com/questions/58083743/what-is-the-fastest-way-to-stack-numpy-arrays-in-a-loop) – Joe Sep 30 '19 at 06:48

1 Answers1

0

Since you already know x_train's shape you could define an array with that shape. Then add the newly processed images to x_train[index] while increementing the index for every iteration.

Djbhai
  • 81
  • 1
  • 3