如何使用colorsys.rgb_到\u hls在python中?

2024-05-16 21:57:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一个rgb样式的图像数据像素,大小为1000px*1000px。 它的数据结构是numpy的数组,1000*1000*3,rgb在[0,1]中,是float。 如果您需要使用

image = Image.fromarray(numpy.uint8(pixels*255))

我已经知道使用colorsys.rgb_到\u hls(r,g,b)可以将一个像素转换为hls,但在这种情况下,我想知道是否有其他方法可以在一个句子中转换整个像素:

^{pr2}$

我使用这个失败是因为:rgb_-to-hls需要3个单独的参数,而我一次只代表r/g/b。在

编辑2014年05月28日上午10:34

我的错是,双循环是可行的,但它的时间成本在python中是无法承受的,因为python的循环太慢了。在

编辑2014 05 28上午10:57

rows, cols = pixels.shape[0], pixels.shape[1]

# transpose to 3 * pixels_number
# utilized for extract R/G/B cols

t_p = pixels.swapaxes(0, 2).swapaxes(1, 2)
R, G, B = t_p[0], t_p[1], t_p[2]

dRG, dRB, dGB = R - G, R - B, G - B
temp = 2*numpy.sqrt(dRG**2+dRB*dGB)
mskTemp = (temp == 0.0)
temp[mskTemp] = 1.0
# Hue
cos = (dRG+dRB)/(temp)
H = numpy.arccos(cos) # 0.08
# check for gray_scale
H[mskTemp] = 0.0
# check for nan value
H[numpy.isnan(H)] = 0.0
# Intensity = r+g+b / 3
I = pixels.mean(axis = 2)
# prepare for Saturation calc
Imin = pixels.min(axis = 2)
I[I == 0.0] = 0.01
S = 1 - Imin / I

它需要0.289秒


Tags: tonumpy编辑forrgb像素tempcols
1条回答
网友
1楼 · 发布于 2024-05-16 21:57:04

如果要将colorsys.rgb_to_hls应用于每个像素,为什么不在数组上循环呢?在

pixels_hls = np.zeros_like(pixels)

for i in range(1000):
    for j in range(1000):
        pixels_hls[i,j,:] = np.array(colorsys.rgb_to_hls(*pixels[i,j,:]))

相关问题 更多 >