旋转、裁剪图片增强数据集,制作文本标签,批量修改图片名

 发现这个用的比较多,总结整理出来供大伙使用,若转载请注明出处
1、旋转、裁剪图片增强数据集
"""
Created on Tue Jul 10 10:24:35 2018

@author: baozi
"""

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


def alter(path,object):
    s = os.listdir('E:/000/0deep/9/G9Jeans')
    count = 1
    
    datagen = ImageDataGenerator(
        rotation_range=360,
        #zoom_range=1.3,
        horizontal_flip=True,
        fill_mode='reflect')
    
    for i in s:
        document = os.path.join(path,i)
        img = Image.open(document)
        
        img=img.resize((128,128))
        x = img_to_array(img)  # this is a Numpy array with shape (3, 128, 128)
        x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, 3, 128, 128)
        
        # the .flow() command below generates batches of randomly transformed images
        # and saves the results to the `preview/` directory
        
        i = 0
        for batch in datagen.flow(x, 
                                  batch_size=1,
                                  save_to_dir='E:/000/0deep/9/G9',  
                                  save_prefix='G9Jeans', 
                                  save_format='jpg'):
            i += 1
            if i > 20:
                break  # otherwise the generator would loop indefinitely
        
        
       
        count = count + 1

alter('E:/000/0deep/9/G9Jeans','E:/000/0deep/9/G9')

2、制作图片对应的标签

import glob
import os
IMG_PATH = 'E:/000/0deep/9test1/G' 
img_paths = glob.glob(os.path.join(IMG_PATH, '*.jpg'))

img_paths.sort()

image_mask_pair = zip(img_paths)
image_mask_pair = list(image_mask_pair)
file=open('E:/000/0deep/9test1/train.txt','w') 


for i in img_paths:
    temp = i
    a=[]
    for j in temp:
        a.append(j)
    file.write(temp +' '+a[23]+'\n')#a[23]的目的是取对应图片名称中的某个字符作为标签号

file.close()

3、批量修改图片名

import os

class BatchRename():
    '''
    批量重命名文件夹中的图片文件

    '''
    def __init__(self):
        self.path = 'E:/000/0deep/9/G/G8'

    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), 'G8_'+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 jpg' % (total_num, i))

if __name__ == '__main__':
    demo = BatchRename()
    demo.rename()

4、随机在数据集里择取一定数量文件(参考)

import os, random, shutil
def copyFile(fileDir):
    # 1
	pathDir = os.listdir(fileDir)
 
    # 2
	sample = random.sample(pathDir, 400)
	print (sample)
	
	# 3
	for name in sample:
		shutil.copyfile(fileDir+name, tarDir+name)
if __name__ == '__main__':
	fileDir = "E:/000/0deep/0train/G/"
	tarDir = 'E:/000/0deep/0val/G/'
	copyFile(fileDir)

5、批量resize图片

import cv2
import numpy as np
import os
fullfilename=[]
filepath="E:/000/0deep/0deep"
filepath1="E:/000/0deep/1deep"
for filename in os.listdir(filepath):
    print (filename)
    print (os.path.join(filepath,filename))
    filelist=os.path.join(filepath,filename)
    fullfilename.append(filelist)
i=1
for imagename in fullfilename:
    img=cv2.imread(imagename)
    img=cv2.resize(img,(128,128))
    resizename=str(i)+'.jpg'
    isExists = os.path.exists(filepath1)
    if not isExists:
        os.makedirs(filepath1)
        print('mkdir resizename accomploshed')
    savename=filepath1+'/'+resizename
    cv2.imwrite(savename,img)
    print('{} is resized'.format(savename))
    i=i+1

# =============================================================================
# from PIL import Image
# import os.path
# import glob  #该方法返回所有匹配的文件路径列表(list)
# Datadir = "E:/000/0deep/0deep/*.jpg"
# savedir = "E:/000/0deep/1deep"
#  
#  
# def convertjpg(jpgfile,outdir,width=128,height=128):
#     img=Image.open(jpgfile)
#     new_img=img.resize((width,height),Image.BILINEAR)
#     new_img.save(os.path.join(outdir,os.path.basename(jpgfile)))
#     
# for jpgfile in glob.glob(Datadir):
#     convertjpg(jpgfile,savedir)
# =============================================================================

6、MATLAB生成图片后裁剪掉白边框

import os
#读取path路径下的 jpg文件
def getAllImages(path):
    #f.endswith()  限制文件类型
    #f.endswith('.jpg')|f.endswith('.png')  改成这句可以读取jpg/png格式的文件
    #注意 返回的是绝对路径
   return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]

import pylab as plb
import PIL.Image as Image
#循环读图
for path in getAllImages(r'E:/000/0deep/0deep'):
    #读图
    img = Image.open(path)
    #显示
   #plb.imshow(img)
# =============================================================================
#     #设置裁剪点(4个)
#     corner = plb.ginput(4)
#     #顺时针取点求解
#     left = (corner[0][0] + corner[3][0])/2
#     top = (corner[1][1] + corner[0][1])/2
#     reight = (corner[1][0] + corner[2][0])/2
#     under = (corner[3][1] + corner[2][1])/2
#     #print left,top,reight,under
# =============================================================================
    #box = [left,top,reight,under]
    #box中的数必须是 int 否则会报错
    box = [int(155),int(70),int(1085),int(800)]#这是确定四条边,对应自己的情况先做修改
    #裁剪
    img2 = img.crop(box)
    #显示裁剪后的效果
    #plb.imshow(img2)
    #plb.show()
    #储存为原来路径覆盖原文件
    img2.save(path)
plb.show()

觉得有用有帮助的给个赞吧~~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值