我正在尝试将原始图像划分为 8x8 重叠的 block ,以便稍后进行特征提取。
这是我的代码:
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
但是,当我运行代码时,我会收到以下错误:
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
我已经在 for 循环中尝试了 widthimage0R-1
但它仍然不起作用。
最佳答案
new0
的大小为 heightimage0R
xwidthimage0R
(我将其称为 h
xw
暂时),我假设它与 image0R
大小相同(否则你会有更多问题)。
您的代码所做的是从 image0R
中取出一个 8x8 的正方形并将其展平到新数组中。
出现问题的原因是 new0
是一个 h
xw
矩阵,但您将其用作 h* w
x64
-矩阵。这是因为行的值 k
介于 0 到 h*w
之间,而列始终为 64。
我的猜测是您打算执行以下操作:
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
关于python - 为什么我的 python 循环出现索引错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66271360/