python - 将具有特定颜色图的 3D 图像转换为具有特定 int 值的 2D 图像

标签 python numpy

对于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/

相关文章:

python - 在 Python 中,如何打印完整的 ISO 8601 时间戳,包括当前时区

python - Exchange Web 服务 (EWS) - 通过 suds 的 Exchange 2010 soap 调用

python - 解析 pandas Dataframe 并根据不同条件应用规则

python - 在数组和元组之间转换时的舍入问题

python - 求解多个参数的方程/表达式

python - NumPy memmap 性能问题

python - 将 Pandas Dataframe 转换为 sklearn 的 numpy

python - Perspective Broker 可以通过 stdio 而不是 TCP 使用吗?

python - 在外部循环中更新 Tkinter GUI

python - 第二次运行 np.empty