将 RGB 转换为类/单个整数值

-1 python arrays numpy image conv-neural-network

我有一个来自 RGB 图像 (64,64,3) 的 numpy 数组,我需要将每个现有的 RGB 组合转换为一个类,由整数值表示。所以最后我有一个包含整数值(0-N)的数组(64,64)。这些值代表图片中特定的 RGB 组合。当然,每种 RGB 组合只获得一个值。简而言之:每种颜色都是一个类,每个像素都有一个合适的类值 (0-N) :)

显然这不是一个大问题,我可以遍历每个像素,检查 RGB 值,如果它们不在“已发现的 RGB”临时列表中,我添加这些值并为这些 RGB 值提供代表类的整数值,否则我在 tempList 中搜索 rgb 值,并给出我在列表中记下的整数值 - 或类似的值。

但说实话,我需要对很多图像执行此操作,并且我尝试使用 python 来做得更好。所以我想知道是否有人有更有效的方法来做到这一点?我浏览了图书馆和看板,但找不到好的方法。

Far*_*hid 5

您可以将三个 8 位整数转换为 32 位整数,并轻松恢复这三个整数。这个想法是使用按位运算,这样每个 8 位代表一种 RGB 颜色。这样你就已经知道N = 16777215(包括零)= 256**3。

下面的代码可以做到这一点:

def rgbtoint32(rgb):
    color = 0
    for c in rgb[::-1]:
        color = (color<<8) + c
        # Do not forget parenthesis.
        # color<< 8 + c is equivalent of color << (8+c)
    return color

def int32torgb(color):
    rgb = []
    for i in range(3):
        rgb.append(color&0xff)
        color = color >> 8
    return rgb

rgb = [32,253,200]
color = rgbtoint32(rgb)
rgb_c = int32torgb(color)

print(rgb)
print(color)
print(rgb_c)
Run Code Online (Sandbox Code Playgroud)

这给出:

[32, 253, 200]
13172000
[32, 253, 200]
Run Code Online (Sandbox Code Playgroud)

更新:使用 numpy 中的“view”,如下文“Mad Physicist”所示,可以有效地执行上述过程:

rgb = np.array([[[32,253,200], [210,25,42]]],dtype = np.uint8)
size_d = list(rgb.shape)
size_d[2] = -1

# Converting to 2D int32 array
colorint32 = np.dstack((rgb,np.zeros(rgb.shape[:2], 'uint8'))).view('uint32').squeeze(-1)

# Converting back from the int32 array to RGB space
rgb_c = colorint32.view('uint8').reshape(size_d)[:,:,:3]

# Print results
print(rgb)
print(colorint32)
print(rgb_c)
Run Code Online (Sandbox Code Playgroud)

这使

[[[ 32 253 200]
  [210  25  42]]]
[[13172000  2759122]]
[[[ 32 253 200]
  [210  25  42]]]
Run Code Online (Sandbox Code Playgroud)