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
猜你喜欢
- 淡入淡出图片轮换轮播效果,可以做新闻图片推荐需要的拿去用,效果预览请点击运行代码相关效果推荐:迅雷首页新闻图片轮播效果js源码 <!D
- 本文实例为大家分享了python实现多人聊天室的具体代码,供大家参考,具体内容如下刚开始学习python,写了一个聊天室练练手。Server
- 准备篇:1、配置防火墙,开启80端口、3306端口vi /etc/sysconfig/iptables-A INPUT -m state -
- 如何在页面错误时向数据库中添加记录?在ASP中,我在页面中添加了On Error Resume Next错误命令,以消除和避免程序错误。现在
- 本文实例讲述了php实现的一段简单概率相关代码。分享给大家供大家参考,具体如下:<?phpfor($i=1;$i<100000;
- 前言前几天逛github发现了一个有趣的并发库-conc,其目标是:更难出现goroutine泄漏处理panic更友好并发代码可读性高从简介
- 在 settings.py 中添加以下内容:LOGGING = { 'version': 1,
- 因为有个老Yashica相机机身,前一阵忍不住想配几个标准镜头。到国内购物网站以及摄影器材交流论坛上看了看,发现不仅很少,价格不实在,而且品
- 问题:我想上传文件时后改名,下载时又将名改回来。 如:我上传一张“我的照片.jpg”上传后改为系统数名“20040302001.jpg”下载
- string模块可以追溯到早期版本的Python。以前在本模块中实现的许多功能已经转移到str物品。这个string模块保留了几个有用的常量
- 主程序mainaddfunc.pyfrom flask import Flask, render_template, request, ur
- 代码'########### '检测远程文件是否存在 '########### function CheckURL(
- 在设计网页之前,客户或产品经理会提出对网页视觉风格设计的期望:活跃、大气、稳重、信赖、都市化….. 设计师一听到关键词或许很自然地在心里蹦出
- ‘Microsoft OLE DB Provider for ODBC Drivers (0x80004005) [Microsoft][O
- 如下所示:x = 3print(x+"nihao")这样会报错x = 3print(x,"nihao"
- Security vulnerability in MySQL/MariaDB 在知道用户名的情况下(如root),直接反复重试(平均大约2
- 本文实例讲述了Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)。分享给大家供大家参考,具体
- 如果没有了解栅格系统是什么,建议看完这篇文章以后再回来。其实有很种 CSS 写法实现栅格系统,很多 CSS 库也都会提供类似的栅格系统实现(
- Cloudflare 有一项功能挺不错的,就是将页面上所有的邮箱地址都加密起来,防止机器人抓到然后干坏事。这项功能要在后台开启 email
- 光学元件类平面反射镜是一种极为简单的模型,因为我们只需要考虑一个平面即可。但是除此之外的其他光学元件,可能会变得有些复杂:我们必须考虑光在入