【发布时间】: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 循环不能正确替换像素?
【问题讨论】: