numpy 我看不懂这些代码,有人能给我解释一下吗

tzdcorbm  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(159)

我来到acros这段代码,我似乎不能理解它。

label_seg = np.zeros(img.shape,dtype=np.uint8)
for i in range(mask_labels.shape[0]):
    label_seg[np.all(img == list(mask_labels.iloc[i, [1,2,3]]), axis=-1)] = i
    label_seg = label_seg[:,:,0]

我试着把它分解,但我还是没有想出任何好的理解

o2g1uqev

o2g1uqev1#

我的(疯狂的)猜测,因为你没有提供输入的例子。
此代码采用3通道图像img(例如RGB),并将其与DataFrame mask_labels中的已知颜色进行比较,然后在新数组label_seg中分配颜色的索引以识别匹配项。
我认为代码中有一些错误:

  • 最后一行不应该是for循环的一部分
  • DataFrame的第一行/颜色Map到0,这也是输入中的默认值。

使用示例:

np.random.seed(0)

img = np.random.randint(0, 255, (5, 5, 3))

mask_labels = pd.DataFrame([[0,  58, 193, 230],
                            [0, 127,  32,  31],
                            [0, 193,   9, 185],
                           ])

# generate an output of the same shape as the input image
label_seg = np.zeros(img.shape, dtype=np.uint8)

# for each row in the DataFrame
for i in range(mask_labels.shape[0]):
    # take the columns 1,2,3
    # if all 3 values match in the img array (same x/y position, all 3 channels)
    # assign the row index in the output array at the same x/y position
    label_seg[np.all(img == list(mask_labels.iloc[i, [1,2,3]]), axis=-1)] = i

label_seg = label_seg[:,:,0]

输出label_seg

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

img(作为图像,每个单元格是一个像素):

masked_labels

0    1    2    3
0  0   58  193  230
1  0  127   32   31
2  0  193    9  185

颜色:

相关问题