Python numpy:将图像遮罩与RGB组合以获得彩色图像遮罩

Python numpy:将图像遮罩与RGB组合以获得彩色图像遮罩,python,numpy,image-processing,Python,Numpy,Image Processing,如何将二进制掩码图像数组(this\u mask-shape:4,4)与预定义的颜色数组(mask\u color,shape:3)组合起来 要获取新的彩色遮罩图像阵列(此遮罩已上色,形状:4,4,3) 我试过逐像素循环,当图像为225x225时,速度慢吗?最好的方法是什么 对于每个图像,我有多层遮罩,每个遮罩层需要有不同的预定义颜色 这可能有效: this_mask = np.array([ [0,1,0,0], [0,0,0,0], [

如何将二进制掩码图像数组(
this\u mask
-shape:4,4)与预定义的颜色数组(
mask\u color
,shape:3)组合起来

要获取新的彩色遮罩图像阵列(
此遮罩已上色
,形状:4,4,3)

我试过逐像素循环,当图像为225x225时,速度慢吗?最好的方法是什么

对于每个图像,我有多层遮罩,每个遮罩层需要有不同的预定义颜色

这可能有效:

    this_mask = np.array([
        [0,1,0,0],
        [0,0,0,0],
        [0,0,0,0],
        [0,0,0,0],
    ])
    mask_color = np.array([128, 128, 64])

    res = []
    for row in new:
        tmp = []
        for col in row:
            tmp.append(np.array([1,1,1]) * col)
        res.append(np.array(tmp))

    res = res * mask_color
对于每个条目,1将转换为[1,1,1],0是[0,0,0]

我这样做是因为我想利用运算*(元素乘法)的优点

这项工作:

    test = np.array([[0, 0, 0],
                     [1, 1, 1],
                     [0, 0, 0],
                     [0, 0, 0]])

    test * np.array([128, 128, 64])
我们会找到的

    array([[  0,   0,   0],
           [128, 128,  64],
           [  0,   0,   0],
           [  0,   0,   0]])
我们想把所有的计算都放在numpy一边。所以我们循环遍历数组只是为了转换,其余的是为了numpy


对于一种遮罩颜色的255x255/1,需要0.2秒;对于1000x1000,需要2秒。下面的函数应该满足您的要求


def apply_mask_color(mask, mask_color):
    return np.concatenate(([mask[ ... , np.newaxis] * color for color in mask_color]), axis=2)

给定以下代码:


此_掩码=np.array([
[0,1,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
])
mask_color=np.array([128,128,64])
应用=应用遮罩颜色(此遮罩,遮罩颜色)
打印(应用.形状)#(4,4,3)
需要注意的是,输出并不是您所期望的。相反,里面的每个元素现在都是一个三维数组,包含了用mask_color表示的rgb值


打印(应用)
输出:


[[[  0   0   0]
  [128 128  64]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]]


我想这才是你想要的。

谢谢!这很有效。我验证了:导入MatpTllb.PyPlice作为PLT PLT。IsSee(Apple)PLT。()@ CHILLS,如果这是可行的,请考虑点击正确的答案,点击点击计数(勾选)旁边的投票计数。通过这种方式,作者获得了声誉分数,其他用户寻找的答案知道它是正确的和有效的,而其他考虑回答的人知道他们不需要担心。非常感谢。

def apply_mask_color(mask, mask_color):
    return np.concatenate(([mask[ ... , np.newaxis] * color for color in mask_color]), axis=2)


[[[  0   0   0]
  [128 128  64]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]]