[英]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.我正在尝试将原始图像划分为 8x8 重叠块,以便稍后进行特征提取。
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.我在 for 循环中尝试
widthimage0R-1
,但它仍然不起作用。
new0
is of size heightimage0R
x widthimage0R
(which I'll refer to as h
x w
for now), which I assume is the same size of image0R
(otherwise you have more problems). new0
的大小是heightimage0R
x widthimage0R
(我现在将其称为h
x w
),我假设它的大小与image0R
相同(否则你会遇到更多问题)。
What your code is doing is taking a 8x8 square from image0R
and flattening it into the new array.您的代码正在做的是从
image0R
中取出一个 8x8 正方形并将其展平到新数组中。
The problem arises because new0
is a h
x w
-matrix, but you're using it as a h*w
x 64
-matrix.出现问题是因为
new0
是一个h
x w
-矩阵,但您将它用作h*w
x 64
-矩阵。 This is because the row has value k
, which goes between 0 to h*w
, and the column is always 64.这是因为行的值
k
介于 0 到h*w
之间,并且列始终为 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
.这里,
new0
的形状是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
).在这里,我们尝试访问
new0
的第 k 行,其中 k 上升到 ( heightimage0R
x widthimage0R
)。 So after k crosses heightimage0R
, it must be throwing error.所以在 k 越过
heightimage0R
之后,它一定是抛出错误。
Can you be more specific of what you want to achieve?你能更具体地说明你想要实现的目标吗? Looks like the logic needs to be changed.
看起来逻辑需要改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.