[英]Mapping values in a numpy array
How do I go from a 2D numpy array where I only have three distinct values: -1, 0, and 1 and map them to the colors red
(255,0,0), green
(0,255,0), and blue
(255,0,0)? 如何从2D numpy数组出发,在该数组中我只有三个不同的值:-1、0和1,并将它们映射为
red
(255,0,0), green
(0,255,0)和blue
(255 ,0,0)? The array is quite large, but to give you an idea of what I am looking for, imagine I have the input 数组很大,但是为了让您大致了解我要寻找的内容,请想象我有输入
array([[ 1, 0, -1],
[-1, 1, 1],
[ 0, 0, 1]])
I want the output: 我想要输出:
array([[(0, 0, 255), (0, 255, 0), (255, 0, 0)],
[(255, 0, 0), (0, 0, 255), (0, 0, 255)],
[(0, 255, 0), (0, 255, 0), (0, 0, 255)]])
I could for-loop and have conditions but I was wondering if there is a one or two liner using a lambda function that could accomplish this? 我可以循环并有条件,但是我想知道是否有使用lambda函数的一两个衬垫可以完成此任务? Thanks!
谢谢!
You might want to consider a structured array, as it allows tuples without the datatype being object
. 您可能要考虑结构化数组,因为它允许元组而数据类型不是
object
。
import numpy as np
replacements = {-1: (255, 0, 0), 0: (0, 255, 0), 1: (0, 0, 255)}
arr = np.array([[ 1, 0, -1],
[-1, 1, 1],
[ 0, 0, 1]])
new = np.zeros(arr.shape, dtype=np.dtype([('r', np.int32), ('g', np.int32), ('b', np.int32)]))
for n, tup in replacements.items():
new[arr == n] = tup
print(new)
Output: 输出:
[[( 0, 0, 255) ( 0, 255, 0) (255, 0, 0)]
[(255, 0, 0) ( 0, 0, 255) ( 0, 0, 255)]
[( 0, 255, 0) ( 0, 255, 0) ( 0, 0, 255)]]
Another option is using an 3D array, where the last dimension is 3
. 另一个选择是使用3D数组,最后一个维度是
3
。 The first "layer" would be red, the second "layer" would be green, and the third "layer" blue. 第一个“层”为红色,第二个“层”为绿色,第三个“层”为蓝色。 This option is compatible with
plt.imshow()
. 该选项与
plt.imshow()
兼容。
import numpy as np
arr = np.array([[ 1, 0, -1],
[-1, 1, 1],
[ 0, 0, 1]])
new = np.zeros((*arr.shape, 3))
for i in range(-1, 2):
new[i + 1, arr == i] = 255
Output: 输出:
array([[[ 0., 0., 255.],
[255., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 255., 0.],
[ 0., 0., 0.],
[255., 255., 0.]],
[[255., 0., 0.],
[ 0., 255., 255.],
[ 0., 0., 255.]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.