python3.6深度学习图片集处理项目源代码(为cnn等准备图片集合,批量生成、删除、改名、旋转、调整大小)

为了方便深度学习,训练模型编写该代码,图片批量生成、删除、改名、旋转、调整大小、排序、计算图片数量,欢迎大家补充修改。

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/3/4 13:07
# @File    : imagespro.py
# @Software: PyCharm

import os
import os.path
from PIL import Image
from skimage import transform,data
import shutil #shutil是一个高级文件操作的包,实现了文件及文件集合复制与删除的功能

# 批量处理文件夹中图片
class imgPro():
    '''
     批量重命名文件夹中的图片文件

     '''

    def __init__(self):
        self.path = r'C:/Users/images'

    #修改文件名(从0开始排序)
    def rename(self):
        print('修改文件名(从0开始排序)')
        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), str(i) + '.jpg')
                try:
                    os.rename(src, dst)
                    print ('converting %s to %s ...' % (src, dst))
                    i = i + 1
                except:
                    continue
        print ('total %d to rename & converted %d jpgs' % (total_num, i))

    # 每张图片每旋转30度,生成一张图片
    def rotate(self):
        print('每张图片每旋转30度,生成一张图片')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        # i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item)
                for angle in range(30,360,30):
                    dst = os.path.join(os.path.abspath(self.path), str(item)[:-4] + '_' + str(angle) + '.jpg')
                    try:
                        img = Image.open(src)
                        img = img.rotate(angle)
                        img.save(dst)
                        print ('converting %s to %s ...' % (src, dst))
                        i = i + 1
                    except Exception as e:
                        print("rotate error = ",e)
                        continue
                    angle = angle + 30
        print ('total %d to rename & converted %d jpgs' % (total_num, i))

    # 图像缩放
    def resize(self,w,h):
        print('图像缩放')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item) # 路径+文件名
                # for angle in range(30,360,30):
                dst = os.path.join(os.path.abspath(self.path), str(item)[:-4] + '_resize' + '.jpg')
                try:
                    img = Image.open(src)
                    img = img.resize((w, h))
                    img.save(dst)
                    print ('resize %s to %s ...' % (src, dst))
                    i = i + 1
                except Exception as e:
                    print("resize error = ",e)
                    continue
        print ('total %d to resize & converted %d jpgs' % (total_num, i))


    # 图像缩放后删除原图
    def resize(self,w,h):
        print('图像缩放后删除原图')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item) # 路径+文件名
                # for angle in range(30,360,30):
                dst = os.path.join(os.path.abspath(self.path), str(item)[:-4] + '_resize' + '.jpg')
                try:
                    img = Image.open(src)
                    new = img.resize((w, h))
                    new.save(dst)
                    img.close()
                    print ('resize %s to %s ...' % (src, dst))
                    i = i + 1
                except Exception as e:
                    print("resize error = ",e)
                    continue
                    # angle = angle + 30
        print ('total %d to resize & converted %d jpgs' % (total_num, i))

    # 获取图片总数
    def getsum(self):
        print('获取图片总数')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        i = 0
        for item in filelist:
            if (item.endswith('.jpg') or item.endswith('.png')):
                i = i + 1
        return i

    # 删除文件夹下所有文件
    # def delallfile(self):
    #     print('删除文件夹下所有文件')
    #     filelist = os.listdir(self.path)
    #     total_num = len(filelist)
    #     if total_num == 0:
    #         print("not find files!")
    #         return
    #     for i in filelist:
    #         src = os.path.join(self.path, i) # 取文件绝对路径
    #         if os.path.isfile(src):
    #             os.remove(src)
    #         else:
    #             delallfile(src)

    # 删除文件夹下所有文件(包括文件夹),保留该文件夹
    def delallfile1(self):
        print('删除文件夹下所有文件(包括文件夹),保留该文件夹')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        for i in filelist:
            src = os.path.join(self.path, i) # 取文件绝对路径
            if os.path.isfile(src):
                os.remove(src)
            else:
                shutil.rmtree(src) # 删除文件夹和文件夹里面的所有文件

    # 删除文件夹下所有jpg图片
    def delalljpg(self):
        print('删除文件夹下所有jpg图片')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item) # 路径+文件名
                if os.path.isfile(src):
                    os.remove(src)

    # 删除文件夹下w*h以外的jpg图片
    def delallwhjpg(self,w,h):
        print('删除文件夹下w*h以外的jpg图片')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        if total_num == 0:
            print("not find files!")
            return
        i = 0
        for item in filelist:
            if item.endswith('.jpg'):
                src = os.path.join(os.path.abspath(self.path), item) # 路径+文件名
                if os.path.isfile(src):
                    im = Image.open(src)
                    wx, wh = im.size
                    im.close()
                    if (wx != w) and (wh != h):
                        os.remove(src)

    # 修改文件后缀为.jpg
    def setpostfix(self):
        print('修改文件后缀')
        filelist = os.listdir(self.path)
        total_num = len(filelist)
        i = 0
        for item in filelist:
            portion = os.path.splitext(item)  # 将文件名拆成名字和后缀
            new = portion[0] + ".jpg"
            os.rename(item, new)  # 修改
        return i

    # 批量水平翻转图片transpose
    def transpose(self):
        print('批量水平翻转图片transpose')
        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), 'transpose' + '.jpg')
                try:
                    img = Image.open(src)
                    img = img.transpose(Image.FLIP_LEFT_RIGHT)
                    img.save(dst)
                except:
                    continue
        print ('transpose worked')

if __name__ == '__main__':
    demo = imgPro()
    demo.path = r'C:/Users/images'
    # demo.rename() # 从0开始排序命名
    # demo.resize(300,300) # 缩放 300*300
    # demo.delalljpg() # 删除全部jpg图片
    # demo.delallfile1()  # 删除全部文件


你可能感兴趣的:(python,深度学习,opencv,源代码,图片)