python - 创建一个具有恒定颜色的 numpy 图像

标签 python numpy

创建一个在所有 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/

相关文章:

php - 如何从网页调用python脚本

python - Cygwin:导入 numpy 错误

python - 从 Python 中的字符串中提取字段和值

python - f2py:输入不是 Fortran 连续的

python - 为什么我的数据没有被屏蔽?

python - 数组中每个值相对于其他值的最小距离

python - 什么是 Python/pandas 相当于这个用于重新排列数据帧列的 R 代码?

python - gunicorn 导入错误 : No module named flask

python - 我如何从 __init__ 调用属性 setter

python - 将数字加倍