【问题标题】:Nested for loop to replace cells in an array嵌套 for 循环以替换数组中的单元格
【发布时间】:2017-08-30 22:22:28
【问题描述】:

我有一个蒙版图像,我正在尝试用另一个数组中的值替换该图像中的蒙版像素。我正在使用嵌套的 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 循环不能正确替换像素?

【问题讨论】:

    标签: python arrays for-loop


    【解决方案1】:

    初始版本的问题是 img_masked[x, y] 肯定永远不会是 [],因为那是空列表 - img_masked 的元素是 numpy 浮点数,而不是列表。

    如果把check改成if img_masked[x, y] != np.nan,就会遇到np.nan不等于自己的问题:

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

    这两种技术的问题是第一个if 总是True,所以你总是使用旧的img 来填充new_img。我强烈建议在寻找这样的错误时在每个分支中添加一些 prints - 这将清楚地表明分支无法正常工作。

    要获得一致的结果,请使用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]
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 2019-06-06
      • 2021-08-09
      • 2020-06-03
      • 2010-10-03
      • 2018-05-21
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多