yolo训练策略--使用 Python 和 OpenCV 进行图像亮度增强与批量文件复制

本文主要是介绍yolo训练策略--使用 Python 和 OpenCV 进行图像亮度增强与批量文件复制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

简介

在计算机视觉和深度学习项目中,数据增强是一种常用的技术,通过对原始图像进行多种变换,可以增加数据集的多样性,从而提高模型的泛化能力。本文将介绍如何使用 Python 和 OpenCV 实现图像的亮度增强,并将增强后的图像与对应的注释文件批量复制到新目录中。

项目背景

假设你有一个数据集,包含若干图像及其对应的 XML 注释文件和标签文件。在模型训练前,你希望对这些图像进行亮度增强,并生成新的图像及其对应的注释文件和标签文件。本教程将指导你如何编写一个 Python 脚本,实现此功能。

train目录如下:

在这里插入图片描述
生成的augmented_data如下:

在这里插入图片描述

代码实现

1. 图像亮度调整函数

首先,我们需要编写一个函数,来调整图像的亮度。此处我们使用 HSV 色彩空间的 V(亮度)通道进行调整。

import cv2
import numpy as npdef adjust_brightness(im, vgain):hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)hue, sat, val = cv2.split(hsv)val = np.clip(val * vgain, 0, 255).astype(np.uint8)enhanced_hsv = cv2.merge((hue, sat, val))brightened_img = cv2.cvtColor(enhanced_hsv, cv2.COLOR_HSV2BGR)return brightened_img

2. 创建输出目录

在进行文件操作前,我们需要为增强后的文件创建一个新的输出目录。

import osdef create_output_folders(base_folder):new_base_folder = os.path.join(os.path.dirname(base_folder), "augmented_data")output_folders = {"images": os.path.join(new_base_folder, "images"),"annotations": os.path.join(new_base_folder, "annotations"),"labels": os.path.join(new_base_folder, "labels")}for folder in output_folders.values():os.makedirs(folder, exist_ok=True)return output_folders

3. 文件复制函数

为了复制原始图像和对应的注释文件,我们编写一个通用的文件复制函数。该函数可以根据需要在文件名后添加后缀。

import shutildef copy_file(src_path, dst_folder, filename_suffix, preserve_ext=True):base_filename, ext = os.path.splitext(os.path.basename(src_path))if preserve_ext:new_filename = f"{base_filename}{filename_suffix}{ext}"else:new_filename = f"{base_filename}{filename_suffix}"dst_path = os.path.join(dst_folder, new_filename)shutil.copy(src_path, dst_path)return dst_path

4. 图像增强与文件复制

该函数实现了图像的亮度增强,同时将增强后的图像和对应的注释文件保存到新的目录中。

def augment_and_copy_files(base_folder, image_filename, num_augmentations=2, vgain_range=(1, 1.5)):base_filename, image_ext = os.path.splitext(image_filename)# 构建原始文件路径file_paths = {"images": os.path.join(base_folder, "images", image_filename),"annotations": os.path.join(base_folder, "annotations", f"{base_filename}.xml"),"labels": os.path.join(base_folder, "labels", f"{base_filename}.txt")}# 创建输出文件夹output_folders = create_output_folders(base_folder)# 复制原始文件for key in file_paths:copy_file(file_paths[key], output_folders[key], "", preserve_ext=True)# 确保增强结果不重复unique_vgains = set()while len(unique_vgains) < num_augmentations:vgain = np.random.uniform(*vgain_range)if vgain not in unique_vgains:unique_vgains.add(vgain)brightened_img = adjust_brightness(cv2.imread(file_paths["images"]), vgain)for key in file_paths:filename_suffix = f"_enhanced_{len(unique_vgains)}"output_path = copy_file(file_paths[key], output_folders[key], filename_suffix, preserve_ext=True)if key == "images":cv2.imwrite(output_path, brightened_img)print(f"Saved: {output_path}")else:print(f"Copied {key}: {output_path}")print(f"All unique images and their annotations for {image_filename} have been enhanced and saved!")

5. 处理整个目录

最后,我们编写一个函数,用于处理指定目录中的所有图像文件,并对每张图像进行增强。

def process_all_images_in_folder(base_folder, num_augmentations=2, vgain_range=(1, 1.5)):images_folder = os.path.join(base_folder, "images")for image_filename in os.listdir(images_folder):if image_filename.lower().endswith(('.bmp', '.jpg', '.jpeg', '.png')):augment_and_copy_files(base_folder, image_filename, num_augmentations, vgain_range)

6. 运行脚本

你可以通过以下代码来运行整个图像增强与文件复制过程:

# 使用示例
base_folder = r"C:\Users\linds\Desktop\fsdownload\upgrade_algo_so\data_res_2024_08_31_10_29\train"
process_all_images_in_folder(base_folder)

7.整体代码

import cv2
import numpy as np
import os
import shutildef adjust_brightness(im, vgain):hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)hue, sat, val = cv2.split(hsv)val = np.clip(val * vgain, 0, 255).astype(np.uint8)enhanced_hsv = cv2.merge((hue, sat, val))brightened_img = cv2.cvtColor(enhanced_hsv, cv2.COLOR_HSV2BGR)return brightened_imgdef create_output_folders(base_folder):new_base_folder = os.path.join(os.path.dirname(base_folder), "augmented_data")output_folders = {"images": os.path.join(new_base_folder, "images"),"annotations": os.path.join(new_base_folder, "annotations"),"labels": os.path.join(new_base_folder, "labels")}for folder in output_folders.values():os.makedirs(folder, exist_ok=True)return output_foldersdef copy_file(src_path, dst_folder, filename_suffix, preserve_ext=True):base_filename, ext = os.path.splitext(os.path.basename(src_path))if preserve_ext:new_filename = f"{base_filename}{filename_suffix}{ext}"else:new_filename = f"{base_filename}{filename_suffix}"dst_path = os.path.join(dst_folder, new_filename)shutil.copy(src_path, dst_path)return dst_pathdef augment_and_copy_files(base_folder, image_filename, num_augmentations=2, vgain_range=(1, 1.5)):base_filename, image_ext = os.path.splitext(image_filename)# 构建原始文件路径file_paths = {"images": os.path.join(base_folder, "images", image_filename),"annotations": os.path.join(base_folder, "annotations", f"{base_filename}.xml"),"labels": os.path.join(base_folder, "labels", f"{base_filename}.txt")}# 创建输出文件夹output_folders = create_output_folders(base_folder)# 复制原始文件for key in file_paths:copy_file(file_paths[key], output_folders[key], "", preserve_ext=True)# 确保增强结果不重复unique_vgains = set()while len(unique_vgains) < num_augmentations:vgain = np.random.uniform(*vgain_range)if vgain not in unique_vgains:unique_vgains.add(vgain)brightened_img = adjust_brightness(cv2.imread(file_paths["images"]), vgain)for key in file_paths:filename_suffix = f"_enhanced_{len(unique_vgains)}"output_path = copy_file(file_paths[key], output_folders[key], filename_suffix, preserve_ext=True)if key == "images":cv2.imwrite(output_path, brightened_img)print(f"Saved: {output_path}")else:print(f"Copied {key}: {output_path}")print(f"All unique images and their annotations for {image_filename} have been enhanced and saved!")def process_all_images_in_folder(base_folder, num_augmentations=2, vgain_range=(1, 1.5)):images_folder = os.path.join(base_folder, "images")for image_filename in os.listdir(images_folder):if image_filename.lower().endswith(('.bmp', '.jpg', '.jpeg', '.png')):augment_and_copy_files(base_folder, image_filename, num_augmentations, vgain_range)# 使用示例
base_folder = r"C:\Users\linds\Desktop\fsdownload\upgrade_algo_so\data_res_2024_08_31_10_29\train"
process_all_images_in_folder(base_folder)

这篇关于yolo训练策略--使用 Python 和 OpenCV 进行图像亮度增强与批量文件复制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1124530

相关文章

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

C 语言中enum枚举的定义和使用小结

《C语言中enum枚举的定义和使用小结》在C语言里,enum(枚举)是一种用户自定义的数据类型,它能够让你创建一组具名的整数常量,下面我会从定义、使用、特性等方面详细介绍enum,感兴趣的朋友一起看... 目录1、引言2、基本定义3、定义枚举变量4、自定义枚举常量的值5、枚举与switch语句结合使用6、枚

redis过期key的删除策略介绍

《redis过期key的删除策略介绍》:本文主要介绍redis过期key的删除策略,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录第一种策略:被动删除第二种策略:定期删除第三种策略:强制删除关于big key的清理UNLINK命令FLUSHALL/FLUSHDB命

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)