python读取、显示、保存图片

一、opencv

:cv2.imread(path, mode);读取出来是ndarray。

如果是读取灰度图,需要指定颜色模式cv2.IMREAD_GRAYSCALE,这样读取出的是一个二维数组,而不是彩色图像的三维数组

如果读取彩色图像,则不需要指定读取模式,这样读取出的是一个三维数组(H, W, 3),通道的顺序是BGR

:cv2.imwrite(path, image)。

import cv2
# 使用opencv读写图片
image = cv2.imread('D:/Graph/1.png', cv2.IMREAD_GRAYSCALE)
cv2.imwrite(path, image)

二、Pillow

读:Image.open(path);读取出来是PIL Image对象。

使用PIL包读取图片时不需要指定颜色模式,程序会自动判断。彩色图像的通道顺序为RGB。 

使用这个包的好处在于会读出来一个Image对象,方便后续pytorchtransform方法使用。

写:Image.save(fp, format=None)

save() 方法用于保存图像,当不指定文件格式时,它会以默认的图片格式来存储;如果指定图片格式,则会以指定的格式存储图片。

并非所有的图片格式都可以用 save() 方法转换完成,比如将 PNG 格式的图片保存为 JPG 格式,如果直接使用 save() 方法就会出现以下错误:

from PIL import Image
im = Image.open("C:/Users/Administrator/Desktop/c-net.png")
im.save('C:/Users/Administrator/Desktop/c.biancheng.net.jpg')
# 系统错误,RGBA不能作为JPEG图片的模式
# OSError: cannot write mode RGBA as JPEG

引发错误的原因是由于 PNG 和 JPG 图像模式不一致导致的。其中 PNG 是四通道 RGBA 模式,即红色、绿色、蓝色、Alpha 透明色;JPG 是三通道 RGB 模式。因此要想实现图片格式的转换,就要将 PNG 转变为三通道 RGB 模式。

Image 类提供的 convert() 方法可以实现图像模式的转换。该函数提供了多个参数,比如 mode、matrix、dither 等,其中最关键的参数是 mode,其余参数无须关心。

# convert(mode,parms**)
# mode:指的是要转换成的图像模式
# params:其他可选参数
from PIL import Image
im = Image.open("C:/Users/Administrator/Desktop/c-net.png")
#此时返回一个新的image对象,转换图片模式
image=im.convert('RGB')
#调用save()保存
image.save('C:/Users/Administrator/Desktop/c.biancheng.net.jpg')

三、matplotlib

显示图片用matplotlib.pyplot包:plt.imshow(ndarray, cmap)

import matplotlib.pyplot as plt
# plt.show函数需要指明颜色模式
plt.imshow(image, cmap='gray')
plt.show()
plt.savefig(path)

参考:

python读取、显示、保存图片的几种方法_遇到坎就得迈过去的博客-CSDN博客_python 保存图片

Python Pillow Image.save 保存为jpg图片压缩问题_python_脚本之家 (jb51.net)

猜你喜欢

转载自blog.csdn.net/qq_41021141/article/details/125939092