使用Keras和卷积神经网络搭建图片分类系统

版权声明:(欢迎转载,转载请注明出处。欢迎沟通交流:[email protected]) https://blog.csdn.net/Yasin0/article/details/82145323

以猫种类的识别为例,使用Keras和卷积神经网络搭建图片分类系统

在正式写代码之前需要强调的是该项目的运行环境(不同的版本运行时可能会出现一些莫名其妙的错误):

  1. Pycharm【anaconda(python3.6)】
  2. Keras2.1.2
  3. TensorFlow 1.3.0
  4. Pillow5
  5. H5py2.7.0
  6. Numpy 1.13.3

1 数据预处理

由于我们收集的图片格式、尺寸、名称都不统一,所以我们首先对我们的数据进行预处理,然后再传给神经网络。

# coding=utf-8
_author_ = 'Yasin'
_date_ = '2018-08-27 17:03'

import os
from PIL import Image

# 统一图片类型,对图片格式、名称进行处理
def renamesJPG(filepath, kind):    # 两参数分别为:文件路径及我们设置猫的种类
    images = os.listdir(filepath)  # 遍历指定文件夹,并将所有文件存入images变量中
    for name in images:            # 重命名后的格式为:种类_原名称.jpg
        os.rename(filepath+name, filepath+kind+'_'+name.split('.')[0]+'.jpg')
# 调用三次函数,分别对不同种类的猫进行处理
renamesJPG('C:\\Users\\Administrator\\Desktop\\cat_kinds\\布偶猫\\','0')
renamesJPG('C:\\Users\\Administrator\\Desktop\\cat_kinds\\孟买猫\\','1')
renamesJPG('C:\\Users\\Administrator\\Desktop\\cat_kinds\\暹罗猫\\','2')
renamesJPG('C:\\Users\\Administrator\\Desktop\\cat_kinds\\英国短毛猫/','3')


# 该函数可以将图片裁剪成指定大小
def reshape(filepath ,outdir,width=100,height=100):
    images = os.listdir(filepath)
    for imgs in images:
        img = Image.open(filepath+imgs)
        try:
            new_img = img.resize((width, height), Image.BILINEAR)
            new_img.save(os.path.join(outdir, os.path.basename(imgs))) # 注意这里是imgs而不是img!!!
        except Exception as e:
            print(e)
# 调用函数,指定传入文件和图片修改后的存储路径
reshape("C:\\Users\\Administrator\\Desktop\\cat_kinds\\布偶猫\\","C:\\Users\\Administrator\\Desktop\\cat_kinds\\buou")
reshape("C:\\Users\\Administrator\\Desktop\\cat_kinds\\孟买猫\\","C:\\Users\\Administrator\\Desktop\\cat_kinds\\mengmai")
reshape("C:\\Users\\Administrator\\Desktop\\cat_kinds\\暹罗猫\\","C:\\Users\\Administrator\\Desktop\\cat_kinds\\xianluo")
reshape("C:\\Users\\Administrator\\Desktop\\cat_kinds\\英国短毛猫\\","C:\\Users\\Administrator\\Desktop\\cat_kinds\\duanmao")

这里注明:0_xxx.jpg 代表布偶猫、1_xxx.jpg 代表孟买猫、2_xxx.jpg 代表暹罗猫、3_xxx.jpg 代表英国短毛猫。

2 训练模型

 

猜你喜欢

转载自blog.csdn.net/Yasin0/article/details/82145323
今日推荐