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

Viewed 68

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.

2 Answers

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
new0 = np.zeros((heightimage0R, widthimage0R), np.uint8)

Here, new0 is of shape heightimage0R x widthimage0R.

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()

Here we are trying to access k'th row of new0 where k goes up to (heightimage0R x widthimage0R). So after k crosses heightimage0R, it must be throwing error.

Can you be more specific of what you want to achieve? Looks like the logic needs to be changed.

Related