Search code examples
pythonnumpyfor-loopfeature-extraction

Why am I getting a index error for my loop in python?


I am trying to divide a raw image into 8x8 overlapping blocks so I can do feature extraction later.

Here is my code:

new0 = np.zeros((heightimage0R, widthimage0R), np.uint8)
k = 0
for i in range(heightimage0R):
    for j in range(widthimage0R):
        crop_tmp0R = image0R[i:i+8,j:j+8]
        new0[k, 0:64] = crop_tmp0R.flatten()
        k = k + 1

However, when ever I run my code I get the following error:

Traceback (most recent call last):

  File "<ipython-input-392-cf9c59842d3a>", line 6, in <module>
    new0[k, 0:64] = crop_tmp0R.flatten()

IndexError: index 256 is out of bounds for axis 0 with size 256

I have tried widthimage0R-1 in the for loop but it still does not work.


Solution

  • new0 is of size heightimage0Rxwidthimage0R (which I'll refer to as hxw for now), which I assume is the same size of image0R (otherwise you have more problems).

    What your code is doing is taking a 8x8 square from image0R and flattening it into the new array.

    The problem arises because new0 is a hxw-matrix, but you're using it as a h*wx64-matrix. This is because the row has value k, which goes between 0 to h*w, and the column is always 64.

    My guess is that you mean to do the following:

    new0 = np.zeros((heightimage0R*widthimage0R, 64), np.uint8)
    k = 0
    for i in range(heightimage0R-8):  # Don't forget the -8 to not exceed the size of the image0R as well!
        for j in range(widthimage0R-8):
            crop_tmp0R = image0R[i:i+8,j:j+8]
            new0[k, 0:64] = crop_tmp0R.flatten()
            k = k + 1