Python图像读写方法对比
作者:颀周 发布时间:2022-10-07 08:13:46
1 实验标准
因为训练使用的框架是Pytorch,因此读取的实验标准如下:
1、读取分辨率都为1920x1080的5张图片(png格式一张,jpg格式四张)并保存到数组。
2、将读取的数组转换为维度顺序为CxHxW的Pytorch张量,并保存到显存中(我使用GPU训练),其中三个通道的顺序为RGB。
3、记录各个方法在以上操作中所耗费的时间。因为png格式的图片大小差不多是质量有微小差异的jpg格式的10倍,所以数据集通常不会用png来保存,就不比较这两种格式的读取时间差异了。
写入的实验标准如下:
1、将5张1920x1080的5张图像对应的Pytorch张量转换为对应方法可使用的数据类型数组。
2、以jpg格式保存五张图片。
3、记录各个方法保存图片所耗费的时间。
2 实验情况
2.1 cv2
因为有GPU,所以cv2读取图片有两种方式:
1、先把图片都读取为一个numpy数组,再转换成保存在GPU中的pytorch张量。
2、初始化一个保存在GPU中的pytorch张量,然后将每张图直接复制进这个张量中。
第一种方式实验代码如下:
import os, torch
import cv2 as cv
import numpy as np
from time import time
read_path = 'D:test'
write_path = 'D:test\\write\\'
# cv2读取 1
start_t = time()
imgs = np.zeros([5, 1080, 1920, 3])
for img, i in zip(os.listdir(read_path), range(5)):
img = cv.imread(filename=os.path.join(read_path, img))
imgs[i] = img
imgs = torch.tensor(imgs).to('cuda')[...,[2,1,0]].permute([0,3,1,2])/255
print('cv2 读取时间1:', time() - start_t)
# cv2保存
start_t = time()
imgs = (imgs.permute([0,2,3,1])[...,[2,1,0]]*255).cpu().numpy()
for i in range(imgs.shape[0]):
cv.imwrite(write_path + str(i) + '.jpg', imgs[i])
print('cv2 保存时间:', time() - start_t)
实验结果:
cv2 读取时间1: 0.39693760871887207
cv2 保存时间: 0.3560612201690674
第二种方式实验代码如下:
import os, torch
import cv2 as cv
import numpy as np
from time import time
read_path = 'D:test'
write_path = 'D:test\\write\\'
# cv2读取 2
start_t = time()
imgs = torch.zeros([5, 1080, 1920, 3], device='cuda')
for img, i in zip(os.listdir(read_path), range(5)):
img = torch.tensor(cv.imread(filename=os.path.join(read_path, img)), device='cuda')
imgs[i] = img
imgs = imgs[...,[2,1,0]].permute([0,3,1,2])/255
print('cv2 读取时间2:', time() - start_t)
# cv2保存
start_t = time()
imgs = (imgs.permute([0,2,3,1])[...,[2,1,0]]*255).cpu().numpy()
for i in range(imgs.shape[0]):
cv.imwrite(write_path + str(i) + '.jpg', imgs[i])
print('cv2 保存时间:', time() - start_t)
实验结果:
cv2 读取时间2: 0.23636841773986816
cv2 保存时间: 0.3066873550415039
2.2 matplotlib
同样两种读取方式,第一种代码如下:
import os, torch
import numpy as np
import matplotlib.pyplot as plt
from time import time
read_path = 'D:test'
write_path = 'D:test\\write\\'
# matplotlib 读取 1
start_t = time()
imgs = np.zeros([5, 1080, 1920, 3])
for img, i in zip(os.listdir(read_path), range(5)):
img = plt.imread(os.path.join(read_path, img))
imgs[i] = img
imgs = torch.tensor(imgs).to('cuda').permute([0,3,1,2])/255
print('matplotlib 读取时间1:', time() - start_t)
# matplotlib 保存
start_t = time()
imgs = (imgs.permute([0,2,3,1])).cpu().numpy()
for i in range(imgs.shape[0]):
plt.imsave(write_path + str(i) + '.jpg', imgs[i])
print('matplotlib 保存时间:', time() - start_t)
实验结果:
matplotlib 读取时间1: 0.45380306243896484
matplotlib 保存时间: 0.768944263458252
第二种方式实验代码:
import os, torch
import numpy as np
import matplotlib.pyplot as plt
from time import time
read_path = 'D:test'
write_path = 'D:test\\write\\'
# matplotlib 读取 2
start_t = time()
imgs = torch.zeros([5, 1080, 1920, 3], device='cuda')
for img, i in zip(os.listdir(read_path), range(5)):
img = torch.tensor(plt.imread(os.path.join(read_path, img)), device='cuda')
imgs[i] = img
imgs = imgs.permute([0,3,1,2])/255
print('matplotlib 读取时间2:', time() - start_t)
# matplotlib 保存
start_t = time()
imgs = (imgs.permute([0,2,3,1])).cpu().numpy()
for i in range(imgs.shape[0]):
plt.imsave(write_path + str(i) + '.jpg', imgs[i])
print('matplotlib 保存时间:', time() - start_t)
实验结果:
matplotlib 读取时间2: 0.2044532299041748
matplotlib 保存时间: 0.4737534523010254
需要注意的是,matplotlib读取png格式图片获取的数组的数值是在[0,1][0,1]范围内的浮点数,而jpg格式图片却是在[0,255][0,255]范围内的整数。所以如果数据集内图片格式不一致,要注意先转换为一致再读取,否则数据集的预处理就麻烦了。
2.3 PIL
PIL的读取与写入并不能直接使用pytorch张量或numpy数组,要先转换为Image类型,所以很麻烦,时间复杂度上肯定也是占下风的,就不实验了。
2.4 torchvision
torchvision提供了直接从pytorch张量保存图片的功能,和上面读取最快的matplotlib的方法结合,代码如下:
import os, torch
import matplotlib.pyplot as plt
from time import time
from torchvision import utils
read_path = 'D:test'
write_path = 'D:test\\write\\'
# matplotlib 读取 2
start_t = time()
imgs = torch.zeros([5, 1080, 1920, 3], device='cuda')
for img, i in zip(os.listdir(read_path), range(5)):
img = torch.tensor(plt.imread(os.path.join(read_path, img)), device='cuda')
imgs[i] = img
imgs = imgs.permute([0,3,1,2])/255
print('matplotlib 读取时间2:', time() - start_t)
# torchvision 保存
start_t = time()
for i in range(imgs.shape[0]):
utils.save_image(imgs[i], write_path + str(i) + '.jpg')
print('torchvision 保存时间:', time() - start_t)
实验结果:
matplotlib 读取时间2: 0.15358829498291016
torchvision 保存时间: 0.14760661125183105
可以看出这两个是最快的读写方法。另外,要让图片的读写尽量不影响训练进程,我们还可以让这两个过程与训练并行。另外,utils.save_image可以将多张图片拼接成一张来保存,具体使用方法如下:
utils.save_image(tensor = imgs, # 要保存的多张图片张量 shape = [n, C, H, W]
fp = 'test.jpg', # 保存路径
nrow = 5, # 多图拼接时,每行所占的图片数
padding = 1, # 多图拼接时,每张图之间的间距
normalize = True, # 是否进行规范化,通常输出图像用tanh,所以要用规范化
range = (-1,1)) # 规范化的范围
来源:https://www.cnblogs.com/qizhou/p/13972783.html?utm_source=tuicool&utm_medium=referral


猜你喜欢
- MySQL出现乱码的原因要了解为什么会出现乱码,我们就先要理解:从客户端发起请求,到MySQL存储数据,再到下次从表取回客户端的过程中,哪些
- 很多朋友希望,我能把我做网站的一些流程及经验跟大家分享一下,最近刚好做一次内部培训,所以稍微整理了一下,这些只是针对网页初学者,具有一定平面
- 在我们的网站建设中,为网站打造一个契合网站主题的个性化标志则是必需的,这直接关系到能否成功地塑造网站的品牌。这从某些角度看仍在网站推广的范畴
- SQL Server 数据库定时自动备份,供大家参考,具体内容如下在SQL Server中出于数据安全的考虑,所以需要定期的备份数据库。而备
- pydantic是一个Python的数据验证和转换库,它的特点是轻量、快速、可扩展、可配置。笔者常用的用于数据接口schema定义与检查。具
- 前言上一篇博文我们讲到了节流函数的应用场景,我们知道了节流函数可以用在模糊查询、scroller、onresize等场景;今天这篇我们来讲防
- 有2个不同的方法增加用户:通过使用GRANT语句或通过直接操作MySQL授权表。比较好的方法是使用GRANT语句,因为他们是更简明并且好像错
- #!/usr/bin/env python # coding=utf-8 #--------------------------------
- 好了,下面我们看看如何在服务器上生成.m3u文件并下传到客户端的:<%dim choose,path,mydb,myset,
- python解决指定代码段超时程序卡死最近我写的一个程序中遇到了解析网页的代码,对于网页信息比较多的可能会超时,最后解析失败,程序卡死,于是
- mysql-5.7.23-winx64 解压版详细安装教程,供大家参考,具体内容如下1、Click here to download Mys
- 在用户登录windows操作系统的时候,如果触发到了登录表单的密码录入框上,并且此时按下了“大写锁定键(Caps Lock)”,那么界面上会
- 如需安装运行环境或远程调试,可加QQ905733049, 或QQ2945218359由专业技术人员远程协助!运行结果如下:代码如下:impo
- 数组统计函数ndimage提供一系列函数,可以计算标注后的数组的相关特征,比如最值、均值、均方根等。下列函数,如果未作其他说明,那么就有3个
- Qt Designer用于像VC++的MFC一样拖放、设计控件PyUIC用于将Qt Designer生成的.ui文件转换成.py文件Qt D
- 一、Python 矩阵基本运算引入 numpy 库import numpy as np1. python矩阵操作1)使用
- 见下:<form action="./calculation.asp"><input&nbs
- 1.SQL Server2019安装包下载1.1进入官网SQL Server 20191.2下载安装包1点击Continue2.填写个人信息
- 本文实例讲述了Python机器学习算法库scikit-learn学习之决策树实现方法。分享给大家供大家参考,具体如下:决策树决策树(DTs)
- python 读写中文json的实例详解读写中文json想要 读写中文json ,可以使用python中的 json 库可以对j