Python 将具有特定颜色贴图的三维图像转换为具有特定int值的二维图像

Python 将具有特定颜色贴图的三维图像转换为具有特定int值的二维图像,python,numpy,Python,Numpy,对于3d图像,它有6个类,分别是: Impervious surfaces (RGB: 255, 255, 255) Building (RGB: 0, 0, 255) Low vegetation (RGB: 0, 255, 255) Tree (RGB: 0, 255, 0) Car (RGB: 255, 255, 0) Clutter/background (RGB: 255, 0, 0) 我想将此图像转换为2d图像,其中 Impervious surfaces --> 0 Bui

对于3d图像,它有6个类,分别是:

Impervious surfaces (RGB: 255, 255, 255)
Building (RGB: 0, 0, 255)
Low vegetation (RGB: 0, 255, 255)
Tree (RGB: 0, 255, 0)
Car (RGB: 255, 255, 0)
Clutter/background (RGB: 255, 0, 0)
我想将此图像转换为2d图像,其中

Impervious surfaces --> 0
Building --> 1
Low vegetation --> 2
Tree --> 3
Car --> 4
Clutter/background --> 5
我只能将for循环用作:

im = imageio.imread('kPUoO.png')
w,h = im.shape[:2]
im_ = np.zeros((w,h), dtype=np.uint8)
for i in range(w):
    for j in range(h):
        if list(im[i,j]) == [0,0,255]:
            im_[i,j] = 1
        if list(im[i,j]) == [0,255,255]:
            im_[i,j] = 2
        if list(im[i,j]) == [0,255,0]:
            im_[i,j] = 3
        if list(im[i,j]) == [255,255,0]:
            im_[i,j] = 4
        if list(im[i,j]) == [255,0,0]:
            im_[i,j] = 5

我想知道有没有更简单的方法来完成这项工作。谢谢

我试图思考一个更一般的问题,在这个问题中,每个波段中可以有0到255之间的任意值,甚至可以有3个以上的波段

im = imageio.imread('kPUoO.png')
w,h = im.shape[:2]
im_ = np.zeros((w,h), dtype=np.uint8)
pos1 = np.where((im[:,:,0]==0) & (im[:,:,1]==0) & (im[:,:,2]==255))
pos2 = np.where((im[:,:,0]==0) & (im[:,:,1]==255) & (im[:,:,2]==255))
pos3 = np.where((im[:,:,0]==0) & (im[:,:,1]==255) & (im[:,:,2]==0))
pos4 = np.where((im[:,:,0]==255) & (im[:,:,1]==255) & (im[:,:,2]==0))
pos5 = np.where((im[:,:,0]==255) & (im[:,:,1]==0) & (im[:,:,2]==0))
im_[pos1] = 1
im_[pos2] = 2
im_[pos3] = 3
im_[pos4] = 4
im_[pos5] = 5
我们可以通过对每列应用不同的位移位对0和255的位置进行编码(0、1和/或2列中的0为0到3位,0、1和/或2列中的255为4到6位):

从那里可以得到一个标准的1:1映射来重新标记类。我认为对于较大的图像或大量的图像,这种方法可能会更快

要了解其工作原理,请执行以下操作:

0,0,0 = 1<<0 + 1<<1 + 1<<2 + 0<<3 + 0<<4 + 0<<5 = 7, /7 = 1
0,0,255 = 1<<0 + 1<<1 + 0<<2 + 0<<3 + 0<<4 + 1<<5 = 35, /7 = 5
0,255,255 = 1<<0 + 0<<1 + 0<<2 + 0<<3 + 1<<4 + 1<<5 = 49, /7 = 7
255,255,255 = 0<<0 + 0<<1 + 0<<2 + 1<<3 + 1<<4 + 1<<5 = 56, /7 = 8
etc...

也许您的数据最初只有六个类,但现在有更多。例如,
im[0,0]
[14255237]
。该图像中有4000多种不同的颜色。图像以以下格式存储,即。如果您最初只有问题中提到的六种颜色,并且希望在图像文件中保留这些值,请使用无损格式,例如。好的,我看到了,谢谢!
numpy.add.reduce(a, -1) // 7
0,0,0 = 1<<0 + 1<<1 + 1<<2 + 0<<3 + 0<<4 + 0<<5 = 7, /7 = 1
0,0,255 = 1<<0 + 1<<1 + 0<<2 + 0<<3 + 0<<4 + 1<<5 = 35, /7 = 5
0,255,255 = 1<<0 + 0<<1 + 0<<2 + 0<<3 + 1<<4 + 1<<5 = 49, /7 = 7
255,255,255 = 0<<0 + 0<<1 + 0<<2 + 1<<3 + 1<<4 + 1<<5 = 56, /7 = 8
etc...
a = (im == 0) * numpy.array([1,2,4], numpy.uint8)
a += (im == 255) * numpy.array([8,16,32], numpy.uint8)
numpy.add.reduce(a, -1) //7