利用keras进行图像识别——训练自己的数据集

本文介绍如何利用Keras进行图像识别,包括数据预处理如图像增强、裁剪、重命名,神经网络训练涉及数据转换、标签编码与归一化,以及模型建立与权重保存。在预测阶段,详细说明了模型加载与应用过程,同时针对训练问题给出了可能的原因和解决建议。
摘要由CSDN通过智能技术生成

1、预处理图片数据集

(1)增强数据集
如果图片数量少的话,可以通过keras.preprocessing.image中的ImageDataGenerator函数进行数据增强,即通过旋转,翻转等操作增加图片的数量。(训练集和测试集都要)

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from PIL import Image
import os

datagen = ImageDataGenerator(
        rotation_range=0.2,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')


def generator(filepath):
    images = os.listdir(filepath)  # 把该路径下所有图片都读取
    for name in images:
    #读取每一张图片,并转化成矩阵
        img=Image.open('picture/test/horse/'+name)
        x=img_to_array(img)
        x=x.reshape((1,)+x.shape)
        i = 0
        for batch in datagen.flow(x,
                                  batch_size=1,
                                  save_to_dir='test_augmentation/horse',#生成后的图像保存路径
                                  save_prefix='3',  #生成图片名称的前缀(用于作为数据的标签)
                                  save_format='jpg'):   #图片保存的格式
            i += 1
            if i > 20: #这个20指出要扩增多少个数据
                break  # otherwise the generator would loop indefinitely

generator('picture/test/horse')

(2)将图片裁剪成统一的形状,以便于输入到神经网络中
os.listdir(’ 文件夹名称’)函数用于遍历文件夹中文件的名称

def convertjpg(jpgfile,outdir,width=100,height=100):
    #导入图片名称为jpgfile,输出到outdir文件中
    img=Image.open('test_augmentation/'+jpgfile)
    try:
        #将图片resize成100*100的大小
        new_jpg=img.resize((width,height),Image.BILINEAR)
        #保存到路径outdir下
        new_jpg.save(os.path.join(outdir,os.path.basename(jpgfile)))
    except Exception as e:
        print(e)

for jpgfile in os.listdir('test_augmentation'):
    #遍历文件中的文件名称
    print(jpgfile)
    convertjpg(jpgfile,'test1')

(3)改变图片的名称
通过os.rename(‘旧名字’,‘新名字’)

  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值