python - 使用 Numpy 向量化标量函数调用

标签 python numpy color-mapping

我想使用 colorsys 模块在 RGB 和 HSL 之间进行转换。 然而,colorsys API 是基于标量的。 我想知道如何在没有 for 循环的情况下对其进行矢量化,以便我可以做类似的事情

hsl = np.vstack([np.ones((1, 256)), np.ones((1, 256,)), np.ones((1, 256,))]).transpose()
rgb = colorsys.hls_to_rgb(hsl[0, :], hsl[1, :], hsl[2, :])

最佳答案

您可以使用np.vectorize,但正如 lolopop 指出的那样,这只是添加了语法糖;它不会使隐式循环更快:

import colorsys
import numpy as np
rgb_to_hls = np.vectorize(colorsys.rgb_to_hls)
hls_to_rgb = np.vectorize(colorsys.hls_to_rgb)

arr = np.random.random((2, 2, 3)) * 255
r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2]
h, l, s = rgb_to_hls(r, g, b)
r2, g2, b2 = hls_to_rgb(h, l, s)
arr2 = np.dstack([r2, g2, b2])
assert np.allclose(arr, arr2)

关于python - 使用 Numpy 向量化标量函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28917362/

相关文章:

Python:While 循环,在不同条件下执行相同的代码。优雅与架空

python - 无法切换到帧——不断出现 AttributeError

Python - 从元组列表生成字典(树)

matlab - 如何在 MATLAB 中将 3 列矩阵绘制为彩色图?

python - 在 Mayavi 中以 0 为中心的颜色图

python - Pygame 侧滚轴街机

python - 在 channel 上重复一个数组

python - NumPy:使用自身修改数组时出现错误结果

Gnuplot 极坐标直方图

python - 如何将 4d RGB 图像数据转换为 LogisticRegression 的 2d 数组