Search code examples
pythonnumpyimage-processingchainer

Creating batches within an array containing images


I have an array X_train containing 9957 images. I am making a Convolutional network.The desired shape of the array for feeding into the model is (batchsize, channel, height, width)

X_train.shape #gives (9957, 60, 80, 3)
X_train[1].shape #gives (60, 80, 3)

If we use

np.reshape(X_train,(-1, 3, 60, 80)) #it gives (9957, 3, 60, 80)

How can I get each array with shape (batchsize, 3, 60, 80) and the final image array for training with shape(9957, batchsize, 3, 60, 80)?


Solution

  • You can get from i-th image until i + batchsize image as follows.

    batchsize = 16
    i = 0
    
    X_batch = X_train[i: i+batchsize]
    print('X_batch.shape: ', X_batch.shape)  # it should be (16, 3, 60, 80)
    

    Please change i with for loop to get each image. For example,

    for i in range(0, len(X_train), batchsize):
        X_batch = X_train[i: i+batchsize]
    
        # --- Do something with X_batch ---