获取RGB颜色

Obtaining RGB colors

所以我在寻找如何根据要检索的所需颜色总数获取 RGB 颜色列表,然后我找到了这段代码。还有一部分我不明白,我已经阅读了“>>”和“&”运算符是按位运算符的注释,但我无法完全理解它们在做什么。

谁能帮我理解颜色值的部分 已分配?

def getDinstinctRGBColorsList(desiredColors)
    availableColors = 16000000
    inc = availableColors/desiredColors
    colorsList = {}
    RGB = 0
    count = 0
    while count <= desiredColors:
        RGB = RGB+inc
        colorBlue = RGB & 255
        colorGreen = (RGB >> 8) & 255
        colorRed = (RGB >> 16) & 255
        colorsList[count] = str(colorRed) + "," + str(colorGreen) + "," + str(colorBlue)
        count += 1
    return colorsList

BitwiseOperators and What are bitwise shift (bit-shift) operators and how do they work?

从您发布的代码看来,RGB 包含 24 位颜色信息:红色 8 位,绿色 8 位,蓝色 8 位,红色数据在最左边 8位,中间8位绿色数据,最右边8位蓝色数据。

假设 RGB 的位看起来像 0brrrrrrrrggggggggbbbbbbbb,其中 r 代表红色值,g 代表绿色值,并且 b有点为蓝值。

注意 255 在二进制中是 0b11111111(8 个设置位)。

colorGreen = (RGB >> 8) & 255 使用 >>(右移)和 &(按位与)提取表示绿色的中间 8 位:

0brrrrrrrrggggggggbbbbbbbb >> 8 产生 0b00000000rrrrrrrrgggggggg

请注意绿色位现在是最左边的 8 位。但是,红色的位仍然存在。

0b00000000rrrrrrrrgggggggg & 0b00000000000000001111111 产生 0b0000000000000000gggggggg

注意只剩下绿色的位。

编辑:这是一种简化。在Python中,>>是算术移位,不是逻辑移位。算术移位保留符号。有关更详细的说明,请参阅 What are bitwise shift (bit-shift) operators and how do they work?