Buckets:
| """Preprocessing NCCT mentah (HU) -> input model Phase 3, sama dengan pipeline preprocessing tim. | |
| Urutan (sama dengan extract.py + normalization.py + pipeline.py): | |
| 1. Orientasi kanonik (RAS) dengan nib.as_closest_canonical; mask ground truth ikut diputar. | |
| 2. Brain mask: TotalSegmentator (--roi_subset brain --fast), diresample ke grid NCCT kanonik. | |
| 3. Isi lubang per slice, lalu ring 2.5 mm di sekitar otak yang HU <= 200 ikut disimpan (keep mask). | |
| 4. Crop kotak keep mask, resample ke 256 x 256 per slice (gaussian anti-alias, linear; mask: nearest). | |
| Jumlah slice (Z) tidak berubah. Di luar keep mask = 0. | |
| 5. Windowing W80 / L40 (0..80 HU) -> skala 0..1. | |
| 6. Histogram equalization seluruh volume (nbins 256) di dalam keep mask (dataset *_he). | |
| 7. Di luar keep mask = 0. Mask ground truth = mask > 0 dan di dalam keep mask. | |
| Kalau TotalSegmentator tidak terpasang, brain mask bisa diunggah sendiri atau diperkirakan dari ambang HU | |
| (perkiraan kasar, BUKAN cara yang dipakai saat training). | |
| """ | |
| import gzip | |
| import os | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import warnings | |
| import nibabel as nib | |
| import numpy as np | |
| from nibabel.processing import resample_from_to | |
| from scipy import ndimage as ndi | |
| from skimage.exposure import equalize_hist | |
| # ------------------------------------------------------------------ config.py tim | |
| WINDOW = 80 | |
| LEVEL = 40 | |
| HE_NBINS = 256 | |
| HE_PER_SLICE = False | |
| BRAIN_DILATION_MM = 2.5 | |
| BONE_HU = 200.0 | |
| SIZE = 256 | |
| BRAIN_METHODS = { | |
| 'totalseg': 'TotalSegmentator (sama dengan training)', | |
| 'upload': 'Upload brain mask sendiri', | |
| 'approx': 'Perkiraan ambang HU (kasar)', | |
| } | |
| # ------------------------------------------------------------------ deteksi jenis input | |
| def looks_preprocessed(array): | |
| """True kalau volume tampak sudah terpreproses: 256 x 256 dan nilai di rentang 0..1.""" | |
| array = np.asarray(array) | |
| if array.ndim < 2 or array.shape[:2] != (SIZE, SIZE): | |
| return False | |
| finite = array[np.isfinite(array)] | |
| return finite.size > 0 and float(finite.min()) >= -0.01 and float(finite.max()) <= 1.01 | |
| def totalseg_available(): | |
| return shutil.which('TotalSegmentator') is not None | |
| def load_nifti_bytes(data): | |
| """Nifti1Image dari bytes (.nii / .nii.gz) tanpa file sementara.""" | |
| if data[:2] == b'\x1f\x8b': | |
| data = gzip.decompress(data) | |
| return nib.Nifti1Image.from_bytes(data) | |
| # ------------------------------------------------------------------ extract.py | |
| def resample(data, transform, binary): | |
| """Crop + resample per slice ke 256 x 256 (salinan extract.resample).""" | |
| data = np.asfortranarray(data) | |
| scale = np.diag(transform)[:2] | |
| gx = scale[0] * np.arange(SIZE) + transform[0, 3] | |
| gy = scale[1] * np.arange(SIZE) + transform[1, 3] | |
| inside = ((gx[:, None] >= -.5) & (gx[:, None] <= data.shape[0] - .5) | |
| & (gy[None, :] >= -.5) & (gy[None, :] <= data.shape[1] - .5)) | |
| result = np.empty((SIZE, SIZE, data.shape[2]), np.uint8 if binary else np.float32) | |
| sigma = np.maximum((scale - 1) / 2, 0) | |
| for z in range(data.shape[2]): | |
| plane = data[:, :, z].astype(result.dtype) | |
| if not binary and np.any(sigma > 0): | |
| plane = ndi.gaussian_filter(plane, sigma, mode='nearest') | |
| result[:, :, z] = ndi.affine_transform(plane, np.diag(scale), offset=transform[:2, 3], | |
| output_shape=(SIZE, SIZE), order=0 if binary else 1, | |
| mode='nearest', prefilter=False) | |
| result[:, :, z][~inside] = 0 | |
| return result | |
| def brain_totalseg(ct_bytes, reference, device='gpu'): | |
| """Brain mask TotalSegmentator di grid NCCT kanonik. Input = file NCCT asli (seperti extract.py).""" | |
| if not totalseg_available(): | |
| raise RuntimeError('TotalSegmentator tidak terpasang (pip install TotalSegmentator).') | |
| work = tempfile.mkdtemp(prefix='totalseg_') | |
| try: | |
| suffix = '.nii.gz' if ct_bytes[:2] == b'\x1f\x8b' else '.nii' | |
| ct_path = os.path.join(work, 'ncct' + suffix) | |
| seg_dir = os.path.join(work, 'seg') | |
| with open(ct_path, 'wb') as handle: | |
| handle.write(ct_bytes) | |
| cmd = ['TotalSegmentator', '-i', ct_path, '-o', seg_dir, '--roi_subset', 'brain', | |
| '--device', device, '--fast', '--quiet'] | |
| run = subprocess.run(cmd, capture_output=True, text=True) | |
| if run.returncode != 0: | |
| raise RuntimeError('TotalSegmentator gagal (kode %d): %s' | |
| % (run.returncode, (run.stderr or run.stdout)[-600:])) | |
| brain_img = nib.load(os.path.join(seg_dir, 'brain.nii.gz')) | |
| brain = resample_from_to(brain_img, (reference.shape, reference.affine), | |
| order=0, mode='constant', cval=0).get_fdata() > 0 | |
| del brain_img | |
| return brain | |
| finally: | |
| shutil.rmtree(work, ignore_errors=True) | |
| def brain_from_image(brain_img, reference): | |
| """Brain mask unggahan (grid apa pun) -> grid NCCT kanonik.""" | |
| return resample_from_to(brain_img, (reference.shape, reference.affine), | |
| order=0, mode='constant', cval=0).get_fdata() > 0 | |
| def brain_approx(ncct): | |
| """Perkiraan kasar: rongga di dalam tulang tengkorak dengan HU jaringan lunak, komponen 3D terbesar.""" | |
| bone = ncct > BONE_HU | |
| out = np.zeros(ncct.shape, dtype=bool) | |
| for z in range(ncct.shape[2]): | |
| closed = ndi.binary_closing(bone[:, :, z], iterations=3) | |
| inside = ndi.binary_fill_holes(closed) & ~closed | |
| out[:, :, z] = inside & (ncct[:, :, z] > -20) & (ncct[:, :, z] < 100) | |
| out = ndi.binary_opening(out, iterations=2) | |
| labels, count = ndi.label(out) | |
| if count == 0: | |
| return out | |
| sizes = ndi.sum(out, labels, range(1, count + 1)) | |
| return labels == (int(np.argmax(sizes)) + 1) | |
| # ------------------------------------------------------------------ normalization.py | |
| def histogram_equalization(volume, mask=None, nbins=HE_NBINS, per_slice=HE_PER_SLICE): | |
| arr = np.asarray(volume) | |
| mask = arr > 0.0 if mask is None else np.asarray(mask, dtype=bool) | |
| if not mask.any(): | |
| return arr.astype(np.float32, copy=True) | |
| if per_slice: | |
| out = np.empty(arr.shape, dtype=np.float32) | |
| for z in range(arr.shape[2]): | |
| m = mask[:, :, z] | |
| out[:, :, z] = equalize_hist(arr[:, :, z], nbins=nbins, mask=m) if m.any() else arr[:, :, z] | |
| return out | |
| return equalize_hist(arr, nbins=nbins, mask=mask).astype(np.float32) | |
| def normalize_ncct(ncct, keep_mask, he=True): | |
| min_hu, max_hu = LEVEL - WINDOW / 2, LEVEL + WINDOW / 2 | |
| out = (np.clip(ncct, min_hu, max_hu) - min_hu) / (max_hu - min_hu) | |
| if he: | |
| out = histogram_equalization(out, mask=keep_mask) | |
| out = np.asarray(out, dtype=np.float32).copy() | |
| out[~keep_mask] = 0.0 | |
| return out | |
| # ------------------------------------------------------------------ pipeline | |
| def preprocess_raw(ct_bytes, mask_bytes=None, brain_method='totalseg', brain_bytes=None, he=True, | |
| device='gpu', log=print): | |
| """NCCT mentah (bytes NIfTI, HU) -> dict siap model. | |
| Kembalian: ncct (256,256,Z) float32 0..1, mask (bool atau None), brain (keep mask, bool), affine, | |
| raw (NCCT kanonik dalam HU, untuk perbandingan), info (dict ringkas). | |
| """ | |
| base = load_nifti_bytes(ct_bytes) | |
| if len(base.shape) != 3: | |
| raise ValueError('NCCT mentah harus 3D, didapat bentuk %s' % (base.shape,)) | |
| reference = nib.as_closest_canonical(base) | |
| spacing = nib.affines.voxel_sizes(reference.affine) | |
| ncct = reference.get_fdata(dtype=np.float32) | |
| orientation = nib.orientations.ornt_transform(nib.io_orientation(base.affine), | |
| nib.io_orientation(reference.affine)) | |
| mask = None | |
| if mask_bytes is not None: | |
| mask_img = load_nifti_bytes(mask_bytes) | |
| if mask_img.shape[:3] != base.shape: | |
| raise ValueError('ukuran mask %s berbeda dengan NCCT %s' % (mask_img.shape, base.shape)) | |
| mask = nib.orientations.apply_orientation(np.asarray(mask_img.dataobj, dtype=np.float32), orientation) | |
| log('Brain mask: %s' % BRAIN_METHODS[brain_method]) | |
| if brain_method == 'totalseg': | |
| brain = brain_totalseg(ct_bytes, reference, device=device) | |
| elif brain_method == 'upload': | |
| if brain_bytes is None: | |
| raise ValueError('brain mask belum diunggah') | |
| brain = brain_from_image(load_nifti_bytes(brain_bytes), reference) | |
| else: | |
| brain = brain_approx(ncct) | |
| if not brain.any(): | |
| raise RuntimeError('brain mask kosong: otak tidak terdeteksi di NCCT ini') | |
| log('Keep mask (isi lubang + ring %.1f mm, HU <= %.0f)' % (BRAIN_DILATION_MM, BONE_HU)) | |
| filled = np.stack([ndi.binary_fill_holes(brain[:, :, z]) for z in range(brain.shape[2])], axis=2) | |
| ring = ndi.distance_transform_edt(~filled, sampling=spacing) <= BRAIN_DILATION_MM | |
| keep = filled | (ring & (ncct <= BONE_HU)) | |
| del ring, brain | |
| log('Crop + resample ke %d x %d' % (SIZE, SIZE)) | |
| xs, ys = np.where(np.any(keep, axis=2)) | |
| lo = np.array([xs.min(), ys.min()]) | |
| hi = np.array([xs.max() + 1, ys.max() + 1]) | |
| scale = np.max((hi - lo) * spacing[:2]) / (SIZE * spacing[:2]) | |
| transform = np.eye(4) | |
| transform[0, 0], transform[1, 1] = scale | |
| transform[:2, 3] = (lo + hi - 1) / 2 - scale * (SIZE - 1) / 2 | |
| affine = reference.affine @ transform | |
| keep_mask = resample(keep, transform, True) > 0 | |
| ncct_r = resample(ncct, transform, binary=False) | |
| ncct_r[~keep_mask] = 0 | |
| mask_r = None | |
| if mask is not None: | |
| mask_res = resample(mask, transform, binary=True) | |
| lost = np.flatnonzero(np.any(mask > 0, axis=(0, 1)) & ~np.any(mask_res, axis=(0, 1))).tolist() | |
| outside = int(((mask > 0) & ~keep).sum()) | |
| if lost or outside: | |
| warnings.warn('lesi terpotong: %d voxel di luar keep mask, slice hilang %s' % (outside, lost)) | |
| mask_r = keep_mask & (mask_res > 0) | |
| log('Windowing W%d/L%d + normalisasi 0..1%s' % (WINDOW, LEVEL, ' + histogram equalization' if he else '')) | |
| ncct_n = normalize_ncct(ncct_r, keep_mask, he=he) | |
| info = { | |
| 'shape_in': tuple(int(s) for s in base.shape), | |
| 'spacing_in': tuple(round(float(s), 3) for s in spacing), | |
| 'orientation_in': ''.join(nib.aff2axcodes(base.affine)), | |
| 'crop_scale': float(scale[0]), | |
| 'pixel_mm': tuple(round(float(s) * float(scale[0]), 3) for s in spacing[:2]), | |
| 'brain_method': brain_method, | |
| 'he': bool(he), | |
| 'keep_voxels': int(keep_mask.sum()), | |
| } | |
| return {'ncct': ncct_n, 'mask': mask_r, 'brain': keep_mask, 'affine': affine, 'raw': ncct, 'info': info} | |
Xet Storage Details
- Size:
- 10.7 kB
- Xet hash:
- 6c0123ceeb03aebc8a279d67c9a5e279b758ae2679b1c0bb304a2b1be4c0aa0d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.