Convert rgb values to one hot labels

Viewed 192

I got an RGB image

 img= np.array(Image.open(path, dtype=np.uint8))

with 3 unique labels:

 labels = list(np.unique(img.reshape(-1, img.shape[2]), axis=0))
 
labels =

[array([  0,   0, 255...ype=uint8), array([255,   0, 255...ype=uint8), array([255, 255, 255...ype=uint8)]

I want to write some code to convert the RGB values to one hot labels, e.g:

[0,0,255] -> [0,0,1] , [255,0,255] -> [1,0,0],  [255,255,255] -> [0,1,0].

I tried:

    for i in range(len(labels)):
      label = labels[i]
      layout[img==label] = i

But can't even index the cells, since I got:

NumPy boolean array indexing assignment cannot assign 3 input values to the 233357 output values where the mask is true
1 Answers

I am assuming layout is the variable where you want to store the modified i.e., one-hot encoded image and img is the original image or numpy array having shape M x N x 3.

labels_old = [[0, 0, 255], [255, 0, 255],  [255, 255, 255]]
labels_new = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]

layout = img.copy()
for i, label in enumerate(labels_old):
    layout[np.all(img == label, axis = -1)] = labels_new[i]
Related