【问题标题】:Vectorize scalar function calls using Numpy使用 Numpy 向量化标量函数调用
【发布时间】:2015-03-07 16:51:18
【问题描述】:

我想使用 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 会这样做,但它只是对你隐藏循环,它不会更快。

标签: python numpy color-mapping


【解决方案1】:

您可以使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多