创建一个在所有 channel 上具有恒定标量的彩色图像很容易:
height, width = 3, 4
shape = (height, width)
num_channels = 3
scalar_value = 0.5
image = np.full((*shape, num_channels), scalar_value)
有没有简单的方法来创建具有恒定颜色向量的图像?
vector_value = (0.3, 0.4, 0.5) # e.g. (red, green, blue)
image = create_new(shape, vector_value)
这可以使用自定义函数来完成:
def create_new(shape, vector_value):
image = np.empty((*shape, len(vector_value)))
image[...] = vector_value
return image
但我想知道这是否可以使用简单的 numpy
表达式来完成。
最佳答案
np.full
的文档有点误导(读错了)。它接受任何可广播值作为 fill_value
,而不仅仅是标量。这意味着你可以做
np.full((*shape, len(vector_value)), vector_value)
我用 numpy 版本 1.17.3 对此进行了测试,但我不确定它何时发生了变化。我的猜测是,如果你回溯得足够远,文档是正确的,fill_value
只能是一个标量。
当前有一个更新文档的问题:https://github.com/numpy/numpy/issues/14837 .
关于python - 创建一个具有恒定颜色的 numpy 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58942356/