CBT_project/imaging/affine.py
Xiao Furen d167c1f7c7 feat(imaging): implement coordinate transformation pipeline and directory restructuring
Introduce a robust coordinate transformation system to manage the relationship
between original CT space and rotated/standardized segmentation spaces.
This includes a new directory hierarchy to separate unrotated crops from
rotated outputs and utility functions for geometric mapping.

Key changes:
- Implement `imaging/transforms.py` to handle bounding box metadata,
  affine standardization, and coordinate mapping between spaces.
- Restructure dataset output: unrotated segmentation files (binary, SDF,
  ROI, etc.) are now stored in a `<vol>/crop/` subdirectory to distinguish
  them from `<vol>/rotated/` aligned versions.
- Add `level_file_path` utility to abstract file discovery across legacy
  (top-level) and new (crop-based) directory structures.
- Enhance `seg_bone` to capture and export bounding box metadata
  (`bbox2`, `nn_bbox`, `bbox_orig`) into `transform.json`.
- Implement `xfr_cbt_native.py` for mapping screw positions back to
  original CT space.
- Update preprocessing and visualization scripts to support the new
  directory layout and transformation metadata.
- Improve TinyDB metadata migration logic to prevent accidental corruption
  of existing database structures.
2026-09-09 13:39:47 +08:00

47 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import numpy as np
import nibabel as nib
def standardize_affine(file_path, output_dir):
"""翻轉 affine 對角為負的軸(資料 flip + 平移修正)後重寫同目錄同名檔。
回傳:實際翻轉的軸 index list未翻為 []。呼叫端transform 記錄)
需要這份 ground truth反 index 鏈路用「N-1-i」鏡射補回翻軸。"""
img = nib.load(file_path)
data = img.get_fdata()
affine = img.affine.copy()
# 初始化翻轉軸
flip_axes = []
# 檢查 X 軸方向
if affine[0, 0] < 0:
flip_axes.append(0)
affine[0, 0] *= -1
affine[0, 3] *= -1 # 修正平移部分
# 檢查 Y 軸方向
if affine[1, 1] < 0:
flip_axes.append(1)
affine[1, 1] *= -1
affine[1, 3] *= -1 # 修正平移部分
# 檢查 Z 軸方向
if affine[2, 2] < 0:
flip_axes.append(2)
affine[2, 2] *= -1
affine[2, 3] *= -1 # 修正平移部分
# 翻轉數據(如果需要)
if flip_axes:
data = np.flip(data, axis=tuple(flip_axes))
# 保存修正後的影像
standardized_img = nib.Nifti1Image(data, affine)
output_path = os.path.join(output_dir, os.path.basename(file_path))
os.makedirs(os.path.dirname(output_path), exist_ok=True)
nib.save(standardized_img, output_path)
return flip_axes