RGB Int到RGB - Python

Oma*_*mar 17 python rgb integer

如何将RGB整数转换为相应的RGB元组(R,G,B)?看起来很简单,但我在谷歌上找不到任何东西.

我知道,每RGB (r,g,b)你有整n = r256^2 + g256 + b,我怎么能解决在Python相反,IE给出的n,我需要的r,g,b值.

Nil*_*nck 43

我不是一个Python专家,但据我所知它有与C相同的运算符.

如果是这样,这应该工作,它也应该比使用modulo和division快得多.

Blue =  RGBint & 255
Green = (RGBint >> 8) & 255
Red =   (RGBint >> 16) & 255
Run Code Online (Sandbox Code Playgroud)

在每种情况下屏蔽掉最低字节是什么(二进制和255 ...等于8位).对于绿色和红色分量,它会做同样的事情,但首先将颜色通道转换为最低字节.


Xor*_*lev 14

从RGB整数:

Blue =  RGBint mod 256
Green = RGBint / 256 mod 256
Red =   RGBint / 256 / 256 mod 256
Run Code Online (Sandbox Code Playgroud)

一旦你知道如何获得它,这可以非常简单地实现.:)

Upd:添加了python函数.不确定是否有更好的方法,但这适用于Python 3和2.4

def rgb_int2tuple(rgbint):
    return (rgbint // 256 // 256 % 256, rgbint // 256 % 256, rgbint % 256)
Run Code Online (Sandbox Code Playgroud)

还有一个很好的解决方案,使用比特移位和屏蔽,这无疑比Nils Pipenbrinck发布的要快得多.

  • 不要忘记使用整数除法而不是浮点除法. (2认同)

ada*_*amk 9

>>> import struct
>>> str='aabbcc'
>>> struct.unpack('BBB',str.decode('hex'))
(170, 187, 204)

for python3:
>>> struct.unpack('BBB', bytes.fromhex(str))
Run Code Online (Sandbox Code Playgroud)

>>> rgb = (50,100,150)
>>> struct.pack('BBB',*rgb).encode('hex')
'326496'

for python3:
>>> bytes.hex(struct.pack('BBB',*rgb))
Run Code Online (Sandbox Code Playgroud)


dbr*_*dbr 7

>>> r, g, b = (111, 121, 131)
>>> packed = int('%02x%02x%02x' % (r, g, b), 16)
Run Code Online (Sandbox Code Playgroud)

这会产生以下整数:

>>> packed
7305603
Run Code Online (Sandbox Code Playgroud)

然后你可以用很明确的方式解压缩它:

>>> packed % 256
255
>>> (packed / 256) % 256
131
>>> (packed / 256 / 256) % 256
121
>>> (packed / 256 / 256 / 256) % 256
111
Run Code Online (Sandbox Code Playgroud)

..或者更紧凑的方式:

>>> b, g, r = [(packed >> (8*i)) & 255 for i in range(3)]
>>> r, g, b
Run Code Online (Sandbox Code Playgroud)

样本适用于任意数量的数字,例如RGBA颜色:

>>> packed = int('%02x%02x%02x%02x' % (111, 121, 131, 141), 16)
>>> [(packed >> (8*i)) & 255 for i in range(4)]
[141, 131, 121, 111]
Run Code Online (Sandbox Code Playgroud)


And*_*Dog 6

我假设你有一个包含RGB值的32位整数(例如ARGB).然后,您可以使用struct模块解压缩二进制数据:

# Create an example value (this represents your 32-bit input integer in this example).
# The following line results in exampleRgbValue = binary 0x00FF77F0 (big endian)
exampleRgbValue = struct.pack(">I", 0x00FF77F0)

# Unpack the value (result is: a = 0, r = 255, g = 119, b = 240)
a, r, g, b = struct.unpack("BBBB", exampleRgbValue)
Run Code Online (Sandbox Code Playgroud)