由于本人在使用yolov3模型跑训练时发现自己标注的图像样本数量实在太少,又懒得再去标注图像,因为标注图像真的是一件超级考验眼睛的事情::>_<:: 故写下了这个数据扩充脚本,将已经标注好的图片进行随机变换,并将该图片对应的txt文件利用线性代数的方法做相应改变,这样标注一张图片就相当于有了好几张图片啦~
代码中有关图像旋转原理详解的部分参考了下面链接中的内容:
https://blog.csdn.net/liyuan02/article/details/6750828
首先直接贴出源码
# -*- coding:utf-8 -*-
import numpy as np
import os
import cv2
import math
import random
start_path = './'
out_path = './out/'
#将所有图片存入列表
def get_filelist():
imgs_list = []
imgs_file = os.listdir(start_path)
for f in imgs_file:
if f.endswith('.jpg'):
imgs_list.append(f)
return imgs_list
#水平镜像翻转
def img_her_flip(pic, labels):
labels = labels
#img_width, img_height, c = pic.shape
flip_pic = cv2.flip(pic, 1, dst=None) # 水平镜像
liner_trans = np.array([[-1, 0, 1],
[0, 1, 0],
[0, 0, 1]])
for i, label in enumerate(labels):
cla, x, y, width, height = label
cen_row_vec = np.array([[float(x), float(y), 1]])
cen_vec = cen_row_vec.T
new_vec = np.dot(liner_trans, cen_vec)
new_x = round(float(new_vec[0][0]), 6)
new_y = round(float(new_vec[1][0]), 6)
labels[i] = [cla, new_x, new_y, width, height]
return flip_pic, labels
#垂直镜像翻转
def img_ver_flip(pic, labels):
labels = labels
flip_pic = cv2.flip(pic,-1,dst=None) # 垂直镜像
liner_trans = np.array([[-1, 0, 1],