tensorflow使用ImageDataGenerator中的flow生成数据

import cv2
#正则匹配使用:
import re
import os
#此库用于拷贝,删除,移动,复制以及解压缩
import shutil
import numpy as np
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)
#建立迭代器
dataAll=ImageDataGenerator(validation_split=0.3)
#纯flow方法,特点是需要自定义y标签的类型,比如改成独热向量:
genIteratorForTrain=dataAll.flow(x=dataForFlow,y=yLabel,batch_size=1,subset="training")
#next返回tuple
fig=plt.figure(1,(20,5))
for i in range(4):
    #添加图片:
    a1=fig.add_subplot(1,4,i+1)
    tuple=genIteratorForTrain.next()
    a1.imshow(np.squeeze(tuple[0]).astype(np.int))
    # 取行方向的最大值做标题,argmax返回的也是ndarry
    print(type(np.argmax(tuple[1],1)[0]))
    print(np.argmax(tuple[1], 1)[0])
    # 没有指定中文字体,显示不了中文
    # 独热向量的特点是,其最大值即为标签:
    a1.set_title(u"class"+str(np.argmax(tuple[1],1)[0]))
#画完子图后。plt句柄默认停留在最后一个子图上:
plt.suptitle(u"all")
tuple=genIteratorForTrain.next()
'''
#返回的是四维ndarrary
print(type(tuple[0]))
print(tuple[0].shape)
#返回的默认是一个独热向量
print(tuple[1])
'''
#plt.imshow(np.squeeze(tuple[0]).astype(np.int))
#总图像显示
plt.show()
#print(fullNameList)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

颢师傅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值