| import SimpleITK as sitk |
| import numpy as np |
| from pathlib import Path |
| from tqdm import tqdm |
|
|
| def get_bounding_box_3d(label_array, foreground_values=None): |
| """ |
| 计算3D标签数组中前景区域的bounding box |
| |
| Parameters: |
| - label_array: 3D numpy数组 |
| - foreground_values: 前景值列表,默认为[1,2,3,4,5,6,7,8,9] |
| |
| Returns: |
| - (z_min, z_max, y_min, y_max, x_min, x_max): bounding box坐标 |
| """ |
| if foreground_values is None: |
| foreground_values = list(range(21, 30)) |
| |
| |
| foreground_mask = np.zeros_like(label_array, dtype=bool) |
| for value in foreground_values: |
| foreground_mask |= (label_array == value) |
| |
| |
| coords = np.where(foreground_mask) |
| |
| if len(coords[0]) == 0: |
| return None |
| |
| z_min, z_max = coords[0].min(), coords[0].max() |
| y_min, y_max = coords[1].min(), coords[1].max() |
| x_min, x_max = coords[2].min(), coords[2].max() |
| |
| return z_min, z_max, y_min, y_max, x_min, x_max |
|
|
| def crop_with_bbox(image_array, bbox): |
| """ |
| 根据bounding box截取图像 |
| """ |
| z_min, z_max, y_min, y_max, x_min, x_max = bbox |
| return image_array[z_min:z_max+1, y_min:y_max+1, x_min:x_max+1] |
|
|
| def calculate_new_origin(original_image, bbox): |
| """ |
| 计算截取后图像的新origin |
| """ |
| z_min, z_max, y_min, y_max, x_min, x_max = bbox |
| |
| |
| original_spacing = original_image.GetSpacing() |
| original_origin = original_image.GetOrigin() |
| |
| |
| new_origin = ( |
| original_origin[0] + x_min * original_spacing[0], |
| original_origin[1] + y_min * original_spacing[1], |
| original_origin[2] + z_min * original_spacing[2] |
| ) |
| |
| return new_origin |
|
|
| def relabel_segmentation(label_array): |
| """ |
| 重新标记分割结果: |
| - 值为1的pixel保持1 |
| - 值为2-9的pixel改成值为2 |
| - 其余的都改成0 |
| """ |
| new_label = np.zeros_like(label_array) |
| new_label[label_array == 21] = 1 |
| new_label[(label_array >= 22) & (label_array <= 29)] = 2 |
| return new_label |
|
|
| def process_ct_and_labels(path_a, path_b, path_c, path_d): |
| """ |
| 处理CT图片和标签文件 |
| |
| Parameters: |
| - path_a: CT图片路径 |
| - path_b: 标签文件路径 |
| - path_c: 截取后图片保存路径 |
| - path_d: 处理后标签保存路径 |
| """ |
| |
| |
| path_a = Path(path_a) |
| path_b = Path(path_b) |
| path_c = Path(path_c) |
| path_d = Path(path_d) |
| |
| |
| path_c.mkdir(parents=True, exist_ok=True) |
| path_d.mkdir(parents=True, exist_ok=True) |
| |
| |
| ct_files = list(path_a.glob("*.mha")) |
| |
| if not ct_files: |
| print(f"在路径 {path_a} 中没有找到mha文件") |
| return |
| |
| print(f"找到 {len(ct_files)} 个CT文件") |
| |
| success_count = 0 |
| failed_files = [] |
| |
| for ct_file in tqdm(ct_files, desc="处理文件"): |
| try: |
| |
| label_file = path_b / ct_file.name |
| |
| if not label_file.exists(): |
| print(f"警告: 找不到对应的标签文件 - {label_file.name}") |
| failed_files.append(ct_file.name) |
| continue |
| |
| |
| print(f"处理: {ct_file.name}") |
| |
| ct_image = sitk.ReadImage(str(ct_file)) |
| label_image = sitk.ReadImage(str(label_file)) |
| |
| |
| ct_array = sitk.GetArrayFromImage(ct_image) |
| label_array = sitk.GetArrayFromImage(label_image) |
| |
| |
| if ct_array.shape != label_array.shape: |
| print(f"警告: 图片和标签尺寸不匹配 - {ct_file.name}") |
| print(f"CT shape: {ct_array.shape}, Label shape: {label_array.shape}") |
| failed_files.append(ct_file.name) |
| continue |
| |
| |
| bbox = get_bounding_box_3d(label_array, foreground_values=list(range(21, 30))) |
| |
| if bbox is None: |
| print(f"警告: 没有找到前景区域 - {ct_file.name}") |
| failed_files.append(ct_file.name) |
| continue |
| |
| print(f"Bounding box: z[{bbox[0]}:{bbox[1]}], y[{bbox[2]}:{bbox[3]}], x[{bbox[4]}:{bbox[5]}]") |
| |
| |
| cropped_ct = crop_with_bbox(ct_array, bbox) |
| cropped_label = crop_with_bbox(label_array, bbox) |
| |
| print(f"原始尺寸: {ct_array.shape}, 截取后尺寸: {cropped_ct.shape}") |
| |
| |
| relabeled = relabel_segmentation(cropped_label) |
| |
| |
| unique_values = np.unique(relabeled) |
| print(f"重新标记后的标签值: {unique_values}") |
| |
| |
| new_origin = calculate_new_origin(ct_image, bbox) |
| |
| |
| cropped_ct_image = sitk.GetImageFromArray(cropped_ct) |
| |
| cropped_ct_image.SetSpacing(ct_image.GetSpacing()) |
| cropped_ct_image.SetOrigin(new_origin) |
| cropped_ct_image.SetDirection(ct_image.GetDirection()) |
| |
| output_ct_path = path_c / ct_file.name |
| sitk.WriteImage(cropped_ct_image, str(output_ct_path)) |
| |
| |
| relabeled_image = sitk.GetImageFromArray(relabeled.astype(np.uint8)) |
| |
| relabeled_image.SetSpacing(label_image.GetSpacing()) |
| relabeled_image.SetOrigin(new_origin) |
| relabeled_image.SetDirection(label_image.GetDirection()) |
| |
| output_label_path = path_d / ct_file.name |
| sitk.WriteImage(relabeled_image, str(output_label_path)) |
| |
| success_count += 1 |
| print(f"✅ 成功处理: {ct_file.name}") |
| print("-" * 50) |
| |
| except Exception as e: |
| print(f"❌ 处理失败: {ct_file.name} - {str(e)}") |
| failed_files.append(ct_file.name) |
| |
| |
| print(f"\n{'='*60}") |
| print(f"处理完成!") |
| print(f"成功处理: {success_count}/{len(ct_files)} 个文件") |
| print(f"失败文件数: {len(failed_files)}") |
| |
| if failed_files: |
| print(f"\n失败的文件:") |
| for filename in failed_files: |
| print(f" - {filename}") |
| |
| print(f"\n输出路径:") |
| print(f"截取后的CT图片: {path_c}") |
| print(f"处理后的标签: {path_d}") |
|
|
| def verify_results(path_c, path_d, num_samples=3): |
| """ |
| 验证处理结果 |
| """ |
| print(f"\n{'='*60}") |
| print("验证处理结果...") |
| |
| ct_files = list(Path(path_c).glob("*.mha"))[:num_samples] |
| |
| for ct_file in ct_files: |
| label_file = Path(path_d) / ct_file.name |
| |
| if label_file.exists(): |
| |
| ct_image = sitk.ReadImage(str(ct_file)) |
| label_image = sitk.ReadImage(str(label_file)) |
| |
| ct_array = sitk.GetArrayFromImage(ct_image) |
| label_array = sitk.GetArrayFromImage(label_image) |
| |
| |
| unique_labels = np.unique(label_array) |
| |
| print(f"\n文件: {ct_file.name}") |
| print(f"CT尺寸: {ct_array.shape}") |
| print(f"标签尺寸: {label_array.shape}") |
| print(f"CT spacing: {ct_image.GetSpacing()}") |
| print(f"CT origin: {ct_image.GetOrigin()}") |
| print(f"标签值: {unique_labels}") |
| |
| |
| for label_val in unique_labels: |
| count = np.sum(label_array == label_val) |
| print(f" 标签 {label_val}: {count} 像素") |
|
|
| def main(): |
| """ |
| 主函数 |
| """ |
| |
| PATH_A = "/research/phd_y3/pelvic_project/Data/images" |
| PATH_B = "/research/phd_y3/pelvic_project/Data/labels" |
| PATH_C = "/research/phd_y3/pelvic_project/Data/left_hip_bbox_images" |
| PATH_D = "/research/phd_y3/pelvic_project/Data/left_hip_bbox_labels" |
| |
| print("开始处理CT图片和标签文件...") |
| print(f"CT图片路径: {PATH_A}") |
| print(f"标签路径: {PATH_B}") |
| print(f"输出CT路径: {PATH_C}") |
| print(f"输出标签路径: {PATH_D}") |
| |
| |
| if not Path(PATH_A).exists(): |
| print(f"错误: CT图片路径不存在 - {PATH_A}") |
| return |
| |
| if not Path(PATH_B).exists(): |
| print(f"错误: 标签路径不存在 - {PATH_B}") |
| return |
| |
| |
| process_ct_and_labels(PATH_A, PATH_B, PATH_C, PATH_D) |
| |
| |
| verify_results(PATH_C, PATH_D) |
|
|
| if __name__ == "__main__": |
| main() |
|
|