Save numpy array as single channel png with custom colors

后端 未结 1 1213
孤城傲影
孤城傲影 2021-01-24 05:04

I have an integer numpy array representing image with few values (about 2-5). And I would like to save it to png file with custom color for every value. I was trying it like thi

1条回答
  •  离开以前
    2021-01-24 05:45

    You can make a palette image like this:

    #!/usr/bin/env python3
    
    from PIL import Image
    import numpy as np
    
    # Make image with small random numbers
    im = np.random.randint(0,5, (4,8), dtype=np.uint8)
    
    # Make a palette
    palette = [255,0,0,    # 0=red
               0,255,0,    # 1=green
               0,0,255,    # 2=blue
               255,255,0,  # 3=yellow
               0,255,255]  # 4=cyan
    # Pad with zeroes to 768 values, i.e. 256 RGB colours
    palette = palette + [0]*(768-len(palette))
    
    # Convert Numpy array to palette image
    pi = Image.fromarray(im,'P')
    
    # Put the palette in
    pi.putpalette(palette)
    
    # Display and save
    pi.show()
    pi.save('result.png')
    

    0 讨论(0)
提交回复
热议问题