栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

ImageNet数据集的处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ImageNet数据集的处理

在下载了这个数据集之后,发现里面的图片并不都是3通道的图片,要先进行处理一下,将单通道图片转化为3通道图片:

#将单通道图像转化为3通道图像
file = r'D:image'
floder = [cla for cla in os.listdir(file)]
total = 0
flodernumber = 0
for cla in floder:
    flodernumber+=1
    print(cla,'   正在处理第',flodernumber,'个文件夹')
    images = os.listdir(os.path.join(file,cla))
    for image_path in images:
        image_path = os.path.join(file,cla,image_path)
        img = Image.open(image_path)
        if len(img.split()) != 3:
            img = cv2.imread(image_path, cv2.IMREAD_COLOR)
            cv2.imwrite(image_path, img)
            total += 1
            print("已处理一张图片")

print('共处理图片数量: ',total)

然后将训练集中的每个类别的图像划分为训练集和验证集:

import os
from shutil import copy
import random
from PIL import Image
import cv2
import numpy as np

def mkfile(file):
    if not os.path.exists(file):
        os.makedirs(file)


file = 'E:BaiduNetdiskDownloadlove'
flower_class = [cla for cla in os.listdir(file) if ".txt" not in cla]

mkfile('E:BaiduNetdiskDownloadlove/train')
for cla in flower_class:
    mkfile('E:BaiduNetdiskDownloadlove/train/'+cla)

mkfile('E:BaiduNetdiskDownloadlove/val')
for cla in flower_class:
    mkfile('E:BaiduNetdiskDownloadlove/val/'+cla)

split_rate = 0.1
for cla in flower_class:
    cla_path = file + '/' + cla + '/'
    images = os.listdir(cla_path)
    num = len(images)
    eval_index = random.sample(images, k=int(num*split_rate))
    for index, image in enumerate(images):
        if image in eval_index:
            image_path = cla_path + image
            new_path = 'E:BaiduNetdiskDownloadlove/val/' + cla
            copy(image_path, new_path)
        else:
            image_path = cla_path + image
            new_path = 'E:BaiduNetdiskDownloadlove/train/' + cla
            copy(image_path, new_path)
        print("r[{}] processing [{}/{}]".format(cla, index+1, num), end="")  # processing bar
    print()

print("processing done!")

这样就可以训练了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269754.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号