Skip to main content
 首页 » 编程设计

python之matplotlib改变jpg图像颜色

2024年10月01日12hnrainll

我正在使用 matplotlib imread 函数从文件系统读取图像。但是,它在显示这些图像时会更改 jpg 图像颜色。 [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() 

它正在为所有图像添加蓝色/绿色色调。我做错了什么?

请您参考如下方法:

matplotlib.image.imread 或 matplotlib.pyplot.imread 将图像读取为无符号整数数组。
然后您将其隐式转换为 float。

matplotlib.pyplot.imshow 以不同方式解释两种格式的数组。

  • float 组在 0.0(无颜色)和 1.0(全色)之间解释。
  • 整数数组在 0 和 255 之间解释。

因此,您有两个选择:

  1. 使用整型数组

    test_imgs = np.empty((5,32,32,3), dtype=np.uint8) 
    
  2. 在绘图之前将数组除以 255:

    test_imgs = test_imgs/255.