人脸图像读取
首先,先调用三个库
import numpy
as np
import cv2
import zipfile
然后确定一下主程序,搞清楚我们这个程序的目的。是为了从解压解压上读取图像。
if __name__
== '__main__':
path
= 'D:\\DeepBlue\\samples\\celeba\\Eval\\Img\\img_ali.gn_cel.eba.zip'
ca
= CelebA
()
cv2
.imshow
(ca
.imgs
[1000])
cv2
.waitKey
()
然后定义一个类CelebA,在构造方法里 ,定义imgs。
class CelebA:
def __init__(self
,path
):
self
.imgs
= []
紧接着放一个with语句对zipfile.ZipFile(path)做一个抛出异常操作,并将zipfile.ZipFile(path)命名为zf(zipfile.ZipFile(path)就是openc中解压文件的方法)
with zipfile
.ZipFile
(path
) as zf
:
用is_dir函数判断info文件否是文件夹,如果是就跳过。
for info
in zf
.filelist
:
if info
.is_dir
(): continue
首先从我们的filename中提取出流数据,并转化成uint8数据,最后对uint8数据进行解码使其形成图片
img
= zf
.read
(info
.filename
)
img
= np
.frombuffer
(img
, np
.uint8
)
img
= cv2
.imdecode
(img
, 1)
然后找出名字并将图像存储到imgs列表中
name
= info
.filename
[info
.filename
.rfind
('/')+1:]
self
.imgs
.append
(img
)
因为不断地输出名字会显得很杂乱无章,所以这里我们让他每完成10000组图像的读取进行一次说明
if len(self
.imgs
) % 10000 == 0:
print('Read %d imgs' % len(self
.imgs
))
最后输出完成语句
print('Read %d imgs from %s successfully!' % (len(self
.imgs
),path
),flush
=True)
完整代码:
import zipfile
import numpy
as np
import cv2
class CelebA:
def __init__(self
,path
):
self
.imgs
= []
with zipfile
.ZipFile
(path
) as zf
:
for info
in zf
.filelist
:
if info
.is_dir
(): continue
img
= zf
.read
(info
.filename
)
img
= np
.frombuffer
(img
, np
.uint8
)
img
= cv2
.imdecode
(img
, 1)
name
= info
.filename
[info
.filename
.rfind
('/')+1:]
self
.imgs
.append
(img
)
if len(self
.imgs
) % 10000 == 0:
print('Read %d imgs' % len(self
.imgs
))
print('Read %d imgs from %s successfully!' % (len(self
.imgs
),path
),flush
=True)
if __name__
== '__main__':
path
= 'D:\\DeepBlue\\samples\\celeba\\Eval\\Img\\img_ali.gn_cel.eba.zip'
ca
= CelebA
()
cv2
.imshow
(ca
.imgs
[1000])
cv2
.waitKey
()
结果如图: