Python 脚本:将图片路径文件和对应标签文件整合到同一个文件夹
以下是一个使用 Python 代码实现的示例,将包含 JPG 图片路径的 TXT 文件和对应的 TXT 标签文件复制到同一个文件夹中:
import os
import shutil
# 文件路径
txt_file_path = 'path/to/txt/file.txt'
labels_folder_path = 'path/to/labels/folder/'
output_folder_path = 'path/to/output/folder/'
# 创建输出文件夹
os.makedirs(output_folder_path, exist_ok=True)
# 读取 txt 文件中的图片路径
with open(txt_file_path, 'r') as txt_file:
image_paths = txt_file.read().splitlines()
# 复制图片文件到输出文件夹
for image_path in image_paths:
image_filename = os.path.basename(image_path)
shutil.copy(image_path, os.path.join(output_folder_path, image_filename))
# 读取 txt 标签文件
for image_path in image_paths:
image_filename = os.path.basename(image_path)
label_filename = os.path.splitext(image_filename)[0] + '.txt'
label_filepath = os.path.join(labels_folder_path, label_filename)
# 复制标签文件到输出文件夹
if os.path.isfile(label_filepath):
shutil.copy(label_filepath, os.path.join(output_folder_path, label_filename))
请根据实际情况替换代码中的文件路径,然后运行代码即可。代码会将 txt 文件中的图片路径对应的 JPG 图片和 TXT 标签复制到指定的输出文件夹中。
原文地址: https://www.cveoy.top/t/topic/phWE 著作权归作者所有。请勿转载和采集!