VansFannel
VansFannel

Reputation: 45921

Resize numpy array with a lot of dimensions

I'm using Python 3.7.7. I'm trying to resize a Numpy image array with this function:

def resize_image_array(image_array, rows_standard, cols_standard):

    # image_array.shape = (3929, 2, 256, 256, 1)
    # rows_standard = 200
    # cols_standard = 200

    # Height or row number.
    image_rows_Dataset = np.shape(image_array)[2]
    # Width or column number.
    image_cols_Dataset = np.shape(image_array)[3]

    num_rows_1 = ((image_rows_Dataset // 2) - (rows_standard / 2)) # num_rows_1 = 28.0
    num_rows_2 = ((image_rows_Dataset // 2) + (rows_standard / 2)) # num_rows_2 = 228.0
    num_cols_1 = ((image_cols_Dataset // 2) - (cols_standard / 2)) # num_cols_1 = 28.0
    num_cols_2 = ((image_cols_Dataset // 2) + (cols_standard / 2)) # num_cols_2 = 228.0

    return image_array[..., num_rows_1:num_rows_2, num_cols_1:num_cols_2, :]

But in the last statement I get this error:

TypeError: slice indices must be integers or None or have an __index__ method

I have also tried:

return image_array[:, :, num_rows_1:num_rows_2, num_cols_1:num_cols_2, :]

But with the same error as shown above.

How can I fix this error?

Upvotes: 1

Views: 83

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114320

The issue, as mentioned in the comments, is that using true divide (/) on vanilla python scalars returns a float, even if both operands are integers. The operator does not check for integer divisibility before performing the division. floats do not have an __index__ method, which converts int-like quantities to an actual int.

The simple solution is to replace / with //. However, the computation of num_rows_2 and num_cols_2 seems superfluous. If you know the values of rows_standard and cols_standard that you want, just add them to num_rows_1 and num_cols_1, respectively. This will result in a much more robust expression:

row_start = (image_array.shape[2] - rows_standard) // 2
row_end = row_start + rows_standard
col_start = (image_array.shape[3] - cols_standard) // 2
col_end = col_start + cols_standard
image_array[..., row_start:row_end, col_start:col_end, :]

Upvotes: 1

Related Questions