如何将二进制蒙版图像数组(this_mask
-形状:4,4)与预定义的颜色数组(mask_color
,形状:3)组合
this_mask = np.array([
[0,1,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
])
this_mask.shape # (4,4)
mask_color = np.array([128, 128, 64])
mask_color.shape # (3)
要获取新的彩色蒙版图像阵列(this_mask_colored
,形状:4、4、3)?
this_mask_colored = # do something with `this_mask` and `mask_color`
# [
# [
# [0,128,0],
# [0,0,0],
# [0,0,0],
# [0,0,0]
# ],
# [
# [0,128,0],
# [0,0,0],
# [0,0,0],
# [0,0,0]
# ],
# [
# [0,64,0],
# [0,0,0],
# [0,0,0],
# [0,0,0]
# ],
# ]
this_mask_colored.shape # (4,4,3)
我尝试逐像素循环,当图像为225x225时,速度是否较慢,什么是最好的方法?
对于每个图像,我都有多个蒙版层,每个蒙版层需要具有不同的预定义颜色。
答案 0 :(得分:1)
这可能有效:
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(带有一个mask_color),这需要0.2秒;对于1000x1000的像素,则需要2秒
答案 1 :(得分:0)
以下功能应该可以满足您的要求。
def apply_mask_color(mask, mask_color):
return np.concatenate(([mask[ ... , np.newaxis] * color for color in mask_color]), axis=2)
给出以下代码:
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])
applied = apply_mask_color(this_mask, mask_color)
print(applied.shape) #(4, 4, 3)
请务必注意,输出结果与您的预期不符。而是,其中的每个元素现在都是一个3维数组,其中包含mask_color
中详细说明的R G B值。
print(applied)
输出:
[[[ 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]]]
我认为这是您正在寻找的更多东西。