代码之家  ›  专栏  ›  技术社区  ›  Panfeng Li

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

  •  1
  • Panfeng Li  · 技术社区  · 7 年前

    为了 this 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)
    

    我想把这个图像转换成二维图像,在这里

    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
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   Benjamin Cintix    7 年前

    我们可以通过对每列应用不同的位移位来对0和255的位置进行编码(0、1和/或2列中的0为0到3位,0、1和/或2列中的255为4到6位):

    a = (im == 0) << numpy.array([0,1,2], numpy.uint8)
    a += (im == 255) << numpy.array([3,4,5], numpy.uint8)
    

    沿着最后一个轴的和唯一地编码这些类。除7是没有必要的,它只是给出了更简单的类标签。

    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
    
        2
  •  0
  •   Panfeng Li    7 年前
    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