tensorflow使用h5py持久化数据集

70 篇文章 5 订阅
11 篇文章 1 订阅

import cv2
#正则匹配使用:
import re
import os
#此库用于拷贝,删除,移动,复制以及解压缩
import shutil
import numpy as np
import h5py
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#用于将普通标签转为独热向量
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
#如此读取图像,直接返回numpy.ndarray
#img=cv2.imdecode(np.fromfile(“C:/Users/104005162/Desktop/企业微信截图_20220212102256.png”,np.uint8),-1)
#print(img.shape)
##转换为bgr图片,注意此时是PNG图片,不能用矩阵直接转换!
##img=img[:,:,::-1]
##bgra
#img=cv2.cvtColor(img,cv2.COLOR_BGRA2RGB)
def readPictureByPath(path):
img=cv2.imdecode(np.fromfile(path,np.uint8),-1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#return np.expand_dims(img,0)
return img
#返回样本的分类序号:
def returnNumClass(path):
if “" not in path:
print(“文件路径非法”)
return None
#如果包含路径,提取出数字
else:
return re.findall("
(.*?).”,path)[0]
#该命令读取某文件夹下所有的文件名:
targetPath=“C:/Users/104005162/Desktop/实验文件夹”
path=“C:/Users/104005162/Desktop/实验数据”
#在路径下新建文件夹:
for i in range(4):
#如果待创建文件夹不存在,创建文件夹
if not os.path.exists(os.path.join(targetPath,str(i))):
os.makedirs(os.path.join(targetPath,str(i)))
else:
print(“待创建文件夹已存在”)
#标签
yLabel=[]
fullNameList=[]
listAllFiles=os.listdir(path)
for fileName in listAllFiles:
fullNameList.append(os.path.join(path,fileName))
#判断是否为文件夹
if os.path.isdir(fullNameList[-1]):
#排除最后一个元素
dirName=fullNameList.pop()
print(dirName+“是一个文件夹”)
#这种表达方式只能用于删除文件
#os.remove(dirName)
#此种表达方式可以用来删除文件夹
shutil.rmtree(dirName)
#跳过此次
continue
#制作对应的标签
yLabel.append(int(returnNumClass(fileName)))
#如果文件提取错误,不返回,只提示
if returnNumClass(fileName)==None:
print(“文件名提取路径失败”+fileName)
continue
#将该文件复制进指定的文件夹中:
else:
#这种方法必须是文件名到文件名
shutil.copyfile(os.path.join(path,fileName), os.path.join(os.path.join(targetPath,returnNumClass(fileName)),fileName))
#这种复制可以是文件名到文件夹名
#shutil.copy(os.path.join(path,fileName), os.path.join(targetPath,returnNumClass(fileName)))
#将y标签转换为独热向量:
#print(to_categorical(yLabel))
yLabel=to_categorical(yLabel)

#返回一个图像迭代器
#遍历fullnameList,读取其中的图片,转换为4维数组:
#以下这种转换方式,将对原先的三维数组,自动新增一个第一维:
allDataSets=[]
for image in fullNameList:
allDataSets.append(readPictureByPath(image))
dataForFlow=np.array(allDataSets)
#(157, 4)
print(yLabel.shape)
#(157, 28, 28, 3)
print(dataForFlow.shape)
#数据持久化:
with h5py.File(“myTextData”, ‘w’) as d:
d[‘x’] =dataForFlow
d[‘label’] = yLabel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颢师傅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值