因为最近在学习深度学习,会遇到处理不同数据集的问题,简单总结了几个常用的脚本,单纯记录以供后续学习.

一.图片重命名


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

class ImageRename():
    def __init__(self):
        self.path = '/home/XXX/list/data/train/'

    def rename(self):
        filelist = os.listdir(self.path)
        total_num = len(filelist)

        i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item)
                dst = os.path.join(os.path.abspath(self.path), 'Fake' + format(str(i), '0>4s') + '.jpg')
                os.rename(src, dst)
                print 'converting %s to %s ...' % (src, dst)
                i = i + 1
        print 'total %d to rename & converted %d jpgs' % (total_num, i)

if __name__ == '__main__':
    newname = ImageRename()
    newname.rename()


二.图片重构尺寸


#-*- coding: utf-8 -*-
import cv2
import os


# 按指定图像大小调整尺寸
def resize_image(image, height=100, width=100):
    top, bottom, left, right = (0, 0, 0, 0)

    # 获取图片尺寸
    h, w, _ = image.shape

    # 对于长宽不等的图片,找到最长的一边
    longest_edge = max(h, w)

    # 计算短边需要增加多少像素宽度才能与长边等长(相当于padding,长边的padding为0,短边才会有padding)
    if h < longest_edge:
        dh = longest_edge - h
        top = dh // 2
        bottom = dh - top
    elif w < longest_edge:
        dw = longest_edge - w
        left = dw // 2
        right = dw - left
    else:
        pass  # pass是空语句,是为了保持程序结构的完整性。pass不做任何事情,一般用做占位语句。

    # RGB颜色
    BLACK = [0, 0, 0]
    # 给图片增加padding,使图片长、宽相等
    # top, bottom, left, right分别是各个边界的宽度,cv2.BORDER_CONSTANT是一种border type,表示用相同的颜色填充
    constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)
    # 调整图像大小并返回图像,目的是减少计算量和内存占用,提升训练速度
    return cv2.resize(constant, (height, width))


def read__image(path_name):
    num = 0
    for dir_image in os.listdir(path_name):  # os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
        full_path = os.path.abspath(os.path.join(path_name, dir_image))

        if os.path.isdir(full_path):  # 如果是文件夹,继续递归调用
            read__image(full_path)
        else:  # 如果是文件了
            if dir_image.endswith('.jpg'):
                image = cv2.imread(full_path)
                image = resize_image(image)
                # 将尺寸调整好的图片保存起来
                image_name = '%s%d.jpg' % ('resize_image', num)  # 注意这里图片名一定要加上扩展名,否则后面imwrite的时候会报错
                cv2.imwrite(image_name, image) #第一个参数为要保存的文件名,第二个参数为要保存的图
                num = num + 1


if __name__ == '__main__':
    read__image('/home/XXX/list/data/train/')


三.生成list清单(图片名+类名)


# -*- coding: UTF-8 -*-
import os
import re

def createFileList(images_path, txt_save_path):
 #打开图片列表清单txt文件
 fw = open(txt_save_path,"w")
 #查看图片目录下的文件,相当于shell指令ls
 images_name = os.listdir(images_path)
 #遍历所有文件名
 for eachname in images_name:
     #正则表达式这里可以根据情况进行更改,如果多类记得仿照下面定义相关变量
     #正则表达式规则:找以real开头,紧跟0到49个数字,并以jpg结尾的图片文件
     pattern_ture = r'(^real\d{0000,49}.jpg$)'
     #正则表达式规则:找以fake开头,紧跟0到49个数字,以jpg结尾的图片文件
     pattern_false = r'(^fake\d{0000,49}.jpg$)'#更改变量名需要定义
     #正则表达式匹配
     ture_name = re.search(pattern_ture, eachname)
     false_name = re.search(pattern_false, eachname)
     #按照规则将内容写入txt文件中
     if ture_name != None:
      fw.write(ture_name.group(0) + ' 1\n')
     if false_name != None:
      fw.write(false_name.group(0) + ' 0\n')#如果分为多类,多加几个if便是。当然相关变量也要记得定义。
 #打印成功信息
 print "生成txt文件成功"
 #关闭fw
 fw.close()

# 下面是相关变量定义的路径
if __name__ == '__main__':
    # caffe_root目录
    root = '/home/XXX/list/'
    # 图片存放目录
    images_path = root + 'data/train/'
    # 生成的图片列表清单txt文件名
    txt_name = 'train.txt'
    # 生成的图片列表清单txt文件的保存目录
    txt_save_path = root + txt_name
    # 生成txt文件
    createFileList(images_path, txt_save_path)


四.计算数据集均值


#-*- coding: utf-8 -*-
import os
import numpy as np
from scipy.misc import imread

filepath = '/home/XXX/list/data/train/'  # 数据集目录
pathDir = os.listdir(filepath)

R_channel = 0
G_channel = 0
B_channel = 0
for idx in xrange(len(pathDir)):
    filename = pathDir[idx]
    img = imread(os.path.join(filepath, filename))
    R_channel = R_channel + np.sum(img[:, :, 0])
    G_channel = G_channel + np.sum(img[:, :, 1])
    B_channel = B_channel + np.sum(img[:, :, 2])

num = len(pathDir) * 202 * 202  # 这里(202,202)是每幅图片的大小,所有图片尺寸都一样
R_mean = R_channel / num
G_mean = G_channel / num
B_mean = B_channel / num

print("R_mean is %f, G_mean is %f, B_mean is %f" % (R_mean, G_mean, B_mean))