PyTorch深度學(xué)習(xí)快速入門教程(絕對通俗易懂!)【小土堆】

P7 p6. Dataset類代碼實戰(zhàn)
對P7寫入txt文檔略做了些調(diào)整:
(ps:增加了檢查文件夾是否存在,不存在則創(chuàng)建的功能,這樣就省去了自己自己再去一個個創(chuàng)建的功能)
import os
root_dir = “your_path”
# 使用字典的“鍵值對”將目標圖片文件夾與標簽文件對應(yīng)
targets = {
"ants_image": "ants_label",
"bees_image": "bees_label",
"spiders_image": "spiders_label"
}
# 創(chuàng)建文件夾、遍歷
for target_dir, out_dir in targets.items():
# 檢查標簽文件夾是否存在,沒有則創(chuàng)建
if not os.path.exists(os.path.join(root_dir, out_dir)):
os.makedirs(os.path.join(root_dir, out_dir))
img_paths = os.listdir(os.path.join(root_dir, target_dir))
label = target_dir.split('_')【0】
for img_path in img_paths:
file_name = img_path.split('.jpg')【0】
with open(os.path.join(root_dir, out_dir, f"{file_name}.txt"), 'w+') as f:
f.write(label)