matplotlib changes jpg image color

坚强是说给别人听的谎言 提交于 2021-01-27 22:14:37

问题


I'm reading images from filesystem using matplotlib imread function. However, it changes jpg image color when it displays those images. [Python 3.5, Anaconda3 4.3, matplotlib2.0]

# reading 5 color images of size 32x32
imgs_path = 'test_images'
test_imgs = np.empty((5,32,32,3), dtype=float)
img_names = os.listdir('test_images'+'/')
for i, img_name in enumerate(img_names):
    #reading in an image
    image = mpimg.imread(imgs_path+'/'+img_name)
    test_imgs[i] = image

#Visualize new raw images
plt.figure(figsize=(12, 7.5))
for i in range(5):
    plt.subplot(11, 4, i+1)
    plt.imshow(test_imgs[i]) 
    plt.title(i)
    plt.axis('off')
plt.show()

It is adding a bluish/greenish tint to all the images. Any mistake I'm doing?


回答1:


matplotlib.image.imread or matplotlib.pyplot.imread read the image as unsigned integer array.
You then implicitely convert it to float.

matplotlib.pyplot.imshow interpretes arrays in both formats differently.

  • float arrays are interpreted between 0.0 (no color) and 1.0 (full color).
  • integer arrays are interpreted between 0 and 255.

The two options you have are thus:

  1. Use an integer array

    test_imgs = np.empty((5,32,32,3), dtype=np.uint8)
    
  2. divide the array by 255. prior to plotting:

    test_imgs = test_imgs/255.
    



回答2:


Matplotlib reads image in RGB format whereas if you use opencv it reads image in BGR format. First convert your .jpg image in RGB and then try displaying it. It worked for me.



来源:https://stackoverflow.com/questions/42455891/matplotlib-changes-jpg-image-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!