IndexError:对于矩形数组,索引10超出了大小为10的轴1的界限,但不是正方形



我使用for循环在数组上迭代,并在执行过程中替换像素。到目前为止,代码产生的结果正是我想要的,但前提是数组是正方形的。最终,我需要在矩形阵列上做同样的事情。如果我将line 7中的尺寸更改为,例如h, w = 10, 12,则会得到IndexError: index 10 is out of bounds for axis 0 with size 10错误。

import scipy.ndimage as ndi
import matplotlib.pyplot as plt
import numpy as np  
#   Generate random image and mask
np.random.seed(seed=5)                      #   To use the same random numbers
h, w = 10,10
mask = np.random.randint(2, size=(h, w))    #   Generate a h x w array of 
#   random integers from 0 - 1
img = np.random.rand(h, w)                  #   Generate a h x w array of 
#   random floats
img_masked = np.where(mask, img, np.nan)    #   Mask the img array and replace
#   invalid values with nan's
#   Use generic filter to compute nan-excluding median of masked image
size = 3
img_masked_median = ndi.generic_filter(img_masked, np.nanmedian, size=size)
new_img = np.ones_like(img_masked)
#   Use a for loop to look at each pixel in the masked, unfiltered image
height, width = img_masked.shape
for y in range(0, height):
for x in range(0, width):
if np.isnan(img_masked[x, y]):
new_img[x, y] = img_masked_median[x, y]
else:
new_img[x, y] = img[x, y]

我知道这与数组长度上的循环有关,我也读过其他有同样错误的问题,但我找不到方形数组与矩形数组的解决方案。

我还试着把循环改成

for y in range(0, height + 1):
for x in range(0, width + 1):

但我也犯了同样的错误。尝试

for y in range(0, height - 1):
for x in range(0, width - 1):

给出了错误的结果
如何修复此问题,使其在数组的范围内
还有,为什么只有当w==h时才会发生这种情况?

您的数组索引是向后的。2维数组被索引为CCD_ 5。由于y在行号上循环,所以所有数组索引都应该是[y, x],而不是[x, y]

最新更新