【发布时间】:2019-06-04 14:00:44
【问题描述】:
给定以下示例数组:
import numpy as np
example = np.array(
[[[ 0, 0, 0, 255],
[ 0, 0, 0, 255]],
[[ 0, 0, 0, 255],
[ 221, 222, 13, 255]],
[[-166, -205, -204, 255],
[-257, -257, -257, 255]]]
)
我想用 [255, 0, 0, 255] 替换值 [0, 0, 0, 255] 值,其他所有值都变为 [0, 0, 0, 0]。
所以想要的输出是:
[[[ 255, 0, 0, 255],
[ 255, 0, 0, 255]],
[[ 255, 0, 0, 255],
[ 0, 0, 0, 0]],
[[ 0, 0, 0, 0],
[ 0, 0, 0, 0]]
这个解决方案接近了:
np.place(example, example==[0, 0, 0, 255], [255, 0, 0, 255])
np.place(example, example!=[255, 0, 0, 255], [0, 0, 0, 0])
但它会输出这个:
[[[255 0 0 255],
[255 0 0 255]],
[[255 0 0 255],
[ 0 0 0 255]], # <- extra 255 here
[[ 0 0 0 0],
[ 0 0 0 0]]]
有什么好的方法可以做到这一点?
【问题讨论】:
标签: python numpy numpy-ndarray