[英]How to use Numpy to replace values in a matrix with a color e.g.[0,255,0]
I have a matrix which only contains 0 or 1. I also have a list of colors eg the below我有一个只包含 0 或 1 的矩阵。我还有一个 colors 的列表,例如下面
class_colors = [[0,0,0], [0,255,0]]
m = np.random.random_integers(0,1,(5,5))
eg the m
looks like:例如
m
看起来像:
0,1,0,1
0,1,0,1
0,1,0,1
How can I replace the 1-values in m
with the class_colors[1]
and 0-values in m
with class_colors[0]
, so the m
will look something like:我如何用
class_colors[1]
替换m
中的 1 值,用class_colors[0]
替换m
中的 0 值,这样m
看起来像:
[0,0,0], [0,255,0],[0,0,0], [0,255,0]
[0,0,0], [0,255,0],[0,0,0], [0,255,0]
[0,0,0], [0,255,0],[0,0,0], [0,255,0]
I used to be able to do so with np.argmax()
and np.take()
but it requires the m
looks like [class_num,w,h]
and then I can do argmax with axis=0
.我曾经能够使用
np.argmax()
和np.take()
这样做,但它需要m
看起来像[class_num,w,h]
然后我可以用axis=0
做 argmax 。
I know I could do it with for loop, but is there any better and faster approach to do this?我知道我可以用 for 循环来完成,但是有没有更好更快的方法来做到这一点?
Not surprisingly the intuitive way works (using advanced indexing):毫不奇怪,直观的方式有效(使用高级索引):
class_colors = np.array([[0,0,0], [0,255,0]])
m = np.array([0,1,0,1,0,1,0,1,0,1,0,1]).reshape((3,4))
class_colors[m]
Is it what you expect:是不是如你所愿:
>>> c[m]
array([[[ 0, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0],
[ 0, 255, 0]],
[[ 0, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0],
[ 0, 255, 0]]])
>>> c # c = np.array(class_colors)
array([[ 0, 0, 0],
[ 0, 255, 0]])
>>> m # m = np.random.randint(0, 2, (2, 4))
array([[0, 1, 0, 1],
[0, 1, 0, 1]])
By extension:通过扩展:
class_colors = [[0,0,0], [0,255,0], [255,0,0], [0,0,255]]
c = np.array(class_colors)
m = np.random.randint(0, 4, (2, 4))
# m <- array([[2, 1, 1, 3], [2, 3, 1, 0]])
>>> c[m]
array([[[255, 0, 0],
[ 0, 255, 0],
[ 0, 255, 0],
[ 0, 0, 255]],
[[255, 0, 0],
[ 0, 0, 255],
[ 0, 255, 0],
[ 0, 0, 0]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.