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博客

相关推荐
IVEN_17 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang18 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮18 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling18 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers