YOLO图像前处理及格式转换

复制代码
import cv2
import numpy as np
import os
import glob

# 数据增强函数
def augment_data(img):
    rows,cols,_ = img.shape

    # 水平翻转图像
    if np.random.random() > 0.5:
        img = cv2.flip(img, 1)
        img_name = os.path.splitext(save_path)[0] + "_flip.png"
        cv2.imwrite(img_name, img)
        print("Saved augmented image:", img_name)

    # 随机缩放图像
    scale = np.random.uniform(0.9, 1.1)
    M = cv2.getRotationMatrix2D((cols/2, rows/2), 0, scale)
    img_transformed = cv2.warpAffine(img, M, (cols, rows))
    img_name = os.path.splitext(save_path)[0] + "_transform.png"
    cv2.imwrite(img_name, img_transformed)
    print("Saved augmented image:", img_name)

    # 随机旋转图像
    angle = np.random.randint(-10, 10)
    M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
    img_rotated = cv2.warpAffine(img, M, (cols, rows))
    img_name = os.path.splitext(save_path)[0] + "_rotated.png"
    cv2.imwrite(img_name, img_rotated)
    print("Saved augmented image:", img_name)

    # 添加高斯噪音
    mean = 0
    std = np.random.uniform(5, 15)
    noise = np.zeros(img.shape, np.float32)
    cv2.randn(noise, mean, std)
    noise = np.uint8(noise)
    img_noisy = cv2.add(img, noise)
    img_name = os.path.splitext(save_path)[0] + "_noisy.png"
    cv2.imwrite(img_name, img_noisy)
    print("Saved augmented image:", img_name)

    # 随机调整对比度和亮度
    alpha = np.random.uniform(0.8, 1.2)
    beta = np.random.randint(-10, 10)
    img_contrast = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)
    img_name = os.path.splitext(save_path)[0] + "_contrast.png"
    cv2.imwrite(img_name, img_contrast)
    print("Saved augmented image:", img_name)

    return img


# 读取 data 文件夹中的所有图片,并进行数据增强
data_dir = "data"
save_dir = "result"
if not os.path.exists(save_dir):
    os.makedirs(save_dir)

# 使用 glob 库来遍历 data 文件夹中所有图像
for img_path in glob.glob(os.path.join(data_dir, "*.png")):

    img = cv2.imread(img_path)

    # 获取保存增强后的图片文件名
    img_name = os.path.basename(img_path)
    save_path = os.path.join(save_dir, img_name)

    # 数据增强
    augment_data(img)

    # 保存原始图片
    cv2.imwrite(save_path, img)
    print("Saved original image:", save_path)

XML格式数据集转TXT(YOLO)_xml转txt-CSDN博客

相关推荐
我材不敲代码2 分钟前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
身如柳絮随风扬1 小时前
Java中的CAS机制详解
java·开发语言
0思必得02 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长2 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779872 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272713 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊3 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
froginwe113 小时前
Scala 循环
开发语言
m0_706653233 小时前
C++编译期数组操作
开发语言·c++·算法
故事和你913 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口