2017-08-30 38 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]