46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
|
|
import os
|
||
|
|
import shutil
|
||
|
|
import re
|
||
|
|
|
||
|
|
def extract_patient_id(filename):
|
||
|
|
# 假設文件名格式為 "something_PATIENTID.nii.gz"
|
||
|
|
match = re.search(r'_([A-Z0-9]+)\.nii\.gz$', filename)
|
||
|
|
if match:
|
||
|
|
return match.group(1)
|
||
|
|
return None
|
||
|
|
|
||
|
|
def merge_folders(folder1, folder2, output_folder):
|
||
|
|
# 確保輸出資料夾存在
|
||
|
|
if not os.path.exists(output_folder):
|
||
|
|
os.makedirs(output_folder)
|
||
|
|
|
||
|
|
# 獲取兩個資料夾中的所有文件
|
||
|
|
files1 = set(os.listdir(folder1))
|
||
|
|
files2 = set(os.listdir(folder2))
|
||
|
|
|
||
|
|
# 合併所有唯一的病人ID
|
||
|
|
all_files = files1.union(files2)
|
||
|
|
|
||
|
|
for file in all_files:
|
||
|
|
patient_id = extract_patient_id(file)
|
||
|
|
if patient_id:
|
||
|
|
new_filename = f"label_{patient_id}.nii.gz"
|
||
|
|
source_folder = folder1 if file in files1 else folder2
|
||
|
|
source_path = os.path.join(source_folder, file)
|
||
|
|
dest_path = os.path.join(output_folder, new_filename)
|
||
|
|
|
||
|
|
# 複製文件到輸出資料夾並重命名
|
||
|
|
shutil.copy2(source_path, dest_path)
|
||
|
|
print(f"Copied and renamed {file} to {new_filename}")
|
||
|
|
else:
|
||
|
|
print(f"Skipped {file} - could not extract patient ID")
|
||
|
|
|
||
|
|
# 設定資料夾路徑
|
||
|
|
folder1 = '/home/onlylian/resampled_T1C_label'
|
||
|
|
folder2 = '/home/onlylian/resampled_CT+CTC_label'
|
||
|
|
output_folder = '/home/onlylian/merged_label_folder'
|
||
|
|
|
||
|
|
# 執行合併
|
||
|
|
merge_folders(folder1, folder2, output_folder)
|
||
|
|
|
||
|
|
print("Merging complete!")
|