对于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
我想知道是否有更简单的方法来完成这项工作。谢谢!
最佳答案
我试图考虑更普遍的问题,即每个波段中可以有 0 到 255 之间的任何值,甚至超过 3 个波段......
我们可以通过对每列应用不同的位移位来编码 0 和 255 的位置(第 0、1 和/或 2 列中的 0 为 0 到 3 位,第 0 列中的 255 为 4 到 6 位, 1 和/或 2):
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
从那里它是一个标准的 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...
等效的公式是:
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
关于python - 将具有特定颜色图的 3D 图像转换为具有特定 int 值的 2D 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123180/