前言
在学习深度学习时,需要对数据预处理,笔者之前没有学过python,注释的地方可能有点多,在此分享给大家,希望能够一起进步
批量改变文件名称
工程文件下有一文件夹名为"Raw_Img",其下有’中国沙皮犬’,‘博美犬’,‘史宾格犬’,'红骨猎浣熊犬’四个文件夹,每一个种类的文件夹里有很多张该品种的图片
#coding : utf-8
import os
import numpy as np
from PIL import Image
//因为是两层目录,所以需要两次遍历
def FileRename(DogType,Filepath):
for Dog_Of_Type in DogType:
filename = os.listdir(Filepath + Dog_Of_Type)
for i in filename:
last_name = i.split('_')[4]
os.rename(Filepath + Dog_Of_Type + '/' + i,Filepath + Dog_Of_Type + '/' + last_name)
if __name__ == "__main__":
DogType = ['中国沙皮犬','博美犬','史宾格犬','红骨猎浣熊犬']
FileRename(DogType = DogType,Filepath = 'Raw_Img/')
filename = os.listdir(Filepath + Dog_Of_Type)
**os.listdir()作用** :
返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序
**注意事项1**:
参数必须是相对此.py文件的完全路径,例Raw_Img/中国沙皮犬,不能将 参数只填为Dog_Of_Type
last_name = i.split('_')[4]
split意为分割,参数为制定的分割符并需要用单引号括上
**注意事项1**:
分割后是一个列表,此处之所以取4是因为文件名为==8_8_N_8_圣伯纳犬0==这种格式,此处是想分割出来==圣伯纳犬0==
os.rename(Filepath + Dog_Of_Type + '/' + i,Filepath + Dog_Of_Type + '/' + last_name)
第一个参数为源文件名,第二个参数是修改后的文件名
**注意事项1**:
Dog_Of_Type是通过os.listdir取出来的,是类似圣伯纳犬这种名字,是不带'/',故当作路径时后要加'/'
if __name__ == "__main__":
笔者之前写错为if __main__ == "__main__"
批量改变文件名称
#coding :utf-8
import numpy as np
from PIL import Image
import os
#resize
def FileResize(Output_folder,DogType,FilePath,Width,Heigh):
for type in DogType:
for sub_file in os.listdir(FilePath+type):#subfile is wenjianming
img_open = Image.open(FilePath + type + '/' +sub_file)
con_RGB = img_open.convert('RGB')
Resized_img = con_RGB.resize((Width,Heigh),Image.BILINEAR)
print (sub_file)
Resized_img.save(os.path.join(Output_folder,os.path.basename(sub_file)))
if __name__ == "__main__":
DogType = ['哈士奇', '德国牧羊犬', '拉布拉多', '萨摩耶犬']
FileResize(Output_folder='test/' ,DogType=DogType , FilePath='Raw_Img/',Width=100,Heigh=100)
img_open = Image.open(FilePath + type + '/' +sub_file)
con_RGB = img_open.convert('RGB')
Resized_img = con_RGB.resize((Width,Heigh),Image.BILINEAR)
resize是Image中包含的函数,我们需要先读取图片,之前我没有加convert,pycharm报错mode error至于
为什么要转换RGB模式我不太清楚(如果有热心网友知道,麻烦评论告诉我哈)
Resized_img.save(os.path.join(Output_folder,os.path.basename(sub_file)))
os.path.join作用:将两个路径连接在一起
os.path.basename作用:返回参数路径中最后一级,例如Raw_Img/中国沙皮狗/沙皮狗1.jpg,则返回沙皮狗1.jpg
图片加载及添加图像与标签
#读取图片返回array数组 numpy array
def ReadImage(filename,train_folder):
img = Image.open (train_folder+filename)
return np.array(img)
#图片加载到列表 图像 和 标签
def DataSet(train_folder):
Train_list_img = []
Train_list_label = []
for file_1 in os.listdir(train_folder):
file_img_to_array = ReadImage(filename=file_1,train_folder=train_folder)
#添加图片数组到主list里
Train_list_img.append(file_img_to_array)
# 添加标签数组到主list里
Train_list_label.append(int(file_1.split('_')[0]))
Train_list_img = np.array(Train_list_img) #ReadImage返回是numpy数组但是,append后的数组还不是,所以要转化
Train_list_label = np.array(Train_list_label)