python中读取和保存图片的几种方式及其它们之间图片格式的相互转换

第一种:PIL读取方式

from PIL import Image
I = Image.open('./0.png')
print(type(I))       #---><class 'PIL.JpegImagePlugin.JpegImageFile'>
print(I.size)        #--->(1280, 720)
I.show()
I.save('./save.png')

第二种:imread读取方式

import matplotlib.pyplot as plt
from scipy.misc import imread, imsave
I = imread('./0.png')
print(type(I))       #---><class 'numpy.ndarray'>
print(I.shape)       #--->(720, 1280, 3)
print(I.size)        #--->2764800
imsave('./save1.png', I)
plt.imshow(I)
plt.show()

第三种:cv2读取方式

import cv2
I = cv2.imread('./0.png')
cv2.namedWindow('input_image', cv2.WINDOW_AUTOSIZE)
I = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY) #灰度化 cv2.imshow(
'input_image', I) cv2.imwrite('./save1.png', I) print(type(I)) #---><class 'numpy.ndarray'> print(I.shape) #--->(720, 1280, 3) #参数=0:(也可以是小于0的数值)一直显示,不会有返回值,若在键盘上按下一个键即会消失,则会返回一个按键对应的ascii码值 #参数>0:显示多少毫秒,超过这个指定时间则返回-1 cv2.waitKey(0) cv2.destroyAllWindows()

图片格式的相互转换:

from PIL import Image
import numpy as np
I = Image.open('./0.png')
print(type(I))        #---><class 'PIL.JpegImagePlugin.JpegImageFile'>
print(I.size)         #--->(1280, 720)
I_array = np.array(I)
print(type(I_array))  #---><class 'numpy.ndarray'>
print(I_array.shape)  #--->(720, 1280, 3)
from PIL import Image
from scipy.misc import imread
I = imread('./0.png')
print(type(I))        #---><class 'numpy.ndarray'>
print(I.shape)        #--->(720, 1280, 3)
print(I.size)         #--->2764800
I = Image.fromarray(I)
print(type(I))        #---><class 'PIL.Image.Image'>
print(I.size)         #--->(1280, 720)
import cv2
from PIL import Image
I = cv2.imread('./0.png')
print(type(I))        #---><class 'numpy.ndarray'>
print(I.shape)        #--->(720, 1280, 3)
I = Image.fromarray(I)
print(type(I))        #---><class 'PIL.Image.Image'>
print(I.size)         #--->(1280, 720)

总结:

1.  'numpy.ndarray'的形状为(H, W, C),而'PIL.Image.Image'的形状为(W, H)。

2.  'numpy.ndarray'的形状属性为.shape,而'PIL.Image.Image'的形状属性为.size。

Image、cv2、io这三种读取的图片位深度都为16,那么保存的图片的位深度分别为:16、8、8。

转载于:https://www.cnblogs.com/czz0508/p/10846702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值