1.概要
本代码是基于python3.6和百度飞桨paddlepaddle2.0模块实现,现在人工智能的模块很很多,主流的有tf,pytorch,百度飞桨等,虽然百度飞桨的流行程度不如tf和pytorch,但是百度飞桨毕竟是国人开发出来的,而且在百度的aistuio上有一些免费的课程,大家可以去看一下https://aistudio.baidu.com/aistudio/course,个人觉得挺不错的,废话不多说直接上代码
2.实现
下载模块
pip install paddlepaddle
首先是图片预处理部分,首先大家需要自己创建一个数据集,将不同的分类的图片保存到不同的文件夹中,例如people文件夹下放人物图,需要出注意的一点就是,文件路径中不能带有中文,不然程序会找不到文件,会报错。图片可以通过爬虫爬取,或者可以直接用我的https://github.com/weita1013/Photo_classification,其中分类文件夹的名称就是图片的类别,数据集的数量最好不要太少,一个分类200张左右就可以基本实现功能。
# 数据预处理
import os
import shutil
name_dict = {
'people': 0, 'animal': 1, 'landscape': 2,
'vehicle': 3, 'food': 4}
data_root_path = r'dataset/photo/'
# 测试集路径
test_file_path = data_root_path + 'test.list'
# 训练集文件路径
train_file_path = data_root_path + 'train.list'
# 样本汇总文件
readme_file = data_root_path + 'readme.json'
# 记录每个类别多少张训练图片、测试图片
name_data_list = {
}
def save_train_test_file(path, name):
if name not in name_data_list:
img_list = []
img_list.append(path)
name_data_list[name] = img_list
else:
name_data_list[name].append(path)
# 遍历目录、将图片路径存入字典,再由字典写入文件
dirs = os.listdir(data_root_path)
for d in dirs:
full_path = data_root_path + d
if os.path.isdir(full_path):
imgs = os.listdir(full_path)
for img in imgs:
save_train_test_file(full_path + '/' + img, d)
else:
pass
# 图片分配到测试集和训练集中,
with open(test_file_path, 'w')as f:
pass
with open(train_file_path, 'w')as f:
pass
# 遍历字段,分配测试集
for name, img_list in name_data_list.items():
i = 0
num = len(img_list)
print('{}:{}张'.format(name, num))
for img in img_list:
if i % 10 == 0:
with open(test_file_path, 'a')as f:
line = '%s\t%d\n' %