深度学习常见数据集处理方法
1、数据集格式转换(json转txt)
import json
import os'''
任务:实例分割,labelme的json文件, 转txt文件
Ultralytics YOLO format
<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>
'''# 类别映射表,定义每个类别对应的ID
label_to_class_id = {"tree": 0# 根据需要添加更多类别
}# json转txt
def convert_labelme_json_to_yolo(json_file, output_dir, img_width, img_height):with open(json_file, 'r') as f:labelme_data = json.load(f)# 获取文件名(不含扩展名)file_name = os.path.splitext(os.path.basename(json_file))[0]# 输出的txt文件路径txt_file_path = os.path.join(output_dir, f"{file_name}.txt")with open(txt_file_path, 'w') as txt_file:for shape in labelme_data['shapes']:label = shape['label']points = shape['points']# 根据类别映射表获取类别ID,如果类别不在映射表中,跳过该标签class_id = label_to_class_id.get(label)if class_id is None:print(f"Warning: Label '{label}' not found in class mapping. Skipping.")continue# 将点的坐标归一化到0-1范围normalized_points = [(x / img_width, y / img_height) for x, y in points]# 写入类别IDtxt_file.write(f"{class_id}")# 写入多边形掩膜的所有归一化顶点坐标for point in normalized_points:txt_file.write(f" {point[0]:.6f} {point[1]:.6f}")txt_file.write("\n")if __name__ == "__main__":json_dir = "json" # 替换为LabelMe标注的JSON文件目录output_dir = "labels" # 输出的YOLO格式txt文件目录img_width = 500 # 图像宽度,根据实际图片尺寸设置img_height = 500 # 图像高度,根据实际图片尺寸设置# 创建输出文件夹if not os.path.exists(output_dir):os.makedirs(output_dir)# 批量处理所有json文件for json_file in os.listdir(json_dir):if json_file.endswith(".json"):json_path = os.path.join(json_dir, json_file)convert_labelme_json_to_yolo(json_path, output_dir, img_width, img_height)
2、数据集扩充(带json标签)
import time
import random
import cv2
import os
import numpy as np
from skimage.util import random_noise
import base64
import json
import re
from copy import deepcopy
import argparseclass DataAugmentForObjectDetection():#代码中包含五中数据增强的手段(噪声,光线,改变像素点,平移,镜像,打开后的数据增强为True,取消为False)def __init__(self, change_light_rate=0.5,add_noise_rate=0.2, random_point=0.5, flip_rate=0.5, shift_rate=0.5, rand_point_percent=0.03,is_addNoise=True, is_changeLight=False, is_random_point=True, is_shift_pic_bboxes=True,is_filp_pic_bboxes=True):self.change_light_rate = change_light_rateself.add_noise_rate = add_noise_rateself.random_point = random_pointself.flip_rate = flip_rateself.shift_rate = shift_rateself.rand_point_percent = rand_point_percent# 是否使用某种增强方式self.is_addNoise = is_addNoiseself.is_changeLight = is_changeLightself.is_random_point = is_random_pointself.is_filp_pic_bboxes = is_filp_pic_bboxesself.is_shift_pic_bboxes = is_shift_pic_bboxes# 加噪声(随机噪声)def _addNoise(self, img):return random_noise(img, seed=int(time.time())) * 255# 调整亮度def _changeLight(self, img):alpha = random.uniform(0.35, 1)blank = np.zeros(img.shape, img.dtype)return cv2.addWeighted(img, alpha, blank, 1 - alpha, 0)# 随机的改变点的值def _addRandPoint(self, img):percent = self.rand_point_percentnum = int(percent * img.shape[0] * img.shape[1])for i in range(num):rand_x = random.randint(0, img.shape[0] - 1)rand_y = random.randint(0, img.shape[1] - 1)if random.randint(0, 1) == 0:img[rand_x, rand_y] = 0else:img[rand_x, rand_y] = 255return img# 平移图像(注:需要到labelme工具上调整图像,部分平移的标注框可能会超出图像边界,对训练造成影响)def _shift_pic_bboxes(self, img, json_info):h, w, _ = img.shapex_min = wx_max = 0y_min = hy_max = 0shapes = json_info['shapes']for shape in shapes:points = np.array(shape['points'])x_min = min(x_min, points[:, 0].min())y_min = min(y_min, points[:, 1].min())x_max = max(x_max, points[:, 0].max())y_max = max(y_max, points[:, 0].max())d_to_left = x_mind_to_right = w - x_maxd_to_top = y_mind_to_bottom = h - y_maxx = random.uniform(-(d_to_left - 1) / 3, (d_to_right - 1) / 3)y = random.uniform(-(d_to_top - 1) / 3, (d_to_bottom - 1) / 3)M = np.float32([[1, 0, x], [0, 1, y]])shift_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))for shape in shapes:for p in shape['points']:p[0] += xp[1] += yreturn shift_img, json_info# 图像镜像翻转def _filp_pic_bboxes(self, img, json_info):h, w, _ = img.shapesed = random.random()if 0 < sed < 0.33:flip_img = cv2.flip(img, 0) # _flip_xinver = 0elif 0.33 < sed < 0.66:flip_img = cv2.flip(img, 1) # _flip_yinver = 1else:flip_img = cv2.flip(img, -1) # flip_x_yinver = -1shapes = json_info['shapes']for shape in shapes:for p in shape['points']:if inver == 0:p[1] = h - p[1]elif inver == 1:p[0] = w - p[0]elif inver == -1:p[0] = w - p[0]p[1] = h - p[1]return flip_img, json_infodef dataAugment(self, img, dic_info):change_num = 0while change_num < 1:if self.is_changeLight:if random.random() > self.change_light_rate:change_num += 1img = self._changeLight(img)if self.is_addNoise:if random.random() < self.add_noise_rate:change_num += 1img = self._addNoise(img)if self.is_random_point:if random.random() < self.random_point:change_num += 1img = self._addRandPoint(img)if self.is_shift_pic_bboxes:if random.random() < self.shift_rate:change_num += 1img, dic_info = self._shift_pic_bboxes(img, dic_info)if self.is_filp_pic_bboxes or 1:if random.random() < self.flip_rate:change_num += 1img, bboxes = self._filp_pic_bboxes(img, dic_info)return img, dic_infoclass ToolHelper():# 从json文件中提取原始标定的信息def parse_json(self, path):with open(path)as f:json_data = json.load(f)return json_data# 对图片进行字符编码def img2str(self, img_name):with open(img_name, "rb")as f:base64_data = str(base64.b64encode(f.read()))match_pattern = re.compile(r'b\'(.*)\'')base64_data = match_pattern.match(base64_data).group(1)return base64_data# 保存图片结果def save_img(self, save_path, img):cv2.imwrite(save_path, img)# 保持json结果def save_json(self, file_name, save_folder, dic_info):with open(os.path.join(save_folder, file_name), 'w') as f:json.dump(dic_info, f, indent=2)if __name__ == '__main__':need_aug_num = 5 #每张图片需要增强的次数toolhelper = ToolHelper()is_endwidth_dot = True #文件是否以.jpg或者png结尾dataAug = DataAugmentForObjectDetection()parser = argparse.ArgumentParser()parser.add_argument('--source_img_json_path', type=str, default=r'/home/leeqianxi/YOLO/datasets/data/data')#需要更改的json地址parser.add_argument('--save_img_json_path', type=str, default=r'/home/leeqianxi/YOLO/datasets/data/new_data')#改变后的json保存地址args = parser.parse_args()source_img_json_path = args.source_img_json_path # 图片和json文件原始位置save_img_json_path = args.save_img_json_path # 图片增强结果保存文件# 如果保存文件夹不存在就创建if not os.path.exists(save_img_json_path):os.mkdir(save_img_json_path)for parent, _, files in os.walk(source_img_json_path):files.sort() # 排序一下for file in files:if file.endswith('jpg') or file.endswith('png'):cnt = 0pic_path = os.path.join(parent, file)json_path = os.path.join(parent, file[:-4] + '.json')json_dic = toolhelper.parse_json(json_path)# 如果图片是有后缀的if is_endwidth_dot:# 找到文件的最后名字dot_index = file.rfind('.')_file_prefix = file[:dot_index] # 文件名的前缀_file_suffix = file[dot_index:] # 文件名的后缀img = cv2.imread(pic_path)while cnt < need_aug_num: # 继续增强auged_img, json_info = dataAug.dataAugment(deepcopy(img), deepcopy(json_dic))img_name = '{}_{}{}'.format(_file_prefix, cnt + 1, _file_suffix) # 图片保存的信息img_save_path = os.path.join(save_img_json_path, img_name)toolhelper.save_img(img_save_path, auged_img) # 保存增强图片json_info['imagePath'] = img_namebase64_data = toolhelper.img2str(img_save_path)json_info['imageData'] = base64_datatoolhelper.save_json('{}_{}.json'.format(_file_prefix, cnt + 1),save_img_json_path, json_info) # 保存xml文件print(img_name)cnt += 1 # 继续增强下一张
3、数据集划分(训练集、测试集、验证集)
# 将图片和标注数据按比例切分为 训练集和测试集
import shutil
import random
import os# 原始路径
image_original_path = "/home/leeqianxi/YOLO/ultralytics/pic/"
label_original_path = "/home/leeqianxi/YOLO/ultralytics/labels/"cur_path = os.getcwd()
# 训练集路径
train_image_path = os.path.join(cur_path, "datasets/images/train/")
train_label_path = os.path.join(cur_path, "datasets/labels/train/")# 验证集路径
val_image_path = os.path.join(cur_path, "datasets/images/val/")
val_label_path = os.path.join(cur_path, "datasets/labels/val/")# 测试集路径
test_image_path = os.path.join(cur_path, "datasets/images/test/")
test_label_path = os.path.join(cur_path, "datasets/labels/test/")# 训练集目录
list_train = os.path.join(cur_path, "datasets/train.txt")
list_val = os.path.join(cur_path, "datasets/val.txt")
list_test = os.path.join(cur_path, "datasets/test.txt")train_percent = 0.8
val_percent = 0.2
test_percent = 0def del_file(path):for i in os.listdir(path):file_data = path + "\\" + ios.remove(file_data)def mkdir():if not os.path.exists(train_image_path):os.makedirs(train_image_path)else:del_file(train_image_path)if not os.path.exists(train_label_path):os.makedirs(train_label_path)else:del_file(train_label_path)if not os.path.exists(val_image_path):os.makedirs(val_image_path)else:del_file(val_image_path)if not os.path.exists(val_label_path):os.makedirs(val_label_path)else:del_file(val_label_path)if not os.path.exists(test_image_path):os.makedirs(test_image_path)else:del_file(test_image_path)if not os.path.exists(test_label_path):os.makedirs(test_label_path)else:del_file(test_label_path)def clearfile():if os.path.exists(list_train):os.remove(list_train)if os.path.exists(list_val):os.remove(list_val)if os.path.exists(list_test):os.remove(list_test)def main():mkdir()clearfile()file_train = open(list_train, 'w')file_val = open(list_val, 'w')file_test = open(list_test, 'w')total_txt = os.listdir(label_original_path)num_txt = len(total_txt)list_all_txt = range(num_txt)num_train = int(num_txt * train_percent)num_val = int(num_txt * val_percent)num_test = num_txt - num_train - num_valtrain = random.sample(list_all_txt, num_train)# train从list_all_txt取出num_train个元素# 所以list_all_txt列表只剩下了这些元素val_test = [i for i in list_all_txt if not i in train]# 再从val_test取出num_val个元素,val_test剩下的元素就是testval = random.sample(val_test, num_val)print("训练集数目:{}, 验证集数目:{}, 测试集数目:{}".format(len(train), len(val), len(val_test) - len(val)))for i in list_all_txt:name = total_txt[i][:-4]srcImage = image_original_path + name + '.png'srcLabel = label_original_path + name + ".txt"if i in train:dst_train_Image = train_image_path + name + '.png'dst_train_Label = train_label_path + name + '.txt'shutil.copyfile(srcImage, dst_train_Image)shutil.copyfile(srcLabel, dst_train_Label)file_train.write(dst_train_Image + '\n')elif i in val:dst_val_Image = val_image_path + name + '.png'dst_val_Label = val_label_path + name + '.txt'shutil.copyfile(srcImage, dst_val_Image)shutil.copyfile(srcLabel, dst_val_Label)file_val.write(dst_val_Image + '\n')else:dst_test_Image = test_image_path + name + '.jpg'dst_test_Label = test_label_path + name + '.txt'shutil.copyfile(srcImage, dst_test_Image)shutil.copyfile(srcLabel, dst_test_Label)file_test.write(dst_test_Image + '\n')file_train.close()file_val.close()file_test.close()if __name__ == "__main__":main()
4、图像裁剪为固定大小
from PIL import Image
import osdef crop_image(image_path, output_dir, crop_c, crop_size=(500, 500)):# 打开原始图片img = Image.open(image_path)img_width, img_height = img.sizecrop_width, crop_height = crop_size# 确保输出目录存在if not os.path.exists(output_dir):os.makedirs(output_dir)# 计算可以裁剪的行数和列数horizontal_crops = img_width // crop_widthvertical_crops = img_height // crop_height# 裁剪并保存子图crop_count = crop_cfor i in range(vertical_crops):for j in range(horizontal_crops):left = j * crop_widthupper = i * crop_heightright = left + crop_widthlower = upper + crop_height# 裁剪图像cropped_img = img.crop((left, upper, right, lower))# 保存裁剪后的图像output_path = os.path.join(output_dir, f"crop_{crop_count+1}.png")cropped_img.save(output_path)crop_count += 1print(f"裁剪完成,共裁剪 {crop_count} 张图片。")if __name__ == "__main__":image_path = "img.png" # 输入图片的路径output_dir = 'cropped_images' # 输出文件夹路径crop_c = 0crop_image(image_path, output_dir, crop_c)
相关文章:
深度学习常见数据集处理方法
1、数据集格式转换(json转txt) import json import os 任务:实例分割,labelme的json文件, 转txt文件 Ultralytics YOLO format <class-index> <x1> <y1> <x2> <y2> ... <xn> <yn> # 类…...
1180 - 【入门】数字出现次数
题目描述 有50个数(0-19),求这50个数中相同数字出现的最多次数为几次? 输入 50个数字 输出 1个数字(即相同数字出现的最多次数) 样例 输入 复制 1 10 2 0 15 8 12 7 0 3 15 0 15 18 16 7 17 16 9 …...
C++20: 像Python一样split字符串
概要 Python 的字符串天生支持 split( ) 操作,支持单个字符或字符串作为分隔符。 C 在这方面显得很笨拙,但是在 C20 下经过一番尝试,还是能够提供类似的简洁调用。 Python 代码 s 0,11,336,23,370nums s.split(,) for n in nums:print(n…...
Unity3D UI 嵌套滚动视图
Unity3D 解决 UI 嵌套滚动视图滑动问题。 嵌套滚动视图 滑动问题 在游戏开发中,我们常常会遇到一种情况,在一个滚动视图列表中,每个 item 还包含了一个内嵌的滚动视图。 这样,当我们在滑动外层的滚动视图时,如果点…...
你还没有将 Siri 接入GPT对话功能吗?
由于各种原因,国内ios用户目前无缘自带 AI 功能,但是这并不代表国内 ios 无法接入 AI 功能,接下来手把手带你为iPhone siri 接入 gpt 对话功能。 siri 接入 chatGPT 暂时还无法下载 ChatGPT app,或者没有账号的读者可以直接跳到…...
_C#_串口助手_字符串拼接缺失问题(未知原理)
最近使用WPF开发串口助手时,遇到一个很奇怪的问题,无论是主线程、异步还是多线程,当串口接收速度达到0.016s一次以上,就会发生字符串缺失问题并且很卡。而0.016s就一切如常,仿佛0.015s与0.016s是天堑之隔。 同一份代码…...
浅析大数据时代下的网络安全
一、大数据时代下网络安全的现状 在全球化进程不断深入发展的情况下,互联网行业发展速度也更加迅猛,人们对网络信息的需求量不断增加,所以目前已经进入了大数据时代。 随着计算机技术的不断发展,我国互联网网络规模、网民数量、…...
Mysql数据库基础篇笔记
目录 sql语句 DDL——数据库定义语言(定义库,表,字段) 数据库操作: 表操作: DML 增删改语句 DQL 语法编写顺序: 条件查询 DCL 用户管理: 权限管理: 函数 常见字符串内置函…...
rabbitmq原理及命令
目录 一、RabbitMQ原理1、交换机(Exchange)fanoutdirecttopicheaders(很少用到) 2、队列Queue3、Virtual Hosts4、基础对象 二、RabbitMQ的一些基本操作:1、用户管理2、用户角色3、vhost4、开启web管理接口5、批量删除队列 一、Ra…...
React进阶面试题(四)
React 的 reconciliation(协调)算法 Reconciliation是React的diff算法,用于比较更新前后的虚拟DOM树差异,从而使用最小的代价将原始DOM按照新的状态、属性进行更新。其目的是找出两棵树的差异,原生方式直接比较复杂度…...
24/12/1 算法笔记<强化学习> 创建Maze交互
我们今天制作一个栅格的游戏。 我们直接上代码教学。 1.载入库和查找相应的函数版本 import numpy as np import time import sysif sys.version_info.major 2:import Tkinter as tk else:import tkinter as tk 2.设置长宽和单元格大小 UNIT 40 MAZE_H 4 MAZE_W 4 3.初始…...
Linux驱动开发(10):I2C子系统–mpu6050驱动实验
本章我们以板载MPU6050为例讲解i2c驱动程序的编写,本章主要分为五部分内容。 第一部分,i2c基本知识,回忆i2c物理总线和基本通信协议。 第二部分,linux下的i2c驱动框架。 第三部分,i2c总线驱动代码拆解。 第四部分&a…...
《装甲车内气体检测“神器”:上海松柏 K-5S 电化学传感器模组详解》
《装甲车内气体检测“神器”:上海松柏 K-5S 电化学传感器模组详解》 一、引言二、K-5S 电化学传感器模组概述(一)产品简介(二)产品特点(三)产品适用场景 三、电化学传感器原理及优点(一…...
如何将多个JS文件打包成一个JS文件?
文章目录 前言SDK 打包安装 webpack创建 webpack.config.js编译命令行遇到的坑点前言 上一篇已经记录了如何开发一个小游戏聚合SDK,既然是SDK,最终都是给外部人员使用的。调研了一下市面上的前端SDK,最终都是编译成一个 js 文件。我猜理由大概是 js 文件之间的调用都是需要…...
100个python经典面试题详解(新版)
应老粉要求,每晚加餐一个最新面试题 包括Python面试中常见的问题,涵盖列表、元组、字符串插值、比较操作符、装饰器、类与对象、函数调用方式、数据结构操作、序列化、数据处理函数等多个方面。 旨在帮助数据科学家和软件工程师准备面试或提升Python技能。 7、Python面试题…...
C#初阶概念理解
梳理了一些本人在学习C#时的一些生疏点,同时也加深自己的印象。 堆&栈 堆用来存储程序运行时产生的变量,当程序结束时释放; 栈用来存储程序运行时,调用方法产生的临时变量,方法运行完成后就会释放…...
node.js基础学习-url模块-url地址处理(二)
前言 前面我们创建了一个HTTP服务器,如果只是简单的http://localhost:3000/about这种链接我们是可以处理的,但是实际运用中一般链接都会带参数,这样的话如果我们只是简单的判断链接来分配数据,就会报404找不到链接。为了解决这个问…...
算法与数据结构(1)
一:数据结构概论 数据结构分为初阶数据结构(主要由C语言实现)和高阶数据结构(由C实现) 初阶数据结构当中,我们会学到顺序表、链表、栈和队列、二叉树、常见排序算法等内容。 高阶数据结构当中࿰…...
FTP介绍与配置
前言: FTP是用来传送文件的协议。使用FTP实现远程文件传输的同时,还可以保证数据传输的可靠性和高效性。 介绍 FTP的应用 在企业网络中部署一台FTP服务器,将网络设备配置为FTP客户端,则可以使用FTP来备份或更新VRP文件和配置文件…...
SQL面试题——抖音SQL面试题 最近一笔有效订单
最近一笔有效订单 题目背景如下,现有订单表order,包含订单ID,订单时间,下单用户,当前订单是否有效 +---------+----------------------+----------+-----------+ | ord_id | ord_time | user_id | is_valid | +---------+----------------------+--------…...
【Python】 -- 趣味代码 - 小恐龙游戏
文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...
MFC内存泄露
1、泄露代码示例 void X::SetApplicationBtn() {CMFCRibbonApplicationButton* pBtn GetApplicationButton();// 获取 Ribbon Bar 指针// 创建自定义按钮CCustomRibbonAppButton* pCustomButton new CCustomRibbonAppButton();pCustomButton->SetImage(IDB_BITMAP_Jdp26)…...
工程地质软件市场:发展现状、趋势与策略建议
一、引言 在工程建设领域,准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具,正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...
JVM虚拟机:内存结构、垃圾回收、性能优化
1、JVM虚拟机的简介 Java 虚拟机(Java Virtual Machine 简称:JVM)是运行所有 Java 程序的抽象计算机,是 Java 语言的运行环境,实现了 Java 程序的跨平台特性。JVM 屏蔽了与具体操作系统平台相关的信息,使得 Java 程序只需生成在 JVM 上运行的目标代码(字节码),就可以…...
Vite中定义@软链接
在webpack中可以直接通过符号表示src路径,但是vite中默认不可以。 如何实现: vite中提供了resolve.alias:通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...
解析“道作为序位生成器”的核心原理
解析“道作为序位生成器”的核心原理 以下完整展开道函数的零点调控机制,重点解析"道作为序位生成器"的核心原理与实现框架: 一、道函数的零点调控机制 1. 道作为序位生成器 道在认知坐标系$(x_{\text{物}}, y_{\text{意}}, z_{\text{文}}…...
内窥镜检查中基于提示的息肉分割|文献速递-深度学习医疗AI最新文献
Title 题目 Prompt-based polyp segmentation during endoscopy 内窥镜检查中基于提示的息肉分割 01 文献速递介绍 以下是对这段英文内容的中文翻译: ### 胃肠道癌症的发病率呈上升趋势,且有年轻化倾向(Bray等人,2018&#x…...
渗透实战PortSwigger Labs指南:自定义标签XSS和SVG XSS利用
阻止除自定义标签之外的所有标签 先输入一些标签测试,说是全部标签都被禁了 除了自定义的 自定义<my-tag onmouseoveralert(xss)> <my-tag idx onfocusalert(document.cookie) tabindex1> onfocus 当元素获得焦点时(如通过点击或键盘导航&…...
FTXUI::Dom 模块
DOM 模块定义了分层的 FTXUI::Element 树,可用于构建复杂的终端界面,支持响应终端尺寸变化。 namespace ftxui {...// 定义文档 定义布局盒子 Element document vbox({// 设置文本 设置加粗 设置文本颜色text("The window") | bold | color(…...
欢乐熊大话蓝牙知识17:多连接 BLE 怎么设计服务不会乱?分层思维来救场!
多连接 BLE 怎么设计服务不会乱?分层思维来救场! 作者按: 你是不是也遇到过 BLE 多连接时,调试现场像网吧“掉线风暴”? 温度传感器连上了,心率带丢了;一边 OTA 更新,一边通知卡壳。…...
