2017-08-31 21 views
0

我正在使用for循環遍歷數組,並且像我一樣替換像素。到目前爲止,代碼只是產生我想要的結果,但只有在數組是正方形的時候。最終,我需要在矩形陣列上做同樣的事情。如果我將line 7中的尺寸更改爲例如h, w = 10, 12,則會出現IndexError: index 10 is out of bounds for axis 0 with size 10錯誤。IndexError:索引10超出了軸1,矩形陣列的大小爲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時纔會發生?

+0

哪一行出現錯誤?我的猜測是'img_masked_median'的尺寸與'img_masked'不一樣。 – Barmar

+0

我在'25行'中。我使用Spyder,它告訴我'img_masked'和'im_masked_median'確實是合適的尺寸(如果按照第一段更改尺寸,則爲10 x 12)。 – Jim421616

+0

不要讓我數線,哪條線出錯? – Barmar

回答

1

你有你的數組索引倒退。二維數組索引爲[row, column]。由於y在行號上循環,所有數組索引應該是[y, x],而不是[x, y]

相關問題