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循環正確替換像素?