目录
- 缩放一个文件夹中的所有图片
- 使用一个阈值将文件夹中的标签图变为二值图
- 给标签图重命名
- 给原图与标签图都重命名并保存
- 取出数据集的图片、对应label图以及对应的名字分别放置于list中
- 同时把img与对应的mask resize 到统一尺寸并保存
- 用于把一个数据集划分为训练集、验证集、测试集存起来(按比例随机)
- 语义分割数据集数据增强
- 合并label图片
- 使用PIL库判断图片尺寸并旋转
image与label
缩放一个文件夹中的所有图片
import numpy as np
import glob
import os
from PIL import Image
def img_resize(image_path,new_image_path,new_size):
imgs = sorted(glob.glob(image_path + "*.jpg") )
print(len(imgs))
for img in imgs:
image = Image.open(img)
image=image.resize(new_size,Image.BILINEAR)
print(image.size)
img_name=os.path.split(img)[1]
print(img_name)
image.save(new_image_path+img_name)
使用一个阈值将文件夹中的标签图变为二值图
import numpy as np
import glob
import os
from PIL import Image
def annotation_prepare(ann_path,new_ann_path,threshold,new_size=False,max_value=1,samll_value=0):
anns = sorted(glob.glob(ann_path + "*.jpg"))
for ann in anns:
ann_name = os.path.split(ann)[1]
print(ann_name)
ann = Image.open(ann)
ann = ann.convert("L")
if (new_size!=False):
w, h = new_size
ann=ann.resize((w,h),Image.BILINEAR)
else:
w,h=ann.size
ann=np.array(ann)
new_ann=(ann>threshold)*max_value
new_ann=new_ann+(ann>=threshold)*samll_value
new_ann = new_ann.astype(np.uint8)
new_ann = Image.fromarray(new_ann)
new_ann.save(new_ann_path+ann_name)
给标签图重命名
def annNameChange(img_path,ann_path,new_img_path,new_ann_path):
imgs = sorted(glob.glob(img_path+"*.jpg"))
for img in imgs:
img_save=Image.open(img)
img = os.path.split(img)[1]
img_name=os.path.splitext(img)[0]
print(img_name)
ann_list=glob.glob(ann_path+img_name+"[_.]*")
print(len(ann_list))
i=1
for ann in ann_list:
ann = Image.open(ann)
new_img_name=new_img_path+'/'+img_name+'.jpg'
new_ann_name=new_ann_path+'/'+img_name+"_0{}.jpg".format(i)
print(new_ann_name)
i =i+1
img_save.save(new_img_name)
ann.save(new_ann_name)
给原图与标签图都重命名并保存
def annNameChange_new(img_path,ann_path,new_img_path,new_ann_path):
imgs = sorted(glob.glob(img_path+"*.jpg"))
i_name=0
for img in imgs:
i_name = i_name+1
img_save=Image.open(img)
img = os.path.split(img)[1]
img_name=os.path.splitext(img)[0]
print(img_name)
ann_list=glob.glob(ann_path+img_name+"[_.]*")
print(len(ann_list))
i=1
for ann in ann_list:
ann = Image.open(ann)
new_img_name=new_img_path+'/{}.jpg'.format(i_name)
new_ann_name=new_ann_path+'/{}_0{}.jpg'.format(i_name,i)
print(new_img_path)
print(new_ann_name)
i =i+1
img_save.save(new_img_name)
ann.save(new_ann_name)
取出数据集的图片、对应label图以及对应的名字分别放置于list中
def get_image(img_path,ann_path):
img_list = glob.glob(img_path+r'\*')
mask_list=glob.glob(ann_path+r'\*')
print(len(img_list))
print('mask_list',len(mask_list))
imgs = []
names=[]
masks=[]
for img_path in img_list:
names.append(os.path.basename(img_path))
img=Image.open(img_path)
imgs.append(img)
for mask_path in mask_list:
mask = Image.open(mask_path)
masks.append(mask)
return names,imgs,masks
同时把img与对应的mask resize 到统一尺寸并保存
"""用来同时把img与对应的mask resize 到统一尺寸"""
def resize_image(args):
img_names,imgs=get_image(args.imgs_dir)
mask_names,masks=get_image(args.masks_dir)
assert len(imgs)==len(masks), 'len(imgs_dir) and len(masks_dir) must be the same'
for i in range(len(imgs)):
re_img = imgs[i].resize((args.w, args.h), Image.BICUBIC)
re_mask= masks[i].resize((args.w, args.h), Image.BICUBIC)
re_label_1,re_label_255=make_label(re_mask,args.Threshold)
re_img.save(os.path.join(args.re_img_dir, img_names[i]))
re_label_1.save(os.path.join(args.re_mask_dir_new, mask_names[i]))
re_label_255.save(os.path.join(args.re_mask_dir, mask_names[i]))
def make_label(mask,Threshold):
mask = mask.convert("L")
mask = np.array(mask).astype(int)
label_1 = (mask > Threshold) *1
label_255=label_1*255
label_1 = label_1.astype(np.uint8)
label_255 = label_255.astype(np.uint8)
label_1 = Image.fromarray(label_1)
label_255= Image.fromarray(label_255)
return label_1,label_255
用于把一个数据集划分为训练集、验证集、测试集存起来(按比例随机)
import random
def split_dataset(img_path,ann_path,train_dir,val_dir,test_dir=None,is_split_test=False):
img_names,imgs,masks=get_image(img_path,ann_path)
train_imgs_dir=os.path.join(train_dir,'imgs')
train_anns_dir = os.path.join(train_dir,'anns')
val_imgs_dir=os.path.join(val_dir,'imgs')
val_anns_dir = os.path.join(val_dir,'anns')
mkdir(train_imgs_dir)
mkdir(train_anns_dir)
mkdir(val_imgs_dir)
mkdir(val_anns_dir)
if test_dir:
test_imgs_dir = os.path.join(train_dir, 'imgs')
test_anns_dir = os.path.join(train_dir, 'anns')
mkdir(test_imgs_dir)
mkdir(test_anns_dir)
assert len(masks) == len(imgs), 'len(imgs_dir) and len(masks_dir) must be the same'
indexs = [i for i in range(len(imgs))]
print(len(imgs))
random.shuffle(indexs)
print(indexs)
print(type(indexs))
if is_split_test:
cnt_train = int(round(len(imgs) * 0.6, 0))
print(cnt_train)
cnt_val = int(round(len(imgs) * 0.2, 0))
print(cnt_val)
cnt_test = int(round(len(imgs) * 0.2, 0))
train_indexs = indexs[0:cnt_train]
print(train_indexs)
val_indexs = indexs[cnt_train:(cnt_train + cnt_val):1]
test_indexs = indexs[(cnt_train + cnt_val):]
else:
cnt_train = int(round(len(imgs) * 0.7, 0))
cnt_val = int(round(len(imgs) * 0.3, 0))
train_indexs = indexs[0:cnt_train]
print(train_indexs)
val_indexs = indexs[cnt_train:]
for i in train_indexs:
imgs[i].save(os.path.join(train_imgs_dir, img_names[i]))
masks[i].save(os.path.join(train_anns_dir,img_names[i]))
for i in val_indexs:
imgs[i].save(os.path.join(val_imgs_dir,img_names[i]))
masks[i].save(os.path.join(val_anns_dir, img_names[i]))
if is_split_test:
for i in test_indexs:
imgs[i].save(os.path.join(test_imgs_dir, img_names[i]))
masks[i].save(os.path.join(test_anns_dir, img_names[i]))
def mkdir(path):
path = path.strip()
path = path.rstrip("\\")
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
return True
else:
return False
语义分割数据集数据增强
import Augmentor
from glob import glob
import os
import random
from PIL import Image
import cv2
import numpy as np
def augmentor(image_path,label_path,num):
p = Augmentor.Pipeline(image_path)
p.ground_truth(label_path)
p.rotate(probability=0.5, max_left_rotation=10, max_right_rotation=10)
p.flip_left_right(probability=0.5)
p.zoom_random(probability=0.5, percentage_area=0.8)
p.flip_top_bottom(probability=0.5)
p.rotate_random_90(probability=0.5)
p.random_distortion(probability=0.2, grid_width=4, grid_height=4, magnitude=8)
p.sample(num)
合并label图片
'''对于一个Groundtruth中把每一个对象都单独标注到一个图片中。该函数用于合并mask到一张图片中'''
import glob
import os
import numpy as np
from PIL import Image
def merge(imgpath_list):
mask=Image.open(imgpath_list[0])
mask = mask.convert('L')
mask=np.array(mask)
for _mask in imgpath_list[1:]:
_mask = Image.open(_mask)
_mask = _mask.convert('L')
_mask = np.array(_mask)
mask = np.maximum(mask, _mask)
mask=Image.fromarray(mask)
return mask
def merge_mask(img_path,ann_path,new_annpath):
img_list = glob.glob(img_path+'\*')
print(len(img_list))
for img_path in img_list:
name=os.path.basename(img_path)
ann_img=os.path.join(ann_path,name)
mask_list=glob.glob(ann_img[0:-4]+'*')
print(name,mask_list)
if(len(mask_list)>1):
mask=merge(mask_list)
else:
mask=Image.open(mask_list[0])
mask.save(os.path.join(new_annpath,name))
使用PIL库判断图片尺寸并旋转
img=Image.open(img_path)
h,w=img.size
if h>w:
img=img.transpose(Image.ROTATE_90)
import os
from PIL import Image
cascade_mask_rcnn_water_train_imgs_dir=r'F:\Dataset\train\color_img'
cascade_mask_rcnn_water_train_marks_dir=r'F:\Jun\Dataset\train\binary_img'
cascade_mask_rcnn_water_val_imgs_dir=r'F:\Jun\Dataset\val\color_img_all'
cascade_mask_rcnn_water_val_marks_dir=r'F:\Jun\Dataset\val\binary_img_all'
def rotate_image(img_path,save_path):
imgs_path = os.listdir(img_path)
for r in imgs_path:
img=os.path.join(img_path,r)
img=Image.open(img)
w, h = img.size
if w>h:
img = img.transpose(Image.ROTATE_90)
img.save(os.path.join(save_path,r))