2017-08-30 64 views
1

我有一個蒙版圖像,我試圖用另一個數組中的值替換該圖像中的蒙版像素。我使用一個嵌套的for循環:嵌套循環替換數組中的單元格

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(height): 
    for x in range(width): 
     if img_masked[x, y] != []: 
      new_img[x, y] = img[x, y] 
     else: 
      new_img[x, y] = img_masked_median[x, y] 

# Plot results in 4x4 grid 
fig, ax = plt.subplots(nrows=2, ncols=2) 
ax[0,0].imshow(img) 
ax[0,0].set_title('img') 
ax[0,1].imshow(img_masked_median) 
ax[0,1].set_title('img_masked_median') 
ax[1,0].imshow(img_masked) 
ax[1,0].set_title('img_masked') 
ax[1,1].imshow(new_img) 
ax[1,1].set_title('new_img') 
plt.show() 

過濾器工作正常,現在我只想更換任何屏蔽的像素與來自img_masked_median對應像素的img。 目前,循環只生成img_masked_median的副本。如果我改變條件線24是

if img_masked[x, y] != np.nan: 

現在它產生IMG的副本。
爲什麼不是for循環正確替換像素?

回答

0

初始版本的問題在於img_masked[x, y]肯定不會是[],因爲這是空列表 - img_masked的元素是numpy浮點數,而不是列表。

如果更改支票if img_masked[x, y] != np.nan,你碰到的問題np.nan不等於本身:

>>> np.nan == np.nan 
False 

與這兩種技術的問題是,第一if總是True,讓你隨時使用舊的img填充new_img。我強烈建議在尋找這樣的錯誤時在每個分支中放置一些print,這會明確指出該分支無法正常工作。

爲了得到一致的結果,使用np.isnan

# Use a for loop to look at each pixel in the masked, unfiltered image 
height, width = img_masked.shape 
for y in range(height): 
    for x in range(width): 
     if np.isnan(img_masked[x, y]): 
      new_img[x, y] = img[x, y] 
     else: 
      new_img[x, y] = img_masked_median[x, y]