python - 为什么我的 python 循环出现索引错误?

标签 python numpy for-loop feature-extraction

我正在尝试将原始图像划分为 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 的大小为 heightimage0Rxwidthimage0R (我将其称为 hxw 暂时),我假设它与 image0R 大小相同(否则你会有更多问题)。

您的代码所做的是从 image0R 中取出一个 8x8 的正方形并将其展平到新数组中。

出现问题的原因是 new0 是一个 hxw 矩阵,但您将其用作 h* wx64-矩阵。这是因为行的值 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/

相关文章:

python - 切片索引必须是整数,它已经是整数了。如何超越这个?

python - 在 Numpy Python 中向量化此函数

javascript - 打印出数组中随机生成的数字后,在 2 个偶数之间添加破折号

powershell - 在Powershell中执行For循环以执行x次不同的服务器重启

python - For 循环在带有 csv 文件的 python 中不起作用

python - 在 Python 正则表达式中使用列表中的值作为变量

python - 在Python中,如何在不更改命名空间的情况下以宏样式将一个文件包含(而不是导入)另一个文件中?

python - Numpy:根据前一个元素计算?

html - Thymeleaf:在 data-slide-to 属性中使用索引时,动态轮播不会链接到相关 slider ?

python - 如何用Python构建这个图?