创建一个有训练集和测试集的图像和标签的数据集代码实现
时间: 2024-05-14 21:16:03 浏览: 22
以下是一个简单的Python代码示例,用于创建带有训练集和测试集的图像和标签数据集:
```python
import os
import random
from shutil import copyfile
# 设置数据集目录
dataset_dir = "/path/to/dataset"
# 设置图像目录和标签目录
image_dir = os.path.join(dataset_dir, "images")
label_dir = os.path.join(dataset_dir, "labels")
# 创建训练集和测试集目录
train_dir = os.path.join(dataset_dir, "train")
test_dir = os.path.join(dataset_dir, "test")
os.makedirs(train_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)
# 将数据集分为训练集和测试集
image_files = os.listdir(image_dir)
random.shuffle(image_files)
split_index = int(0.8 * len(image_files))
train_files = image_files[:split_index]
test_files = image_files[split_index:]
# 复制训练集图像和标签到训练集目录
for file in train_files:
image_file = os.path.join(image_dir, file)
label_file = os.path.join(label_dir, file)
train_image_file = os.path.join(train_dir, file)
train_label_file = os.path.join(train_dir, file)
copyfile(image_file, train_image_file)
copyfile(label_file, train_label_file)
# 复制测试集图像和标签到测试集目录
for file in test_files:
image_file = os.path.join(image_dir, file)
label_file = os.path.join(label_dir, file)
test_image_file = os.path.join(test_dir, file)
test_label_file = os.path.join(test_dir, file)
copyfile(image_file, test_image_file)
copyfile(label_file, test_label_file)
```
以上代码假设图像和标签文件名相同且位于同一目录中,创建一个名为 "train" 的训练集目录和一个名为 "test" 的测试集目录,并将数据集的80%用于训练集,20%用于测试集。
请注意,此代码仅是一个示例,实际数据集的创建方式可能因数据集类型和格式而异。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)