如何根据txt文件的分类标注将批量图片归类到对应文件夹
图片按标注类别自动归类实现方案
实现逻辑
- 按3行一组读取标注txt文件,分别提取图片路径、类别信息,直接跳过分隔线
- 自动创建对应类别的存储文件夹,重复创建也不会触发报错
- 兼容异常场景,遇到不存在的图片会直接打印提示跳过,不会中断整个分类流程
完整可运行代码
import os import shutil # -------------------------- 请调整以下参数 -------------------------- # 你的标注txt文件路径 annotation_file = "file.txt" # 分类后图片存放的根目录 target_root = "./sorted_images" # 不需要保留原目录图片的话,把下方shutil.copy2改成shutil.move即可 # ------------------------------------------------------------------- # 初始化根目录 os.makedirs(target_root, exist_ok=True) with open(annotation_file, 'r', encoding='utf-8') as f: while True: # 逐组读取3行内容:图片行、类别行、分隔线 img_line = f.readline() class_line = f.readline() split_line = f.readline() # 读到文件末尾直接退出循环 if not img_line or not class_line or not split_line: break # 提取有效信息,去除首尾空格、换行符、前缀内容 img_path = img_line.replace("Analysing Image: ", "").strip() class_name = class_line.replace("Object Class Presented: ", "").strip() # 跳过不存在的图片 if not os.path.exists(img_path): print(f"图片不存在,已跳过:{img_path}") continue # 创建对应类别文件夹 class_save_dir = os.path.join(target_root, class_name) os.makedirs(class_save_dir, exist_ok=True) # 执行文件复制/移动操作 target_path = os.path.join(class_save_dir, os.path.basename(img_path)) shutil.copy2(img_path, target_path)
内容的提问来源于stack exchange,提问作者programmer1234
相关产品推荐
相关产品推荐

