def image_filter_wrapper(*args, **kwargs): have_array_input = False have_xarray_input = False args_list = list(args) for index, arg in enumerate(args): if _HAVE_XARRAY and isinstance(arg, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(arg) args_list[index] = image elif is_arraylike(arg): have_array_input = True array = np.asarray(arg) image = itk.image_view_from_array(array) args_list[index] = image potential_image_input_kwargs = ('input', 'input1', 'input2', 'input3') for key, value in kwargs.items(): if (key.lower() in potential_image_input_kwargs or "image" in key.lower()): if _HAVE_XARRAY and isinstance(value, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(value) kwargs[key] = image elif is_arraylike(value): have_array_input = True array = np.asarray(value) image = itk.image_view_from_array(array) kwargs[key] = image if have_xarray_input or have_array_input: # Convert output itk.Image's to numpy.ndarray's output = image_filter(*tuple(args_list), **kwargs) if isinstance(output, tuple): output_list = list(output) for index, value in output_list: if isinstance(value, itk.Image): if have_xarray_input: data_array = itk.xarray_from_image(value) output_list[index] = data_array else: array = itk.array_from_image(value) output_list[index] = array return tuple(output_list) else: if isinstance(output, itk.Image): if have_xarray_input: output = itk.xarray_from_image(output) else: output = itk.array_from_image(output) return output else: return image_filter(*args, **kwargs)
def nifti_to_zarr_ngff(nifti_file: str) -> str: """Convert the nifti file on disk to a Zarr NGFF store. The Zarr store will have the same path with '.zarr' appended. If the store already exists, it will not be re-created. """ import itk import spatial_image_multiscale import spatial_image_ngff import zarr store_path = convert_to_store_path(nifti_file) if store_path.exists(): return store_path image = itk.imread(str(nifti_file)) da = itk.xarray_from_image(image) da.name = 'image' scale_factors = [2, 2, 2, 2] multiscale = spatial_image_multiscale.to_multiscale(da, scale_factors) store_path = Path(str(nifti_file) + '.zarr') store = zarr.NestedDirectoryStore(str(nifti_file) + '.zarr') spatial_image_ngff.imwrite(multiscale, store) # celery tasks must return a serializable type; using string here return str(store_path)
def nifti_to_zarr_ngff(nifti_file: Union[str, Path]) -> Path: """Convert the nifti file on disk to a Zarr NGFF store. The Zarr store will have the same path with '.zarr' appended. If the store already exists, it will not be re-created. """ store_path = Path(str(nifti_file) + '.zarr') if store_path.exists(): return store_path image = itk.imread(str(nifti_file)) da = itk.xarray_from_image(image) da.name = 'image' scale_factors = [2, 2, 2, 2] multiscale = spatial_image_multiscale.to_multiscale(da, scale_factors) store_path = Path(str(nifti_file) + '.zarr') store = zarr.NestedDirectoryStore(str(nifti_file) + '.zarr') spatial_image_ngff.imwrite(multiscale, store) return store_path
# xarray conversion try: import xarray as xr print("Testing xarray conversion") image = itk.imread(filename) image.SetSpacing((0.1, 0.2)) image.SetOrigin((30.0, 44.0)) theta = np.radians(30) cosine = np.cos(theta) sine = np.sin(theta) rotation = np.array(((cosine, -sine), (sine, cosine))) image.SetDirection(rotation) data_array = itk.xarray_from_image(image) assert data_array.dims[0] == "y" assert data_array.dims[1] == "x" assert data_array.dims[2] == "c" assert np.array_equal(data_array.values, itk.array_from_image(image)) assert len(data_array.coords["x"]) == 256 assert len(data_array.coords["y"]) == 256 assert len(data_array.coords["c"]) == 3 assert data_array.coords["x"][0] == 30.0 assert data_array.coords["x"][1] == 30.1 assert data_array.coords["y"][0] == 44.0 assert data_array.coords["y"][1] == 44.2 assert data_array.coords["c"][0] == 0 assert data_array.coords["c"][1] == 1 assert data_array.attrs["direction"][0, 0] == cosine assert data_array.attrs["direction"][0, 1] == sine
# xarray conversion try: import xarray as xr import numpy as np print('Testing xarray conversion') image = itk.imread(filename) image.SetSpacing((0.1, 0.2)) image.SetOrigin((30., 44.)) theta = np.radians(30) cosine = np.cos(theta) sine = np.sin(theta) rotation = np.array(((cosine, -sine), (sine, cosine))) image.SetDirection(rotation) data_array = itk.xarray_from_image(image) assert data_array.dims[0] == 'y' assert data_array.dims[1] == 'x' assert data_array.dims[2] == 'c' assert np.array_equal(data_array.values, itk.array_from_image(image)) assert len(data_array.coords['x']) == 256 assert len(data_array.coords['y']) == 256 assert len(data_array.coords['c']) == 3 assert data_array.coords['x'][0] == 30.0 assert data_array.coords['x'][1] == 30.1 assert data_array.coords['y'][0] == 44.0 assert data_array.coords['y'][1] == 44.2 assert data_array.coords['c'][0] == 0 assert data_array.coords['c'][1] == 1 assert data_array.attrs['direction'][0, 0] == cosine assert data_array.attrs['direction'][0, 1] == sine
added = itk.add_image_filter(array1, array2) assert isinstance(added, np.ndarray) assert np.all(added == 3) added = itk.add_image_filter(Input1=array1, Input2=array2) assert isinstance(added, np.ndarray) assert np.all(added == 3) # support kwargs with "image" in the name masked = itk.mask_image_filter(array1, mask_image=array2) try: import xarray as xr image1 = itk.image_from_array(array1) data_array1 = itk.xarray_from_image(image1) image2 = itk.image_from_array(array2) data_array2 = itk.xarray_from_image(image2) added = itk.add_image_filter(data_array1, data_array2) assert isinstance(added, xr.DataArray) assert np.all(added == 3) added = itk.add_image_filter(Input1=data_array1, Input2=data_array2) assert isinstance(added, xr.DataArray) assert np.all(added == 3) # support kwargs with "image" in the name masked = itk.mask_image_filter(data_array1, mask_image=data_array2) except ImportError: # Could not import xarray
def image_filter_wrapper(*args, **kwargs): have_array_input = False have_xarray_input = False have_torch_input = False args_list = list(args) for index, arg in enumerate(args): if _HAVE_XARRAY and isinstance(arg, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(arg) args_list[index] = image elif _HAVE_TORCH and isinstance(arg, torch.Tensor): have_torch_input = True image = itk.image_view_from_array(np.asarray(arg)) args_list[index] = image elif not isinstance(arg, itk.Object) and is_arraylike(arg): have_array_input = True array = np.asarray(arg) image = itk.image_view_from_array(array) args_list[index] = image potential_image_input_kwargs = ("input", "input1", "input2", "input3") for key, value in kwargs.items(): if key.lower( ) in potential_image_input_kwargs or "image" in key.lower(): if _HAVE_XARRAY and isinstance(value, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(value) kwargs[key] = image elif _HAVE_TORCH and isinstance(value, torch.Tensor): have_torch_input = True image = itk.image_view_from_array(np.asarray(value)) kwargs[key] = image elif not isinstance(value, itk.Object) and is_arraylike(value): have_array_input = True array = np.asarray(value) image = itk.image_view_from_array(array) kwargs[key] = image if have_xarray_input or have_torch_input or have_array_input: # Convert output itk.Image's to numpy.ndarray's output = image_filter(*tuple(args_list), **kwargs) if isinstance(output, tuple): output_list = list(output) for index, value in enumerate(output_list): if isinstance(value, itk.Image): if have_xarray_input: data_array = itk.xarray_from_image(value) output_list[index] = data_array elif have_torch_input: data_array = itk.array_view_from_image(value) torch_tensor = torch.from_numpy(data_array) output_list[index] = torch_tensor else: array = itk.array_view_from_image(value) output_list[index] = array return tuple(output_list) else: if isinstance(output, itk.Image): if have_xarray_input: output = itk.xarray_from_image(output) elif have_torch_input: output = itk.array_view_from_image(output) output = torch.from_numpy(output) else: output = itk.array_view_from_image(output) return output else: return image_filter(*args, **kwargs)
def image_filter_wrapper(*args, **kwargs): have_array_input = False have_xarray_input = False have_torch_input = False args_list = list(args) for index, arg in enumerate(args): if _HAVE_XARRAY and isinstance(arg, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(arg) args_list[index] = image elif _HAVE_TORCH and isinstance(arg, torch.Tensor): have_torch_input = True channels = arg.shape[0] # assume first dimension is channels arr = np.asarray(arg) if channels > 1: # change from contiguous to interleaved channel order arr = move_last_dimension_to_first(arr) image = itk.image_view_from_array(arr, is_vector=channels > 1) args_list[index] = image elif not isinstance(arg, itk.Object) and is_arraylike(arg): have_array_input = True array = np.asarray(arg) image = itk.image_view_from_array(array) args_list[index] = image potential_image_input_kwargs = ("input", "input1", "input2", "input3") for key, value in kwargs.items(): if key.lower( ) in potential_image_input_kwargs or "image" in key.lower(): if _HAVE_XARRAY and isinstance(value, xr.DataArray): have_xarray_input = True image = itk.image_from_xarray(value) kwargs[key] = image elif _HAVE_TORCH and isinstance(value, torch.Tensor): have_torch_input = True channels = value.shape[ 0] # assume first dimension is channels arr = np.asarray(value) if ( channels > 1 ): # change from contiguous to interleaved channel order arr = move_last_dimension_to_first(arr) image = itk.image_view_from_array(arr, is_vector=channels > 1) kwargs[key] = image elif not isinstance(value, itk.Object) and is_arraylike(value): have_array_input = True array = np.asarray(value) image = itk.image_view_from_array(array) kwargs[key] = image if have_xarray_input or have_torch_input or have_array_input: # Convert output itk.Image's to numpy.ndarray's output = image_filter(*tuple(args_list), **kwargs) if isinstance(output, tuple): output_list = list(output) for index, value in enumerate(output_list): if isinstance(value, itk.Image): if have_xarray_input: data_array = itk.xarray_from_image(value) output_list[index] = data_array elif have_torch_input: channels = value.GetNumberOfComponentsPerPixel() data_array = itk.array_view_from_image(value) if ( channels > 1 ): # change from interleaved to contiguous channel order data_array = move_first_dimension_to_last( data_array) torch_tensor = torch.from_numpy(data_array) output_list[index] = torch_tensor else: array = itk.array_view_from_image(value) output_list[index] = array return tuple(output_list) else: if isinstance(output, itk.Image): if have_xarray_input: output = itk.xarray_from_image(output) elif have_torch_input: channels = output.GetNumberOfComponentsPerPixel() output = itk.array_view_from_image(output) if ( channels > 1 ): # change from interleaved to contiguous channel order output = move_first_dimension_to_last(output) output = torch.from_numpy(output) else: output = itk.array_view_from_image(output) return output else: return image_filter(*args, **kwargs)