数据增强——图像翻转

目标:利用CV2通过对图像旋转、翻转,实现图像扩增

功能1:图像翻转

函数:cv2.flip(src, flipCode[, dst])

flipCode Anno
1 水平翻转
0 垂直翻转
-1 水平垂直翻转

参考地址:https://blog.csdn.net/jningwei/article/details/78753607

水平翻转目标框坐标

原目标框:左上角(w0,h0) 右下角(w1,h1) 水平翻转后:左上角(W-w0-w,h0) 右下角(W-w1+w,h1)

代码功能:

def img_flip(image_path,annotation_path,image_save_path,annotation_save_path):
    num_i = 10000000
    list_img = os.listdir(image_path)   #image_path文件夹下文件名称列表
    path_img = [os.path.join(image_path, path) for path in list_img]  #image_path文件夹下文件路径列表
    for path in path_img:
        num_i += 1

        txt = os.path.basename(path).replace('.jpg', '')  # 返回文件名
        txt_path = txt + '.txt'
        annot_path = os.path.join(annotation_path, txt_path)
        with open(annot_path, encoding='utf-8') as fp:
            text = fp.read()
            data = text.split(' ')
        if len(data) == 6:
            img = cv2.imread(path)
            img_h, img_w, _ = img.shape     #获取图像高度、宽度、通道数
            cv2.flip(img, 1)                #图像水平翻转
            img_name = 'core_battery' + str(num_i) + '.jpg'
            cv2.imwrite(os.path.join(image_save_path, img_name), img)
            w_0, w_1, = int(data[2]), int(data[4])
            annot_w = w_1 - w_0
            w_0_0 = img_w - w_0 - annot_w
            w_1_0 = img_w - w_1 + annot_w
            string = data[0] + ' ' + data[1] + ' ' + str(w_0_0) + ' ' + data[3] + ' ' + str(w_1_0) + ' ' + data[5]
            txt_name = 'core_battery' + str(num_i) + '.txt'

            with open(os.path.join(annotation_save_path, txt_name), 'w') as fp:
                fp.write(string)

if __name__ == '__main__':
    image_save_path = 'C:\data\core_500\image_new'             #处理后的图像保存位置
    annotation_save_path = 'C:\data\core_500/annotation_new'   #处理后的目标框保存位置
    annotation_path = 'C:\data\core_500\Annotation'            #原图像保存位置
    image_path = 'C:\data\core_500\Image'                      #原目标框保存位置
    # 图像翻转
    img_flip(image_path,annotation_path,image_save_path,annotation_save_path)
    # 图像旋转
    img_rot(image_path, annotation_path, image_save_path, annotation_save_path)
发布了109 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42233538/article/details/103501593