人脸图像读取
- 首先,先调用三个库
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 # is_die(检查是否是目录)————>bool
- 首先从我们的filename中提取出流数据,并转化成uint8数据,最后对uint8数据进行解码使其形成图片
img = zf.read(info.filename)
img = np.frombuffer(img, np.uint8) # frombuffer 收集数据,uint8:将收集的数据转制为八位的数组
img = cv2.imdecode(img, 1) # cv2.imdecode:解码成图,1是彩图,2是灰度图
- 然后找出名字并将图像存储到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) #flush参数主要是刷新, 默认flush = False,不刷新,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# is_die(检查是否是目录)————>bool
img = zf.read(info.filename)
img = np.frombuffer(img, np.uint8) # frombuffer 收集数据,uint8:将收集的数据转制为八位的数组
img = cv2.imdecode(img, 1) # cv2.imdecode:解码成图,1是彩图,2是灰度图
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) #flush参数主要是刷新, 默认flush = False,不刷新,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()
结果如图: