Python numpy.uint16() Examples
The following are 30
code examples of numpy.uint16().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: gac.py From openISP with MIT License | 7 votes |
def execute(self): img_h = self.img.shape[0] img_w = self.img.shape[1] img_c = self.img.shape[2] gc_img = np.empty((img_h, img_w, img_c), np.uint16) for y in range(self.img.shape[0]): for x in range(self.img.shape[1]): if self.mode == 'rgb': gc_img[y, x, 0] = self.lut[self.img[y, x, 0]] gc_img[y, x, 1] = self.lut[self.img[y, x, 1]] gc_img[y, x, 2] = self.lut[self.img[y, x, 2]] gc_img[y, x, :] = gc_img[y, x, :] / 4 elif self.mode == 'yuv': gc_img[y, x, 0] = self.lut[0][self.img[y, x, 0]] gc_img[y, x, 1] = self.lut[1][self.img[y, x, 1]] gc_img[y, x, 2] = self.lut[1][self.img[y, x, 2]] self.img = gc_img return self.img
Example #2
Source File: longtermmean.py From yatsm with MIT License | 6 votes |
def ordinal2yeardoy(ordinal): """ Convert ordinal dates to two arrays of year and doy Args: ordinal (np.ndarray): ordinal dates Returns: np.ndarray: nobs x 2 np.ndarray containing the year and DOY for each ordinal date """ _date = [dt.fromordinal(_d) for _d in ordinal] yeardoy = np.empty((ordinal.size, 2), dtype=np.uint16) yeardoy[:, 0] = np.array([int(_d.strftime('%Y')) for _d in _date]) yeardoy[:, 1] = np.array([int(_d.strftime('%j')) for _d in _date]) return yeardoy
Example #3
Source File: aaf.py From openISP with MIT License | 6 votes |
def execute(self): img_pad = self.padding() raw_h = self.img.shape[0] raw_w = self.img.shape[1] aaf_img = np.empty((raw_h, raw_w), np.uint16) for y in range(img_pad.shape[0] - 4): for x in range(img_pad.shape[1] - 4): p0 = img_pad[y + 2, x + 2] p1 = img_pad[y, x] p2 = img_pad[y, x + 2] p3 = img_pad[y, x + 4] p4 = img_pad[y + 2, x] p5 = img_pad[y + 2, x + 4] p6 = img_pad[y + 4, x] p7 = img_pad[y + 4, x + 2] p8 = img_pad[y + 4, x + 4] aaf_img[y, x] = (p0 * 8 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8) / 16 self.img = aaf_img return self.img
Example #4
Source File: nlm.py From openISP with MIT License | 6 votes |
def execute(self): img_pad = self.padding() img_pad = img_pad.astype(np.uint16) raw_h = self.img.shape[0] raw_w = self.img.shape[1] nlm_img = np.empty((raw_h, raw_w), np.uint16) kernel = np.ones((2*self.ds+1, 2*self.ds+1)) / pow(2*self.ds+1, 2) for y in range(img_pad.shape[0] - 2 * self.Ds): for x in range(img_pad.shape[1] - 2 * self.Ds): center_y = y + self.Ds center_x = x + self.Ds sweight, average, wmax = self.calWeights(img_pad, kernel, center_y, center_x) average = average + wmax * img_pad[center_y, center_x] sweight = sweight + wmax nlm_img[y,x] = average / sweight self.img = nlm_img return self.clipping()
Example #5
Source File: kimotion.py From BiblioPixelAnimations with MIT License | 6 votes |
def __init__(self, server): super().__init__() self.setDaemon(True) self._stop = threading.Event() self._reading = thread_lock() self.dt = np.dtype(np.uint16) self.dt = self.dt.newbyteorder('<') self._data = [np.zeros(WS_FRAME_SIZE, self.dt), np.zeros(WS_FRAME_SIZE, self.dt)] self._buf = False self.ws = create_connection("ws://{}/".format(server))
Example #6
Source File: test_half.py From recruit with Apache License 2.0 | 6 votes |
def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits): # Test specifically that all bits are considered when deciding # whether round to even should occur (i.e. no bits are lost at the # end. Compare also gh-12721. The most bits can get lost for the # smallest denormal: smallest_value = np.uint16(1).view(np.float16).astype(float_t) assert smallest_value == 2**-24 # Will be rounded to zero based on round to even rule: rounded_to_zero = smallest_value / float_t(2) assert rounded_to_zero.astype(np.float16) == 0 # The significand will be all 0 for the float_t, test that we do not # lose the lower ones of these: for i in range(bits): # slightly increasing the value should make it round up: larger_pattern = rounded_to_zero.view(uint_t) | uint_t(1 << i) larger_value = larger_pattern.view(float_t) assert larger_value.astype(np.float16) == smallest_value
Example #7
Source File: test_function_base.py From recruit with Apache License 2.0 | 6 votes |
def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [np.int16, np.uint16, np.int32, np.uint32, np.float32, np.float64, np.complex64, np.complex128]: a = np.array(ba, ctype) a2 = np.array(ba2, ctype) if ctype in ['1', 'b']: assert_raises(ArithmeticError, np.cumprod, a) assert_raises(ArithmeticError, np.cumprod, a2, 1) assert_raises(ArithmeticError, np.cumprod, a) else: assert_array_equal(np.cumprod(a, axis=-1), np.array([1, 2, 20, 220, 1320, 6600, 26400], ctype)) assert_array_equal(np.cumprod(a2, axis=0), np.array([[1, 2, 3, 4], [5, 12, 21, 36], [50, 36, 84, 180]], ctype)) assert_array_equal(np.cumprod(a2, axis=-1), np.array([[1, 2, 6, 24], [5, 30, 210, 1890], [10, 30, 120, 600]], ctype))
Example #8
Source File: test_ecat.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_subheader(self): assert_equal(self.subhdr.get_shape() , (10,10,3)) assert_equal(self.subhdr.get_nframes() , 1) assert_equal(self.subhdr.get_nframes(), len(self.subhdr.subheaders)) assert_equal(self.subhdr._check_affines(), True) assert_array_almost_equal(np.diag(self.subhdr.get_frame_affine()), np.array([ 2.20241979, 2.20241979, 3.125, 1.])) assert_equal(self.subhdr.get_zooms()[0], 2.20241978764534) assert_equal(self.subhdr.get_zooms()[2], 3.125) assert_equal(self.subhdr._get_data_dtype(0),np.uint16) #assert_equal(self.subhdr._get_frame_offset(), 1024) assert_equal(self.subhdr._get_frame_offset(), 1536) dat = self.subhdr.raw_data_from_fileobj() assert_equal(dat.shape, self.subhdr.get_shape()) scale_factor = self.subhdr.subheaders[0]['scale_factor'] assert_equal(self.subhdr.subheaders[0]['scale_factor'].item(),1.0) ecat_calib_factor = self.hdr['ecat_calibration_factor'] assert_equal(ecat_calib_factor, 25007614.0)
Example #9
Source File: test_casting.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_able_int_type(): # The integer type cabable of containing values for vals, exp_out in ( ([0, 1], np.uint8), ([0, 255], np.uint8), ([-1, 1], np.int8), ([0, 256], np.uint16), ([-1, 128], np.int16), ([0.1, 1], None), ([0, 2**16], np.uint32), ([-1, 2**15], np.int32), ([0, 2**32], np.uint64), ([-1, 2**31], np.int64), ([-1, 2**64-1], None), ([0, 2**64-1], np.uint64), ([0, 2**64], None)): assert_equal(able_int_type(vals), exp_out)
Example #10
Source File: test_utils.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def test_can_cast(): tests = ((np.float32, np.float32, True, True, True), (np.float64, np.float32, True, True, True), (np.complex128, np.float32, False, False, False), (np.float32, np.complex128, True, True, True), (np.float32, np.uint8, False, True, True), (np.uint32, np.complex128, True, True, True), (np.int64, np.float32, True, True, True), (np.complex128, np.int16, False, False, False), (np.float32, np.int16, False, True, True), (np.uint8, np.int16, True, True, True), (np.uint16, np.int16, False, True, True), (np.int16, np.uint16, False, False, True), (np.int8, np.uint16, False, False, True), (np.uint16, np.uint8, False, True, True), ) for intype, outtype, def_res, scale_res, all_res in tests: assert_equal(def_res, can_cast(intype, outtype)) assert_equal(scale_res, can_cast(intype, outtype, False, True)) assert_equal(all_res, can_cast(intype, outtype, True, True))
Example #11
Source File: time_stack.py From radiometric_normalization with Apache License 2.0 | 6 votes |
def _uniform_weight_alpha(sum_masked_arrays, output_datatype): '''Calculates the cumulative mask of a list of masked array Input: sum_masked_arrays (list of numpy masked arrays): The list of masked arrays to find the cumulative mask of, each element represents one band. (sums_masked_array.mask has a 1 for a no data pixel and a 0 otherwise) output_datatype (numpy datatype): The output datatype Output: output_alpha (numpy uint16 array): The output mask (0 for a no data pixel, uint16 max value otherwise) ''' output_alpha = numpy.ones(sum_masked_arrays[0].shape) for band_sum_masked_array in sum_masked_arrays: output_alpha[numpy.nonzero(band_sum_masked_array.mask == 1)] = 0 output_alpha = output_alpha.astype(output_datatype) * \ numpy.iinfo(output_datatype).max return output_alpha
Example #12
Source File: test_function_base.py From recruit with Apache License 2.0 | 6 votes |
def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.float32, np.float64, np.complex64, np.complex128]: a = np.array(ba, ctype) a2 = np.array(ba2, ctype) tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype) assert_array_equal(np.cumsum(a, axis=0), tgt) tgt = np.array( [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype) assert_array_equal(np.cumsum(a2, axis=0), tgt) tgt = np.array( [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype) assert_array_equal(np.cumsum(a2, axis=1), tgt)
Example #13
Source File: test_ctypeslib.py From recruit with Apache License 2.0 | 6 votes |
def test_padded_union(self): dt = np.dtype(dict( names=['a', 'b'], offsets=[0, 0], formats=[np.uint16, np.uint32], itemsize=5, )) ct = np.ctypeslib.as_ctypes_type(dt) assert_(issubclass(ct, ctypes.Union)) assert_equal(ctypes.sizeof(ct), dt.itemsize) assert_equal(ct._fields_, [ ('a', ctypes.c_uint16), ('b', ctypes.c_uint32), ('', ctypes.c_char * 5), # padding ])
Example #14
Source File: gimage_tests.py From radiometric_normalization with Apache License 2.0 | 6 votes |
def test_save_with_compress(self): output_file = 'test_save_with_compress.tif' test_band = numpy.array([[5, 2, 2], [1, 6, 8]], dtype=numpy.uint16) test_alpha = numpy.array([[0, 0, 0], [1, 1, 1]], dtype=numpy.bool) test_gimage = gimage.GImage([test_band, test_band, test_band], test_alpha, self.metadata) gimage.save(test_gimage, output_file, compress=True) result_gimg = gimage.load(output_file) numpy.testing.assert_array_equal(result_gimg.bands[0], test_band) numpy.testing.assert_array_equal(result_gimg.bands[1], test_band) numpy.testing.assert_array_equal(result_gimg.bands[2], test_band) numpy.testing.assert_array_equal(result_gimg.alpha, test_alpha) self.assertEqual(result_gimg.metadata, self.metadata) os.unlink(output_file)
Example #15
Source File: hmutils.py From simnibs with GNU General Public License v3.0 | 6 votes |
def format_time(running_time): """Format time in seconds as hours:minutes:seconds. PARAMETERS ---------- running_time : float Time in seconds. RETURNS ---------- running_time : str The time formatted as hours:minutes:seconds. """ hrs = np.uint16(np.floor(running_time/(60.**2))) mts = np.uint16(np.floor(running_time/60.-hrs*60)) sec = np.uint16(np.round(running_time-hrs*60.**2-mts*60.)) return "{:02d}:{:02d}:{:02d}".format(hrs,mts,sec)
Example #16
Source File: normalize.py From radiometric_normalization with Apache License 2.0 | 6 votes |
def apply_using_lut(input_band, transformation): '''Applies a linear transformation to an array using a look up table. This creates a uint16 array as the output and clips the output band to the range of a uint16. :param array input_band: A 2D array representing the image data of the a single band :param LinearTransformation transformation: A LinearTransformation (gain and offset) :returns: A 2D array of of the input_band with the transformation applied ''' logging.info('Normalize: Applying linear transformation to band (uint16)') def _apply_lut(band, lut): '''Changes band intensity values based on intensity look up table (lut) ''' if lut.dtype != band.dtype: raise Exception( 'Band ({}) and lut ({}) must be the same data type.').format( band.dtype, lut.dtype) return numpy.take(lut, band, mode='clip') lut = _linear_transformation_to_lut(transformation) return _apply_lut(input_band, lut)
Example #17
Source File: util.py From exposure with MIT License | 6 votes |
def read_tiff16(fn): import tifffile import numpy as np img = tifffile.imread(fn) if img.dtype == np.uint8: depth = 8 elif img.dtype == np.uint16: depth = 16 else: print("Warning: unsupported data type {}. Assuming 16-bit.", img.dtype) depth = 16 return (img * (1.0 / (2**depth - 1))).astype(np.float32)
Example #18
Source File: model.py From modelforge with Apache License 2.0 | 6 votes |
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray: """Return a copy of an integer numpy array with the minimum bitness.""" assert arr.dtype.kind in ("i", "u") if arr.size == 0: return arr if arr.dtype.kind == "i": assert arr.min() >= 0 mlbl = int(arr.max()).bit_length() if mlbl <= 8: dtype = numpy.uint8 elif mlbl <= 16: dtype = numpy.uint16 elif mlbl <= 32: dtype = numpy.uint32 else: dtype = numpy.uint64 return arr.astype(dtype)
Example #19
Source File: longtermmean.py From yatsm with MIT License | 6 votes |
def group_years(years, interval=3): """ Return integers representing sequential groupings of years Note: years specified must be sorted Args: years (np.ndarray): the year corresponding to each EVI value interval (int, optional): number of years to group together (default: 3) Returns: np.ndarray: integers representing sequential year groupings """ n_groups = math.ceil((years.max() - years.min()) / interval) if n_groups <= 1: return np.zeros_like(years, dtype=np.uint16) splits = np.array_split(np.arange(years.min(), years.max() + 1), n_groups) groups = np.zeros_like(years, dtype=np.uint16) for i, s in enumerate(splits): groups[np.in1d(years, s)] = i return groups
Example #20
Source File: test_half.py From recruit with Apache License 2.0 | 6 votes |
def test_half_values(self): """Confirms a small number of known half values""" a = np.array([1.0, -1.0, 2.0, -2.0, 0.0999755859375, 0.333251953125, # 1/10, 1/3 65504, -65504, # Maximum magnitude 2.0**(-14), -2.0**(-14), # Minimum normal 2.0**(-24), -2.0**(-24), # Minimum subnormal 0, -1/1e1000, # Signed zeros np.inf, -np.inf]) b = np.array([0x3c00, 0xbc00, 0x4000, 0xc000, 0x2e66, 0x3555, 0x7bff, 0xfbff, 0x0400, 0x8400, 0x0001, 0x8001, 0x0000, 0x8000, 0x7c00, 0xfc00], dtype=uint16) b.dtype = float16 assert_equal(a, b)
Example #21
Source File: gimage_tests.py From radiometric_normalization with Apache License 2.0 | 5 votes |
def setUp(self): self.band = numpy.array([[0, 1], [2, 3]], dtype=numpy.uint16) self.mask = numpy.array([[0, 1], [0, 1]], dtype=numpy.bool) self.metadata = {'geotransform': (-1.0, 2.0, 0.0, 1.0, 0.0, -1.0)} self.test_photometric_alpha_image = 'test_photometric_alpha_image.tif' test_ds = gdal.GetDriverByName('GTiff').Create( self.test_photometric_alpha_image, 2, 2, 4, gdal.GDT_UInt16, options=['PHOTOMETRIC=RGB', 'ALPHA=YES']) gdal_array.BandWriteArray(test_ds.GetRasterBand(1), self.band) gdal_array.BandWriteArray(test_ds.GetRasterBand(2), self.band) gdal_array.BandWriteArray(test_ds.GetRasterBand(3), self.band) gdal_array.BandWriteArray(test_ds.GetRasterBand(4), self.mask) test_ds.SetGeoTransform(self.metadata['geotransform'])
Example #22
Source File: gimage_tests.py From radiometric_normalization with Apache License 2.0 | 5 votes |
def test__nodata_to_mask(self): test_band = numpy.array([[0, 1, 2], [1, 2, 3]], dtype=numpy.uint16) test_mask = gimage._nodata_to_mask([test_band], 3) expected_mask = numpy.array([[1, 1, 1], [1, 1, 0]], dtype=numpy.uint16) numpy.testing.assert_array_equal(test_mask, expected_mask)
Example #23
Source File: test_half.py From recruit with Apache License 2.0 | 5 votes |
def test_half_conversions(self): """Checks that all 16-bit values survive conversion to/from 32-bit and 64-bit float""" # Because the underlying routines preserve the NaN bits, every # value is preserved when converting to/from other floats. # Convert from float32 back to float16 b = np.array(self.all_f32, dtype=float16) assert_equal(self.all_f16.view(dtype=uint16), b.view(dtype=uint16)) # Convert from float64 back to float16 b = np.array(self.all_f64, dtype=float16) assert_equal(self.all_f16.view(dtype=uint16), b.view(dtype=uint16)) # Convert float16 to longdouble and back # This doesn't necessarily preserve the extra NaN bits, # so exclude NaNs. a_ld = np.array(self.nonan_f16, dtype=np.longdouble) b = np.array(a_ld, dtype=float16) assert_equal(self.nonan_f16.view(dtype=uint16), b.view(dtype=uint16)) # Check the range for which all integers can be represented i_int = np.arange(-2048, 2049) i_f16 = np.array(i_int, dtype=float16) j = np.array(i_f16, dtype=int) assert_equal(i_int, j)
Example #24
Source File: test_index_tricks.py From recruit with Apache License 2.0 | 5 votes |
def test_dtypes(self): # Test with different data types for dtype in [np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64]: coords = np.array( [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype) shape = (5, 8) uncoords = 8*coords[0]+coords[1] assert_equal(np.ravel_multi_index(coords, shape), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape)) uncoords = coords[0]+5*coords[1] assert_equal( np.ravel_multi_index(coords, shape, order='F'), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) coords = np.array( [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]], dtype=dtype) shape = (5, 8, 10) uncoords = 10*(8*coords[0]+coords[1])+coords[2] assert_equal(np.ravel_multi_index(coords, shape), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape)) uncoords = coords[0]+5*(coords[1]+8*coords[2]) assert_equal( np.ravel_multi_index(coords, shape, order='F'), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape, order='F'))
Example #25
Source File: test_ctypeslib.py From recruit with Apache License 2.0 | 5 votes |
def test_union(self): dt = np.dtype(dict( names=['a', 'b'], offsets=[0, 0], formats=[np.uint16, np.uint32] )) ct = np.ctypeslib.as_ctypes_type(dt) assert_(issubclass(ct, ctypes.Union)) assert_equal(ctypes.sizeof(ct), dt.itemsize) assert_equal(ct._fields_, [ ('a', ctypes.c_uint16), ('b', ctypes.c_uint32), ])
Example #26
Source File: pascal_voc.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def _load_annotation(self, index): # store original annotation as orig_objs height, width, orig_objs = self._parse_voc_anno(self._image_anno_tmpl.format(index)) # filter difficult objects if not self._config['use_diff']: non_diff_objs = [obj for obj in orig_objs if obj['difficult'] == 0] objs = non_diff_objs else: objs = orig_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs,), dtype=np.int32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): # Make pixel indexes 0-based x1 = obj['bbox'][0] - 1 y1 = obj['bbox'][1] - 1 x2 = obj['bbox'][2] - 1 y2 = obj['bbox'][3] - 1 cls = self._class_to_ind[obj['name'].lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls roi_rec = {'index': index, 'objs': orig_objs, 'image': self._image_file_tmpl.format(index), 'height': height, 'width': width, 'boxes': boxes, 'gt_classes': gt_classes, 'flipped': False} return roi_rec
Example #27
Source File: gimage_tests.py From radiometric_normalization with Apache License 2.0 | 5 votes |
def test__save_to_ds(self): output_file = 'test_save_to_ds.tif' test_band = numpy.array([[0, 1], [2, 3]], dtype=numpy.uint16) test_gimage = gimage.GImage([test_band], self.mask, self.metadata) output_ds = gdal.GetDriverByName('GTiff').Create( output_file, 2, 2, 2, gdal.GDT_UInt16, options=['ALPHA=YES']) gimage._save_to_ds(test_gimage, output_ds, nodata=3) # Required for gdal to write to file output_ds = None test_ds = gdal.Open(output_file) saved_number_of_bands = test_ds.RasterCount self.assertEquals(saved_number_of_bands, 2) saved_band = test_ds.GetRasterBand(1).ReadAsArray() numpy.testing.assert_array_equal(saved_band, self.band) saved_nodata = test_ds.GetRasterBand(1).GetNoDataValue() self.assertEqual(saved_nodata, 3) saved_alpha = test_ds.GetRasterBand(2).ReadAsArray() numpy.testing.assert_array_equal(saved_alpha, self.mask * 255) os.unlink(output_file)
Example #28
Source File: test_ctypeslib.py From recruit with Apache License 2.0 | 5 votes |
def test_structure_aligned(self): dt = np.dtype([ ('a', np.uint16), ('b', np.uint32), ], align=True) ct = np.ctypeslib.as_ctypes_type(dt) assert_(issubclass(ct, ctypes.Structure)) assert_equal(ctypes.sizeof(ct), dt.itemsize) assert_equal(ct._fields_, [ ('a', ctypes.c_uint16), ('', ctypes.c_char * 2), # padding ('b', ctypes.c_uint32), ])
Example #29
Source File: env.py From vergeml with MIT License | 5 votes |
def _toscalar(v): if isinstance(v, (np.float16, np.float32, np.float64, np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64)): return np.asscalar(v) else: return v
Example #30
Source File: hmutils.py From simnibs with GNU General Public License v3.0 | 5 votes |
def write_ref_fs(vol): """Write a FreeSurfer reference file to disk. If input format is LAS then output format is LIA (from LAS to LIA: x,-z,y). PARAMETERS ---------- vol : nibabel image object Reference volume from which the file is generated. The actual data of the volume is not important. RETURNS ---------- Write the file "ref_FS.nii.gz" to the same folder as vol. """ output_dir = os.path.dirname(vol.get_filename()) data = np.transpose(np.zeros_like(vol.get_data()),(0,2,1)) # alternatively, if we wanted to write out the data #data = np.transpose(vol.get_data(),(0,2,1))[:,::-1,:] affine = vol.affine[[0,2,1,3]]*np.array([1,1,-1,1])[:,np.newaxis] vx = get_vx_size(vol) dim = vol.shape affine = np.array([[-vx[0], 0 , 0 , vx[0]*dim[0]/2.], [ 0 , 0 , vx[1], -vx[1]*dim[1]/2.], [ 0 , -vx[2], 0 , vx[2]*dim[2]/2.], [ 0 , 0 , 0 , 1]]) ref = nib.Nifti1Image(data.astype(np.uint16),affine) ref.set_qform(affine) ref.header.set_xyzt_units(*vol.header.get_xyzt_units()) nib.save(ref, os.path.join(output_dir, "ref_FS.nii.gz"))