使用 Python 从分割图像创建标签数据集

Creating a label dataset from a segmented image using Python

我已经标记了图像以生成带有标签的 numpy 数组,例如

array([[0, 1, 0, ..., 0, 0, 0],
        [0, 1, 0, ..., 0, 0, 0],
        [0, 1, 0, ..., 0, 0, 0],
        ..., 
        [0, 0, 0, ..., 0, 0, 0],
        [2, 2, 0, ..., 0, 0, 0],
        [2, 2, 0, ..., 0, 0, 0]], dtype=uint8)}

将其转化为数据集的最有效方法是什么:

x-coord | y-coord | label 
-------------------------
0       | 0       | 0
0       | 1       | 1
0       | 2       | 0
...
1024    | 0       | 2
1024    | 1       | 2

等等

我不介意输出格式是什么,但我希望字典会最方便。

这是我当前的慢速代码,它遍历图像的坐标:

(x, y) = img.shape
for x1, x2 in np.ndindex((x, y)):
    data[(x1, x2)] = img[x1, x2]

我这样做的原因是我想为每个像素向数组添加其他功能。

您可以使用 np.meshgrid and np.vstack 创建一个 Nx3 numpy 数组,其格式与矢量化方式所要求的格式相似,例如 -

In [103]: img
Out[103]: 
array([[0, 1, 1, 0, 0],
       [0, 1, 0, 0, 1],
       [1, 1, 1, 1, 2],
       [2, 1, 1, 0, 2]])

In [104]: M,N = img.shape

In [105]: Y,X = np.meshgrid(np.arange(N),np.arange(M))

In [106]: np.vstack((X,Y,img)).reshape(3,-1).T
Out[106]: 
array([[0, 0, 0],
       [0, 1, 1],
       [0, 2, 1],
       [0, 3, 0],
       [0, 4, 0],
       [1, 0, 0],
       [1, 1, 1],
       [1, 2, 0],
       [1, 3, 0],
       [1, 4, 1],
       [2, 0, 1],
       [2, 1, 1],
       [2, 2, 1],
       [2, 3, 1],
       [2, 4, 2],
       [3, 0, 2],
       [3, 1, 1],
       [3, 2, 1],
       [3, 3, 0],
       [3, 4, 2]])