hebing_yaml.py
import os
import shutil
import time
import yaml
import json
class Time_Str:
def __init__(self):
self.last_time, self.counter = '', 0
def get_time(self, fmt="%m%d_%H%M_%S"):
now_time = time.strftime(fmt)
self.counter += 1
if now_time != self.last_time:
self.last_time, self.counter = now_time, 0
return f"{now_time}_{self.counter}"
def get_time_sec(self):
return self.get_time("%m%d_%H%M_%S")
def get_time_mm(self):
return self.get_time("%m%d_%H%M")
def update_json_image_path(json_path, new_img_name):
"""修改 JSON 文件中的 imagePath 字段"""
try:
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 更新字段
if "imagePath" in data:
data["imagePath"] = new_img_name
# 保存回原文件
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"✅ 更新 imagePath: {json_path} -> {new_img_name}")
except Exception as e:
print(f"⚠️ 修改 {json_path} 失败: {e}")
if __name__ == '__main__':
name_get = Time_Str()
yaml_path = r"data_chan.yaml"
with open(yaml_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
for key in ['train', 'val']:
dirs = data[key]
save_dir = rf"D:\data\det_chan_1112_{key}"
os.makedirs(save_dir, exist_ok=True)
for dir_a in dirs:
json_files = [
os.path.join(root, file).replace("\\", "/")
for root, _, files in os.walk(dir_a)
for file in files if file.lower().endswith(('.json', '.xpkl', '.xjpeg'))
]
for json_file in json_files:
json_name = os.path.basename(json_file)
json_to = os.path.join(save_dir, json_name)
img_path = os.path.splitext(json_file)[0] + ".jpg"
if not os.path.exists(img_path):
print('❌ 图片不存在:', img_path)
continue
if os.path.exists(json_to):
# 同名文件存在,重命名
new_name = name_get.get_time_mm()
json_name = f"{new_name}.json"
img_name = f"{new_name}.jpg"
new_json_path = os.path.join(save_dir, json_name)
new_img_path = os.path.join(save_dir, img_name)
shutil.copyfile(json_file, new_json_path)
shutil.copyfile(img_path, new_img_path)
# 修改 imagePath
update_json_image_path(new_json_path, img_name)
else:
# 不重名,直接复制
shutil.copy(json_file, save_dir)
shutil.copy(img_path, save_dir)
print("\n训练集路径(train):", data['train'])
print("验证集路径(val):", data['val'])
print("类别数(nc):", data['nc'])
print("类别名称(names):", data['names'])