pythonnumpyopencvimage-processingbinary-image

Coloring the categorical image


I have a categorical image with the size of 14400 * 7200. I am trying the following code to colorize the values ​​in this image. It works but takes a long time. How can I do this in a shorter time?

        color_map = {}
        for category in np.unique(np.arange(201, dtype=np.uint8)):
            color_map[category] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))   
            
        color_map["0"]=(128, 64,128) 
        color_map["1"]=(232, 35,244)
        color_map["2"]=( 70, 70, 70)
        color_map["3"]=(156,102,102)
        color_map["4"]=(255,255,204)
        color_map["5"]=(153,153,153)
        color_map["6"]=(30,170, 250)
        color_map["7"]=(30,170, 250)
        color_map["8"]=(52,219, 163)
        color_map["9"]=(0,102, 102)
        color_map["10"]=( 180,130,70)
        color_map["11"]=(60, 20, 220)
        color_map["12"]=(60, 20, 220)
        color_map["13"]=(255, 0, 0)
        color_map["14"]=(255, 0, 0)
        color_map["15"]=(255, 0, 0)
        color_map["16"]=(255, 0, 0)
        color_map["17"]=(255, 0, 0)
        color_map["18"]=(255, 0, 0)
        color_map["40"]=(0, 0, 0)
        color_map["41"]=(0, 1, 0)
        color_map["42"]=(0, 2, 0)
        color_map["43"]=(0, 3, 0)
        color_map["44"]=(0, 4, 0)
        color_map["45"]=(0, 5, 0)
        color_map["46"]=(0, 6, 0)
        color_map["47"]=(0, 7, 0)
        color_map["48"]=(0, 8, 0)
        color_map["49"]=(0, 9, 0)
        color_map["50"]=(0, 10, 0)
        color_map["51"]=(0, 11, 0)
        
        a_array = np.array(a)

        
        category_image = a_array
        colored_image = np.zeros((category_image.shape[0], category_image.shape[1], 3), dtype=np.uint8)
        for h in range(category_image.shape[0]):
            for g in range(category_image.shape[1]):
                category = category_image[h, g]
                colored_image[h, g] = color_map[str(category)]#normalde str yok
        cv2.imwrite(j, colored_image)

thanks for your solutions


Solution

  • Instead of looping over every pixel, use numpy masking to choose indices in colored_image and assign to them:

    for category in np.unique(category_image):
        colored_image[category_image == category] = color_map[category]
    

    On my machine, this runs through a random 1024x1024 image in 0.16 seconds.

    Note you'll need to change color_map's keys to be ints, not strings:

    color_map[0] = (128, 64, 128)
    color_map[1] = (232, 35, 244)
    # etc ...