NumPy - creating 1-hot tensor from a 2D numpy array

Viewed 1850

I have a numpy 2D array with values that range from 0 to 59.

for those who are familiar with DL and specifically Image Segmentation - I create the array (call it L) from a .png image and the value of each pixel L[x,y] means the class that this pixel belongs to (out of the 60 classes).

I want to create a 1-hot tensor - Lhot, in which (Lhot[x,y,z] == 1) only if (L[x,y] == z), and 0 otherwise.

I want to create it with some kind of broadcasting/indexing (1,2 lines) - without loops.

it should be functionally equal to this piece of code (Dtype corresponds to L):

Lhot = np.zeros((L.shape[0], L.shape[1], 60), dtype=Dtype)
for i in range(L.shape[0]):
    for j in range(L.shape[1]):
        Lhot[i,j,L[i,j]] = 1

anyone has an idea? Thanks!

2 Answers
Related