将整数转换为RGB值,然后使用Python返回 [英] convert Integers to RGB values and back with Python

查看:146
本文介绍了将整数转换为RGB值,然后使用Python返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,一个函数从给定的Integer返回RGB值,另一个函数进行相反的操作,为它提供RGB值,它返回一个Integer。我通过查看是否将转换为RGB的整数从RGB转换回原始整数值来对此进行测试,但是我得到了不同的值。

I have two functions, one to return RGB values from a given Integer, and the other function does the reverse, providing it with RGB values it returns an Integer. I'm testing this by seeing if the integer i convert to RGB turns back from RGB into the original integer value, but I'm getting different values.

def getRGBfromI(RGBint):
    blue =  RGBint & 255
    green = (RGBint >> 8) & 255
    red =   (RGBint >> 16) & 255
    return red, green, blue

def getIfromRGB(rgb):
    red = rgb[0]
    green = rgb[1]
    blue = rgb[2]
    print red, green, blue
    RGBint = (red<<16) + (green<<8) + blue
    return RGBint

测试:

i1 = 2147483647
colr1 = getRGBfromI(i1)
print colr1 # returns (255,255,255)

i2 =getIfromRGB(colr1)

print i1, i2 # returns 2147483647 16777215

在我看来,getRGBfromI()是正确的,而getIfromRGB()是是错误的,但我对此也可能是错误的。

To me it seems like the getRGBfromI() is correct and the getIfromRGB() is incorrect, but I may be wrong about that too.

推荐答案

两个函数似乎都可以正常工作。

Both functions seem to be working fine.

最大由24位整数表示的值(立即忘记符号)是

The max value expressed by a 24 bit integer (forget the sign for now) is

mx = pow(2,24)-1 # i.e. 16777215

所以

i1 = 2147483647

高于 mx

colr1 = getRGBfromI(i1)

正确给出

(255, 255, 255)  # better to view it in hex as 0xFFFFFF

因为它切掉了高于24的位(0xFFFFFF占用了0到23)

since it cuts out the bits higher than 24 (0xFFFFFF occupies bits from 0 to 23)

Viceversa,

Viceversa,

i2 = getIfromRGB(colr1)

正确给出

16777215

这是您可以用24位表示的最大值(即 mx )。

which is the max value you can represent with 24 bits (i.e. the mx above).

如果您倒了在1升的瓶子中装满1.4升水,溢流中会损失一些水。
清空瓶子时,您会发现最大容量为1L

If you pour 1.4 litres of water in a 1L bottle, some water will be lost in the overflow. When you empty the bottle, you will find 1L at max

这篇关于将整数转换为RGB值,然后使用Python返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆