Python numpy.int16() Examples
The following are 30 code examples for showing how to use numpy.int16(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: sklearn-audio-transfer-learning Author: jordipons File: utils.py License: ISC License | 6 votes |
def wavefile_to_waveform(wav_file, features_type): data, sr = sf.read(wav_file) if features_type == 'vggish': tmp_name = str(int(np.random.rand(1)*1000000)) + '.wav' sf.write(tmp_name, data, sr, subtype='PCM_16') sr, wav_data = wavfile.read(tmp_name) os.remove(tmp_name) # sr, wav_data = wavfile.read(wav_file) # as done in VGGish Audioset assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype data = wav_data / 32768.0 # Convert to [-1.0, +1.0] # at least one second of samples, if not repead-pad src_repeat = data while (src_repeat.shape[0] < sr): src_repeat = np.concatenate((src_repeat, data), axis=0) data = src_repeat[:sr] return data, sr
Example 2
Project: pyscf Author: pyscf File: numpy_helper.py License: Apache License 2.0 | 6 votes |
def frompointer(pointer, count, dtype=float): '''Interpret a buffer that the pointer refers to as a 1-dimensional array. Args: pointer : int or ctypes pointer address of a buffer count : int Number of items to read. dtype : data-type, optional Data-type of the returned array; default: float. Examples: >>> s = numpy.ones(3, dtype=numpy.int32) >>> ptr = s.ctypes.data >>> frompointer(ptr, count=6, dtype=numpy.int16) [1, 0, 1, 0, 1, 0] ''' dtype = numpy.dtype(dtype) count *= dtype.itemsize buf = (ctypes.c_char * count).from_address(pointer) a = numpy.ndarray(count, dtype=numpy.int8, buffer=buf) return a.view(dtype)
Example 3
Project: me-ica Author: ME-ICA File: test_arraywriters.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_no_offset_scale(): # Specific tests of no-offset scaling SAW = SlopeArrayWriter # Floating point for data in ((-128, 127), (-128, 126), (-128, -127), (-128, 0), (-128, -1), (126, 127), (-127, 127)): aw = SAW(np.array(data, dtype=np.float32), np.int8) assert_equal(aw.slope, 1.0) aw = SAW(np.array([-126, 127 * 2.0], dtype=np.float32), np.int8) assert_equal(aw.slope, 2) aw = SAW(np.array([-128 * 2.0, 127], dtype=np.float32), np.int8) assert_equal(aw.slope, 2) # Test that nasty abs behavior does not upset us n = -2**15 aw = SAW(np.array([n, n], dtype=np.int16), np.uint8) assert_array_almost_equal(aw.slope, n / 255.0, 5)
Example 4
Project: me-ica Author: ME-ICA File: test_arraywriters.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_writer_maker(): arr = np.arange(10, dtype=np.float64) aw = make_array_writer(arr, np.float64) assert_true(isinstance(aw, SlopeInterArrayWriter)) aw = make_array_writer(arr, np.float64, True, True) assert_true(isinstance(aw, SlopeInterArrayWriter)) aw = make_array_writer(arr, np.float64, True, False) assert_true(isinstance(aw, SlopeArrayWriter)) aw = make_array_writer(arr, np.float64, False, False) assert_true(isinstance(aw, ArrayWriter)) assert_raises(ValueError, make_array_writer, arr, np.float64, False) assert_raises(ValueError, make_array_writer, arr, np.float64, False, True) # Does calc_scale get run by default? aw = make_array_writer(arr, np.int16, calc_scale=False) assert_equal((aw.slope, aw.inter), (1, 0)) aw.calc_scale() slope, inter = aw.slope, aw.inter assert_false((slope, inter) == (1, 0)) # Should run by default aw = make_array_writer(arr, np.int16) assert_equal((aw.slope, aw.inter), (slope, inter)) aw = make_array_writer(arr, np.int16, calc_scale=True) assert_equal((aw.slope, aw.inter), (slope, inter))
Example 5
Project: me-ica Author: ME-ICA File: test_casting.py License: 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 6
Project: me-ica Author: ME-ICA File: test_spatialimages.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_isolation(self): # Test image isolated from external changes to header and affine img_klass = self.image_class arr = np.arange(3, dtype=np.int16) aff = np.eye(4) img = img_klass(arr, aff) assert_array_equal(img.get_affine(), aff) aff[0,0] = 99 assert_false(np.all(img.get_affine() == aff)) # header, created by image creation ihdr = img.get_header() # Pass it back in img = img_klass(arr, aff, ihdr) # Check modifying header outside does not modify image ihdr.set_zooms((4,)) assert_not_equal(img.get_header(), ihdr)
Example 7
Project: me-ica Author: ME-ICA File: test_scaling.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_calculate_scale(): # Test for special cases in scale calculation npa = np.array # Here the offset handles it res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, True) assert_equal(res, (1.0, -2.0, None, None)) # Not having offset not a problem obviously res = calculate_scale(npa([-2, -1], dtype=np.int8), np.uint8, 0) assert_equal(res, (-1.0, 0.0, None, None)) # Case where offset handles scaling res = calculate_scale(npa([-1, 1], dtype=np.int8), np.uint8, 1) assert_equal(res, (1.0, -1.0, None, None)) # Can't work for no offset case assert_raises(ValueError, calculate_scale, npa([-1, 1], dtype=np.int8), np.uint8, 0) # Offset trick can't work when max is out of range res = calculate_scale(npa([-1, 255], dtype=np.int16), np.uint8, 1) assert_not_equal(res, (1.0, -1.0, None, None))
Example 8
Project: me-ica Author: ME-ICA File: test_utils.py License: 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 9
Project: me-ica Author: ME-ICA File: test_arrayproxy.py License: GNU Lesser General Public License v2.1 | 6 votes |
def test_nifti1_init(): bio = BytesIO() shape = (2,3,4) hdr = Nifti1Header() arr = np.arange(24, dtype=np.int16).reshape(shape) write_raw_data(arr, hdr, bio) hdr.set_slope_inter(2, 10) ap = ArrayProxy(bio, hdr) assert_true(ap.file_like == bio) assert_equal(ap.shape, shape) # Check there has been a copy of the header assert_false(ap.header is hdr) # Get the data assert_array_equal(np.asarray(ap), arr * 2.0 + 10) with InTemporaryDirectory(): f = open('test.nii', 'wb') write_raw_data(arr, hdr, f) f.close() ap = ArrayProxy('test.nii', hdr) assert_true(ap.file_like == 'test.nii') assert_equal(ap.shape, shape) assert_array_equal(np.asarray(ap), arr * 2.0 + 10)
Example 10
Project: hsds Author: HDFGroup File: hdf5dtypeTest.py License: Apache License 2.0 | 6 votes |
def testCreateBaseType(self): dt = hdf5dtype.createDataType('H5T_STD_U32BE') self.assertEqual(dt.name, 'uint32') self.assertEqual(dt.byteorder, '>') self.assertEqual(dt.kind, 'u') dt = hdf5dtype.createDataType('H5T_STD_I16LE') self.assertEqual(dt.name, 'int16') self.assertEqual(dt.kind, 'i') dt = hdf5dtype.createDataType('H5T_IEEE_F64LE') self.assertEqual(dt.name, 'float64') self.assertEqual(dt.kind, 'f') dt = hdf5dtype.createDataType('H5T_IEEE_F32LE') self.assertEqual(dt.name, 'float32') self.assertEqual(dt.kind, 'f') typeItem = { 'class': 'H5T_INTEGER', 'base': 'H5T_STD_I32BE' } typeSize = hdf5dtype.getItemSize(typeItem) dt = hdf5dtype.createDataType(typeItem) self.assertEqual(dt.name, 'int32') self.assertEqual(dt.kind, 'i') self.assertEqual(typeSize, 4)
Example 11
Project: blow Author: joansj File: audio.py License: Apache License 2.0 | 6 votes |
def synthesize(frames,filename,stride,sr=16000,deemph=0,ymax=0.98,normalize=False): # Generate stream y=torch.zeros((len(frames)-1)*stride+len(frames[0])) for i,x in enumerate(frames): y[i*stride:i*stride+len(x)]+=x # To numpy & deemph y=y.numpy().astype(np.float32) if deemph>0: y=deemphasis(y,alpha=deemph) # Normalize if normalize: y-=np.mean(y) mx=np.max(np.abs(y)) if mx>0: y*=ymax/mx else: y=np.clip(y,-ymax,ymax) # To 16 bit & save wavfile.write(filename,sr,np.array(y*32767,dtype=np.int16)) return y ########################################################################################################################
Example 12
Project: Black-Box-Audio Author: rtaori File: run_audio_attack.py License: MIT License | 5 votes |
def save_wav(audio, output_wav_file): wav.write(output_wav_file, 16000, np.array(np.clip(np.round(audio), -2**15, 2**15-1), dtype=np.int16)) print('output dB', db(audio))
Example 13
Project: vergeml Author: mme File: env.py License: MIT License | 5 votes |
def _convert(self, vals): res = {} for k, v in vals.items(): if isinstance(v, (np.int, np.int8, np.int16, np.int32, np.int64)): v = int(v) elif isinstance(v, (np.float, np.float16, np.float32, np.float64)): v = float(v) elif isinstance(v, Labels): v = list(v) elif isinstance(v, np.ndarray): v = v.tolist() elif isinstance(v, dict): v = self._convert(v) res[k] = v return res
Example 14
Project: vergeml Author: mme File: env.py License: 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 15
Project: spectrum_painter Author: polygon File: radios.py License: MIT License | 5 votes |
def convert(self, complex_iq): intlv = self._interleave(complex_iq) clipped = self._clip(intlv, limit=1.0) converted = 2047. * clipped bladerf_out = converted.astype(np.int16) return bladerf_out
Example 16
Project: Griffin_lim Author: candlewill File: audio.py License: MIT License | 5 votes |
def save_wav(wav, path): wav *= 32767 / max(0.01, np.max(np.abs(wav))) wavfile.write(path, hparams.sample_rate, wav.astype(np.int16))
Example 17
Project: Deep_VoiceChanger Author: pstuvwx File: gla_gpu.py License: MIT License | 5 votes |
def save(path, bps, data): if data.dtype != np.int16: data = data.astype(np.int16) data = np.reshape(data, -1) wav.write(path, bps, data)
Example 18
Project: Deep_VoiceChanger Author: pstuvwx File: gla_util.py License: MIT License | 5 votes |
def save(path, bps, data): if data.dtype != np.int16: data = data.astype(np.int16) data = np.reshape(data, -1) wav.write(path, bps, data)
Example 19
Project: Deep_VoiceChanger Author: pstuvwx File: dataset.py License: MIT License | 5 votes |
def save(path, bps, data): if data.dtype != np.int16: data = data.astype(np.int16) data = np.reshape(data, -1) wav.write(path, bps, data)
Example 20
Project: NiBetaSeries Author: HBClab File: conftest.py License: MIT License | 5 votes |
def brainmask_file(deriv_dir, deriv_mask_fname=deriv_mask_fname): brainmask_file = deriv_dir.ensure(deriv_mask_fname) bm_data = np.array([[[1, 1]]], dtype=np.int16) bm_img = nib.Nifti1Image(bm_data, np.eye(4)) bm_img.to_filename(str(brainmask_file)) return brainmask_file
Example 21
Project: NiBetaSeries Author: HBClab File: conftest.py License: MIT License | 5 votes |
def atlas_file(tmpdir_factory): atlas_file = tmpdir_factory.mktemp("atlas").join("atlas.nii.gz") atlas_data = np.array([[[1, 2]]], dtype=np.int16) atlas_img = nib.Nifti1Image(atlas_data, np.eye(4)) atlas_img.to_filename(str(atlas_file)) return atlas_file
Example 22
Project: neuropythy Author: noahbenson File: images.py License: GNU Affero General Public License v3.0 | 5 votes |
def parse_type(self, hdat, dataobj=None): dtype = super(MGHImageType, self).parse_type(hdat, dataobj=dataobj) if np.issubdtype(dtype, np.floating): dtype = np.float32 elif np.issubdtype(dtype, np.int8): dtype = np.int8 elif np.issubdtype(dtype, np.int16): dtype = np.int16 elif np.issubdtype(dtype, np.integer): dtype = np.int32 else: raise ValueError('Could not deduce appropriate MGH type for dtype %s' % dtype) return dtype
Example 23
Project: DeepLab_v3_plus Author: songdejia File: util.py License: MIT License | 5 votes |
def encode_segmap(mask): """Encode segmentation label images as pascal classes Args: mask (np.ndarray): raw segmentation label image of dimension (M, N, 3), in which the Pascal classes are encoded as colours. Returns: (np.ndarray): class map with dimensions (M,N), where the value at a given location is the integer denoting the class index. """ mask = mask.astype(int) label_mask = np.zeros((mask.shape[0], mask.shape[1]), dtype=np.int16) for ii, label in enumerate(get_pascal_labels()): label_mask[np.where(np.all(mask == label, axis=-1))[:2]] = ii label_mask = label_mask.astype(int) return label_mask
Example 24
Project: GST-Tacotron Author: KinglittleQ File: cutoff.py License: MIT License | 5 votes |
def cutoff(input_wav, output_wav): ''' input_wav --- input wav file path output_wav --- output wav file path ''' # read input wave file and get parameters. with wave.open(input_wav, 'r') as fw: params = fw.getparams() # print(params) nchannels, sampwidth, framerate, nframes = params[:4] strData = fw.readframes(nframes) waveData = np.fromstring(strData, dtype=np.int16) max_v = np.max(abs(waveData)) for i in range(waveData.shape[0]): if abs(waveData[i]) > 0.08 * max_v: break for j in range(waveData.shape[0] - 1, 0, -1): if abs(waveData[j]) > 0.08 * max_v: break # write new wav file with wave.open(output_wav, 'w') as fw: params = list(params) params[3] = nframes - i - (waveData.shape[0] - 1 - j) fw.setparams(params) fw.writeframes(strData[2 * i:2 * (j + 1)])
Example 25
Project: QCElemental Author: MolSSI File: molecule.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def atomic_numbers(self) -> Array[np.int16]: atomic_numbers = self.__dict__.get("atomic_numbers_") if atomic_numbers is None: atomic_numbers = np.array([periodictable.to_Z(x) for x in self.symbols]) return atomic_numbers
Example 26
Project: QCElemental Author: MolSSI File: molecule.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def mass_numbers(self) -> Array[np.int16]: mass_numbers = self.__dict__.get("mass_numbers_") if mass_numbers is None: mass_numbers = np.array([periodictable.to_A(x) for x in self.symbols]) return mass_numbers
Example 27
Project: openISP Author: cruxopen File: hsc.py License: MIT License | 5 votes |
def execute(self): lut_sin, lut_cos = self.lut() img_h = self.img.shape[0] img_w = self.img.shape[1] img_c = self.img.shape[2] hsc_img = np.empty((img_h, img_w, img_c), np.int16) for y in range(img_h): for x in range(img_w): hsc_img[y,x,0] = (self.img[y,x,0] - 128) * lut_cos[self.hue] + (self.img[y,x,1] - 128) * lut_sin[self.hue] + 128 hsc_img[y,x,1] = (self.img[y,x,1] - 128) * lut_cos[self.hue] - (self.img[y,x,0] - 128) * lut_sin[self.hue] + 128 hsc_img[y,x,0] = self.saturation * (self.img[y,x,0] - 128) / 256 + 128 hsc_img[y,x,1] = self.saturation * (self.img[y,x,1] - 128) / 256 + 128 self.img = hsc_img return self.clipping()
Example 28
Project: openISP Author: cruxopen File: bcc.py License: MIT License | 5 votes |
def execute(self): img_h = self.img.shape[0] img_w = self.img.shape[1] bcc_img = np.empty((img_h, img_w), np.int16) for y in range(img_h): for x in range(img_w): bcc_img[y,x] = self.img[y,x] + self.brightness bcc_img[y,x] = self.img[y,x] + (self.img[y,x] - 127) * self.contrast self.img = bcc_img return self.clipping()
Example 29
Project: openISP Author: cruxopen File: eeh.py License: MIT License | 5 votes |
def execute(self): img_pad = self.padding() img_h = self.img.shape[0] img_w = self.img.shape[1] ee_img = np.empty((img_h, img_w), np.int16) em_img = np.empty((img_h, img_w), np.int16) for y in range(img_pad.shape[0] - 2): for x in range(img_pad.shape[1] - 4): em_img[y,x] = np.sum(np.multiply(img_pad[y:y+3, x:x+5], self.edge_filter[:, :])) / 8 ee_img[y,x] = img_pad[y+1,x+2] + self.emlut(em_img[y,x], self.thres, self.gain, self.emclip) self.img = ee_img return self.clipping(), em_img
Example 30
Project: L3C-PyTorch Author: fab-jul File: images_loader.py License: GNU General Public License v3.0 | 5 votes |
def to_tensor_not_normalized(pic): """ copied from PyTorch functional.to_tensor, removed final .float().div(255.) """ if isinstance(pic, np.ndarray): # handle numpy array img = torch.from_numpy(pic.transpose((2, 0, 1))) return img # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) elif pic.mode == 'F': img = torch.from_numpy(np.array(pic, np.float32, copy=False)) elif pic.mode == '1': img = 255 * torch.from_numpy(np.array(pic, np.uint8, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() return img