1

How can I write this for loop in numpy to make it run faster I am trying to convert grayscale label having values 0-7 to a colored image with corresponding colors

def label_img_to_color(img):
    label_to_color = {
        0: [0, 0,0],
        1: [244, 35,232],
        2: [ 70, 70, 70],
        3: [102,102,156],
        4: [190,153,153],
        5: [153,153,153],
        6: [250,170, 30],
        7: [220,220,  0],
        }

    img_height, img_width = img.shape

    img_color = np.zeros((img_height, img_width, 3))
    for row in range(img_height):
        for col in range(img_width):
            label = img[row, col]

            img_color[row, col] = np.array(label_to_color[label])

    return img_color

1 Answers1

1

Here it is

def label_img_to_color_20(img):
    img=img.astype(np.uint8)
    lut=np.ones((256,1,3),dtype=np.uint8)
    
    ine = np.array([[
         [128, 64,128],#road 0 
         [244, 35,232],#sidewalk 1
         [ 70, 70, 70],#building 2
         [190,153,153],#wall  3
         [153,153,153],#fence 4
         [250,170, 30],#pole  5
         [220,220,  0],#traffic light 6
         [107,142, 35],#traffic sign 7
         
    ]])

    
    lut[0:8,:,:]=ine.reshape(8,1,3)
    img_color=cv2.applyColorMap(img,lut)

    return img_color

This was the faster way to do that if anyone runs into a problem like that do not use for loops on images always use numpy or opencv functions to do that because they are implemented in C and run much faster because of that