背景:在深度学习时候,通常需要批量处理大量的图片,一般几千张,图像不够时还需要进行数据增强,因此需要批量处理图像数据。
【1】批量加载文件夹里面的数据
import os
import cv2
#批量处理图像,改名,
def read__image(open_path,save_path):
# os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
for dir_image in os.listdir(open_path):
#打开当前运行脚本的绝对路,就是真个文件里面所有文件的路径
full_path = os.path.abspath(os.path.join(open_path,dir_image))
#选择后缀为.jpg格式的文件
num=0
if dir_image.endswith('.jpg'):
image = cv2.imread(full_path)
#分离文件路径和文件名
(filepath, filename) = os.path.split(full_path)
#分离文件名和后缀 去掉后坠取文件名。就是去掉.jpg,只要前面的图片名
nameall = os.path.splitext(filename)[0]
'''
如果需要进一步分割图片名,可以用,name=str(nameall).splite('-')[2:5]进行切分字符串
'''
#图像批量处理后保存
agutationimg=DateArgutation(image)
for index in range(len(agutationimg)):
image_path = save_path+'%s_%s.jpg' % (nameall,str(index)) # 注意这里图片名一定要加上扩展名,否则后面imwrite的时候会报错
cv2.imwrite(image_path,agutationimg[index])
#直接改名保存
#num+=1
#image_path = save_path+'%s_%s.jpg' % (nameall,str(num)) # 注意这里图片名一定要加上扩展名,否则后面imwrite的时候会报错
#cv2.imwrite(image_path,agutationimg[index])
【2】图像数据增强
#输入一张图片,产生旋转,缩放,长宽调整等形式
def DateArgutation(images):
img=images
agutationimg=[]
imgInfo=img.shape
height=imgInfo[0]
width=imgInfo[1]
#图像翻转0 90 270
flipped1 = cv2.flip(img, -1)
agutationimg.append(flipped1)
flipped2 = cv2.flip(img, 1)
agutationimg.append(flipped2)
flipped3 = cv2.flip(img, 0)
agutationimg.append(flipped3)
#等比例缩放
height1=int(height*0.8)
width1=int(width*0.8)
resImg1=cv2.resize(img,(width1,height1))
agutationimg.append(resImg1)
height2=int(height*3)
width2=int(width*3)
resImg2=cv2.resize(img,(width2,height2))
agutationimg.append(resImg2)
print('success!')
return agutationimg
【3】批量读入数据放置在列表中
#载入图片,处理后保存到一个列表中
def GetImg(open_path):
patch=[]
for dir_image in os.listdir(open_path): # os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
full_path = os.path.abspath(os.path.join(open_path,dir_image))
if dir_image.endswith('.jpg'):
image = cv2.imread(full_path)
resImg=cv2.resize(image,(227,227))
patch.append(resImg)
return patch