Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?

前端 未结 1 1207
逝去的感伤
逝去的感伤 2021-02-10 11:46

There is a bmp image just as shown the first picture bellow, and its information is list as the second picture bellow. But when display with plt.imshow() function of matplotlib

相关标签:
1条回答
  • 2021-02-10 12:48

    This happen because you are actually plotting the image as matrix with matplotlib.pyplot. Matplotlib doesn't support .bmpnatively so I think there are some error with the default cmap. In your specific case you have a grayscale image. So in fact you can change the color map to grayscale with cmap="gray".

    from PIL import Image
    img= Image.open(r'./test/test2.bmp')
    plt.imshow(img,cmap='gray',vmin=0,vmax=255)
    

    Note you have to set vmin and vmax if you want to reproduce the same luminance of your original image otherwise I think python by default will stretch to min max the values. This is a solution without importing PIL:

    img=matplotlib.image.imread(r'/Users/giacomo/Downloads/test2.bmp')
    plt.imshow(img,cmap='gray',vmin=0,vmax=255)
    

    Alternatively you can use PIL to show the image or you can convert your image to a .png before.

    If you want show the image with PIL.Image you can use this:

    from PIL import Image
    img= Image.open( r'./test/test2.bmp')
    img.show()
    

    Note if you are using I-Python Notebook the image is shown in a new external window

    Another option is to change the mode of the image to 'P' (Palette encoding: one byte per pixel, with a palette of class ImagePalette translating the pixels to colors). With .convert and then plot the image with matplotlib plt.imshow:

    convertedimg=img.convert('P')
    plt.imshow(convertedimg)
    

    enter image description here

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