python直接读取tar文件中的图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29007291/article/details/82119119

背景: tar文件过大,解压缩太慢又占空间,希望直接读取其中的图片


分析:
涉及到两方面:
1. 获取其中的文件名;
2. 读取其中的文件

具体操作:
1. 利用 tarfile 模块读取其中文件名

#假设文件名为 n01440764.tar 并置于E盘下
import tarfile

#读取文件名,并放到list中
name_list = []
with tarfile.open("E:/n01440764.tar", "r") as file:
    for i in file.getmembers():
        name_list.append(i.name)

2 利用PIL模块与 numpy 模块读入图片并转为numpy array

import numpy as np
from PIL import Image, TarIO

#利用Image类读入图片
fp = TarIO.TarIO("E:/n01440764.tar", "n01440764_11974.JPEG")
im = Image.open(fp)

#从Image类转化为numpy array
im = np.asarray(im)
im.flags.writeable = True;
plt.imshow(im)

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/82119119