[英]Replacing a value from one array with a value of the same index of another array?
I have two 3D numpy.array
objects which represent two images.我有两个代表两个图像的 3D numpy.array
对象。 I have a code that replaces every black pixel in an image to white, but instead of that, I want to replace each pixel that is not black in the first image to the "parallel" pixel color in the other image.我有一个代码可以将图像中的每个黑色像素替换为白色,但我想将第一个图像中不是黑色的每个像素替换为另一个图像中的“平行”像素颜色。 How can I do this by changing my code?如何通过更改我的代码来做到这一点? Thanks!谢谢!
r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with
red, green, blue = image[:, :, 0], image[:, :, 1], image[:, :, 2]
mask = (red == r1) & (green == g1) & (blue == b1)
image[:, :, :3][mask] = [r2, g2, b2]
You can use numpy.sum
to test whether the pixel is black since the rgb
sum will be zero for that pixel if and only if the pixel is black.您可以使用numpy.sum
来测试像素是否为黑色,因为当且仅当像素为黑色时,该像素的rgb
和才会为零。 The test on that summation provides a mask that can be used to update your image.该求和的测试提供了一个可用于更新图像的掩码。
import numpy as np
# Assume image1 and image2 exist in memory as 3-dimensional numpy.arrays
# with shapes (M,N,k) where k is the channel depth (r,g,b -> k=3)
mask = np.sum(image1,axis=-1) > 0
image1[mask] = image2[mask]
You can create a mask to selectively operate on items within your array.您可以创建一个掩码来有选择地对数组中的项目进行操作。 It is easier to visualize with 2d arrays, so for example sake:使用二维数组更容易可视化,例如:
import numpy as np
a = np.random.randint(0, 10, (5, 4))
b = np.random.randint(0, 10, (5, 4))
Let's see what a and b look like.让我们看看 a 和 b 是什么样的。
In [317]: a
Out[317]:
array([[6, 0, 4, 0],
[1, 9, 1, 6],
[7, 2, 5, 0],
[8, 3, 5, 0],
[1, 8, 1, 6]])
In [318]: b
Out[318]:
array([[1, 3, 2, 1],
[9, 1, 9, 4],
[9, 4, 5, 5],
[6, 0, 6, 4],
[5, 1, 1, 2]])
Suppose we want to select locations where a==0 and b==3, we build an index (mask).假设我们要选择 a==0 和 b==3 的位置,我们建立一个索引(掩码)。 idx = (a==0) & (b==3) idx = (a==0) & (b==3)
How does idx look? idx 看起来如何?
In [320]: idx
Out[320]:
array([[False, True, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
Now, if you want to operate on array a where a==0 and b==3 (suppose we want to make the a value equal the b value:现在,如果您想对 a==0 和 b==3 的数组 a 进行操作(假设我们想让 a 值等于 b 值:
a[idx] = b[idx]
Now what does a look like?现在看起来像什么?
In [322]: a
Out[322]:
array([[6, 3, 4, 0],
[1, 9, 1, 6],
[7, 2, 5, 0],
[8, 3, 5, 0],
[1, 8, 1, 6]])
With this knowledge in hand, you can apply the same method to 3d arrays (though harder to visualize).掌握这些知识后,您可以将相同的方法应用于 3d 数组(尽管更难可视化)。
# identify pixels that are NOT black (i.e. not equal to 0 0 0)
idx = (image1[:, :, 0] == 0) & (image1[:, :, 1] == 0) & (image1[:, :, 2] == 0)
image1[~idx] = image2[~idx]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.