|
23 | 23 | spnd, _, _ = optional_package('scipy.ndimage')
|
24 | 24 |
|
25 | 25 | from .affines import AffineError, to_matvec, from_matvec, append_diag
|
| 26 | +from .funcs import as_closest_canonical |
26 | 27 | from .spaces import vox2out_vox
|
27 |
| -from .nifti1 import Nifti1Image |
| 28 | +from .nifti1 import Nifti1Header, Nifti1Image |
28 | 29 | from .imageclasses import spatial_axes_first
|
29 | 30 |
|
30 | 31 | SIGMA2FWHM = np.sqrt(8 * np.log(2))
|
@@ -311,3 +312,31 @@ def smooth_image(img,
|
311 | 312 | mode=mode,
|
312 | 313 | cval=cval)
|
313 | 314 | return out_class(sm_data, img.affine, img.header)
|
| 315 | + |
| 316 | + |
| 317 | +def _transform_range(x, new_min, new_max): |
| 318 | + x = np.asarray(x) |
| 319 | + x_min, x_max = x.min(), x.max() |
| 320 | + return (((x - x_min) * (new_max - new_min)) / (x_max - x_min)) + new_min |
| 321 | + |
| 322 | + |
| 323 | +def conform(from_img, out_shape=(256, 256, 256), |
| 324 | + voxel_size=(1.0, 1.0, 1.0), order=3, cval=0.0, out_class=Nifti1Image): |
| 325 | + # Create fake image of the image we want to resample to. |
| 326 | + hdr = Nifti1Header() |
| 327 | + hdr.set_data_shape(out_shape) |
| 328 | + hdr.set_zooms(voxel_size) |
| 329 | + dst_aff = hdr.get_best_affine() |
| 330 | + to_img = Nifti1Image(np.empty(out_shape), affine=dst_aff, header=hdr) |
| 331 | + # Resample input image. |
| 332 | + out_img = resample_from_to( |
| 333 | + from_img=from_img, to_vox_map=to_img, order=order, mode="constant", cval=cval, out_class=out_class) |
| 334 | + # Cast to uint8. |
| 335 | + data = out_img.get_fdata() |
| 336 | + data = _transform_range(data, new_min=0.0, new_max=255.0) |
| 337 | + data = data.round(out=data).astype(np.uint8) |
| 338 | + out_img._dataobj = data |
| 339 | + out_img.set_data_dtype(data.dtype) |
| 340 | + # Reorient to RAS. |
| 341 | + out_img = as_closest_canonical(out_img) |
| 342 | + return out_img |
0 commit comments