本文整理汇总了Python中numpy.uint函数的典型用法代码示例。如果您正苦于以下问题:Python uint函数的具体用法?Python uint怎么用?Python uint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了uint函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_uint_indexing
def test_uint_indexing():
"""
Test that accessing a row with an unsigned integer
works as with a signed integer. Similarly tests
that printing such a row works.
This is non-trivial: adding a signed and unsigned
integer in numpy results in a float, which is an
invalid slice index.
Regression test for gh-7464.
"""
t = table.Table([[1., 2., 3.]], names='a')
assert t['a'][1] == 2.
assert t['a'][np.int(1)] == 2.
assert t['a'][np.uint(1)] == 2.
assert t[np.uint(1)]['a'] == 2.
trepr = ['<Row index=1>',
' a ',
'float64',
'-------',
' 2.0']
assert repr(t[1]).splitlines() == trepr
assert repr(t[np.int(1)]).splitlines() == trepr
assert repr(t[np.uint(1)]).splitlines() == trepr
开发者ID:Cadair,项目名称:astropy,代码行数:27,代码来源:test_row.py
示例2: get_panorama_col_from_azimuth
def get_panorama_col_from_azimuth(self, azimuth):
'''
@param azimuth: The target azimuth angle (in radians) for which the corresponding col in the panoramic image is to be found.
@retval col: The valid col number (first col is index 0 and last is width-1) in the panorama where the azimuth maps to.
'''
azimuth_filtered = np.mod(azimuth, 2.0 * np.pi) # Filter input azimuth so values are only positive angles between 0 and 2PI
arc_length = self.cyl_radius * azimuth_filtered
col = np.uint(self.cols - 1 - np.uint(arc_length / self.pixel_size))
return col
开发者ID:flair2005,项目名称:omnistereo_sensor_design,代码行数:9,代码来源:panorama.py
示例3: __init__
def __init__(self,timeSeries=None,
lenSeries=2**18,
numChannels=1,
fMin=400,fMax=800,
sampTime=None,
noiseRMS=0.1):
""" Initializes the AmplitudeTimeSeries instance.
If a array is not passed, then a random whitenoise dataset is generated.
Inputs:
Len -- Number of time data points (usually a power of 2) 2^38 gives about 65 seconds
of 400 MHz sampled data
The time binning is decided by the bandwidth
fMin -- lowest frequency (MHz)
fMax -- highest frequency (MHz)
noiseRMS -- RMS value of noise (TBD)
noiseAlpha -- spectral slope (default is white noise) (TBD)
ONLY GENERATES WHITE NOISE RIGHT NOW!
"""
self.shape = (np.uint(numChannels),np.uint(lenSeries))
self.fMax = fMax
self.fMin = fMin
if sampTime is None:
self.sampTime = np.uint(numChannels)*1E-6/(fMax-fMin)
else:
self.sampTime = sampTime
if timeSeries is None:
# then use the rest of the data to generate a random timeseries
if VERBOSE:
print "AmplitudeTimeSeries __init__ did not get new data, generating white noise data"
self.timeSeries = np.complex64(noiseRMS*(np.float16(random.standard_normal(self.shape))
+np.float16(random.standard_normal(self.shape))*1j)/np.sqrt(2))
else:
if VERBOSE:
print "AmplitudeTimeSeries __init__ got new data, making sure it is reasonable."
if len(timeSeries.shape) == 1:
self.shape = (1,timeSeries.shape[0])
else:
self.shape = timeSeries.shape
self.timeSeries = np.reshape(np.complex64(timeSeries),self.shape)
self.fMin = fMin
self.fMax = fMax
if sampTime is None:
self.sampTime = numChannels*1E-6/(fMax-fMin)
else:
self.sampTime = sampTime
return None
开发者ID:shriharshtendulkar,项目名称:FRBSignalGeneration,代码行数:56,代码来源:FRBSignalGeneration.py
示例4: TipDetector
def TipDetector(I):
I.flags.writeable = True
# Convert RGB to YUV
Y=0.3*I[:,:,2]+0.6*I[:,:,1]+0.1*I[:,:,0]
V=0.4375*I[:,:,2]-0.375*I[:,:,1]-0.0625*I[:,:,0]
U=-0.15*I[:,:,2]-0.3*I[:,:,1]+0.45*I[:,:,0]
# Find pink
M=np.ones((np.shape(I)[0], np.shape(I)[1]), np.uint8)*255
for i in range(0,np.shape(I)[0]):
for j in range(0,np.shape(I)[1]):
if V[i,j]>15 and U[i,j]>-7:
M[i,j]=0
kernel = np.ones((5,5),np.uint8)
M = cv2.morphologyEx(M, cv2.MORPH_OPEN, kernel)
M=cv2.GaussianBlur(M,(7,7),8)
# find Harris corners in pink mask
dst = cv2.cornerHarris(M,5,3,0.04)
dst = cv2.dilate(dst,None)
ret, dst = cv2.threshold(dst,0.7*dst.max(),255,0)
dst = np.uint8(dst)
E = np.where(dst > 0.01*dst.max())
# find Harris corners in image
gray1 = cv2.cvtColor(I,cv2.COLOR_BGR2GRAY)
gray1 = np.float32(gray1)
dst1 = cv2.cornerHarris(gray1,3,3,0.04)
dst1 = cv2.dilate(dst1,None)
ret1, dst1 = cv2.threshold(dst1,0.01*dst1.max(),255,0)
dst1 = np.uint8(dst1)
E1 = np.where(dst1 > 0.01*dst1.max())
# no tip identified
if not E or not E1:
return [0,0]
# Rearrange the coordinates in more readable format
ind1 = np.lexsort((E1[1],E1[0]))
C1=[(E1[1][i],E1[0][i]) for i in ind1]
ind = np.lexsort((E[1],E[0]))
C=[(E[1][i],E[0][i]) for i in ind]
# Identify the tip
D=[]
for i in range(1,np.shape(C1)[0]):
for j in range(1,np.shape(C)[0]):
if abs(C1[i][0]-C[j][0])<5 and abs(C1[i][1]-C[j][1])<5:
D.append([int(np.uint(C1[i][0]*2)), int(np.uint(C1[i][1]*2))])
if not D:
return [0,0]
else:
return count(D)
开发者ID:Somahtr,项目名称:robotic_surgery,代码行数:55,代码来源:tip_detection.py
示例5: fun_select_image_area
def fun_select_image_area(image_data):
"""The function select idealy the area whith information in it.
Basically I'm defining a grid and take only the center as important area.
"""
ss = np.shape(image_data)
h = np.uint(np.linspace(0, ss[0], 6))
v = np.uint(np.linspace(0, ss[1], 6))
image_data_area = image_data[h[2] : h[3], v[2] : v[3], :]
# image_data_area = image_data[h[1]:h[4],v[1]:v[4],:]
return image_data_area
开发者ID:mrbonsoir,项目名称:random_notebooks,代码行数:13,代码来源:visualisationTools.py
示例6: max_32_val
def max_32_val():
x = 0
numpy.uint(x)
x = 0xFFFFFFFFFF #Can go up to 10 byte representation? long int?
#x = 0x800000000; # Mask for 1000 0000 0000.... 0000
#x = x >> 32; Interestingly... it uses logic right shift, not arith.
print x
x = x/8
print("Number of bytes: ", x)
x = x/1024
print("Number of Kilobytes: ", x)
x = x/1024
print("Number of Megabytes: ", x)
x = x/1024
print("Number of Gigabytes: ", x)
开发者ID:sahle123,项目名称:Personal-References,代码行数:15,代码来源:max_32_val.py
示例7: downsample
def downsample(image, scale):
"""Downsample an image down to a smaller image by a factor of `scale`, by
averaging the bins."""
result_shape = np.uint(np.array(image.shape) // scale)
result = np.zeros(result_shape, dtype=image.dtype)
num_avg = scale**2
if len(result_shape) == 2:
# 2d downsample
# XXX: I know this is topography, so scale down the z-axis, too.
ylim, xlim = result_shape
for y in range(ylim):
for x in range(xlim):
xmin, xmax = x * scale, (x+1) * scale
ymin, ymax = y * scale, (y+1) * scale
result[y,x] = np.mean(image[ymin:ymax, xmin:xmax] / scale)
elif len(result_shape) == 3:
# 3d downsample
# XXX: I know this is price data, so sum it instead of averaging.
zlim, ylim, xlim = result_shape
for z in range(zlim):
for y in range(ylim):
for x in range(xlim):
zmin, zmax = z * scale, (z+1) * scale
xmin, xmax = x * scale, (x+1) * scale
ymin, ymax = y * scale, (y+1) * scale
result[z,y,x] = np.sum(image[zmin:zmax, ymin:ymax, xmin:xmax])
return result
开发者ID:jefftaylor42,项目名称:pitmining,代码行数:27,代码来源:pitmining.py
示例8: __init__
def __init__(self, opt):
# option (dictionary) contains
# mandatory:
# season, batter/pitcher
self.season = []
if len(opt['season']) == 1:
self.season.append(str(opt['season'][0]))
else:
self.season = np.linspace(opt['season'][0],
opt['season'][1],
opt['season'][1]-opt['season'][0]+1)
for i in range(len(self.season)):
self.season[i] = np.uint(self.season[i])
# batter or pitcher
self.type = opt['type']
# options:
# position, file path, etc (tbd)
if 'postion' in opt:
self.position = opt['position']
else:
self.position = 'NULL'
if 'file' in opt:
self.fp = opt['file']
else:
self.fp = []
# initialize DB
# DB structure
# [season] -> [each files] -> [each line]
self.db = []
开发者ID:thechaos16,项目名称:MajorLeague,代码行数:29,代码来源:fangraph_parser.py
示例9: parse_text
def parse_text(file_name):
"""Parse data from Ohio State University text mocap files (http://accad.osu.edu/research/mocap/mocap_data.htm)."""
# Read the header
fid = open(file_name, 'r')
point_names = np.array(fid.readline().split())[2:-1:3]
fid.close()
for i in range(len(point_names)):
point_names[i] = point_names[i][0:-2]
# Read the matrix data
S = np.loadtxt(file_name, skiprows=1)
field = np.uint(S[:, 0])
times = S[:, 1]
S = S[:, 2:]
# Set the -9999.99 markers to be not present
S[S==-9999.99] = np.NaN
# Store x, y and z in different arrays
points = []
points.append(S[:, 0:-1:3])
points.append(S[:, 1:-1:3])
points.append(S[:, 2:-1:3])
return points, point_names, times
开发者ID:OwenThomas,项目名称:GPy,代码行数:26,代码来源:mocap.py
示例10: sanitize_refreq
def sanitize_refreq(origin, dest):
dest.create_dataset(name="data", data=origin["Data"].value.transpose((2,0,1,3)))
dest["data"].attrs.create('__complex__', "1")
dest.create_group(name="indices")
exec("indL = %s"%origin["IndicesL"].value)
exec("indR = %s"%origin["IndicesR"].value)
indL = [ str(i) for i in indL ]
indR = [ str(i) for i in indR ]
dest["indices"].create_dataset(name="left", data=indL)
dest["indices"].create_dataset(name="right", data=indR)
dest.create_group(name="singularity")
dest["singularity"].create_dataset(name="data", data=origin["Tail"]["array"].value.transpose((2,0,1,3)))
dest["singularity"]["data"].attrs.create('__complex__', "1")
dest["singularity"].create_dataset(name="omin", data=origin["Tail"]["OrderMinMIN"].value)
mask = numpy.zeros( dest["singularity"]["data"].shape[0:2], numpy.integer )
mask.fill(origin["Tail"]["OrderMax"].value)
dest["singularity"].create_dataset(name="mask", data=mask)
dest.create_group(name="mesh")
size = numpy.uint(len(origin["Mesh"]["array"].value))
min_w = origin["Mesh"]["array"].value[0]
max_w = origin["Mesh"]["array"].value[-1]
dest["mesh"].create_dataset(name="kind", data=1)
dest["mesh"].create_dataset(name="min", data=min_w)
dest["mesh"].create_dataset(name="max", data=max_w)
dest["mesh"].create_dataset(name="size", data=size)
return ['Data', 'IndicesL', 'IndicesR', 'Mesh', 'Name', 'Note', 'Tail']
开发者ID:davoudn,项目名称:triqs-1,代码行数:31,代码来源:update_archive.py
示例11: sanitize_imfreq
def sanitize_imfreq(origin, dest):
dest.create_dataset(name="data", data=origin["Data"].value.transpose((2,0,1,3)))
dest["data"].attrs.create('__complex__', "1")
dest.create_group(name="indices")
exec("indL = %s"%origin["IndicesL"].value)
exec("indR = %s"%origin["IndicesR"].value)
indL = [ str(i) for i in indL ]
indR = [ str(i) for i in indR ]
dest["indices"].create_dataset(name="left", data=indL)
dest["indices"].create_dataset(name="right", data=indR)
dest.create_group(name="singularity")
dest["singularity"].create_dataset(name="data", data=origin["Tail"]["array"].value.transpose((2,0,1,3)))
dest["singularity"]["data"].attrs.create('__complex__', "1")
dest["singularity"].create_dataset(name="omin", data=origin["Tail"]["OrderMinMIN"].value)
mask = numpy.zeros( dest["singularity"]["data"].shape[0:2], numpy.integer )
mask.fill(origin["Tail"]["OrderMax"].value)
dest["singularity"].create_dataset(name="mask", data=mask)
dest.create_group(name="mesh")
beta = origin["Mesh"]["Beta"].value
pi = numpy.arccos(-1)
size = numpy.uint(len(origin["Mesh"]["array"].value))
dest["mesh"].create_dataset(name="kind", data=2)
dest["mesh"].create_dataset(name="min", data=pi/beta)
dest["mesh"].create_dataset(name="max", data=(2*size+1)*pi/beta)
dest["mesh"].create_dataset(name="size", data=size)
dest["mesh"].create_group(name="domain")
dest["mesh"]["domain"].create_dataset(name="beta", data=beta)
dest["mesh"]["domain"].create_dataset(name="statistic", data={"Fermion":"F", "Boson":"B"}[origin["Mesh"]["Statistic"].value] )
return ['Data', 'IndicesL', 'IndicesR', 'Mesh', 'Name', 'Note', 'Tail']
开发者ID:davoudn,项目名称:triqs-1,代码行数:34,代码来源:update_archive.py
示例12: deterministic_shuffle
def deterministic_shuffle(list_, seed=1):
r"""
Args:
list_ (list):
seed (int):
Returns:
list: list_
CommandLine:
python -m utool.util_numpy --test-deterministic_shuffle
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> list_ = [1,2,3,4,5,6]
>>> seed = 1
>>> list_ = deterministic_shuffle(list_, seed)
>>> result = str(list_)
>>> print(result)
[4, 6, 1, 3, 2, 5]
"""
rand_seed = np.uint32(np.random.rand() * np.uint(0 - 2) / 2)
if not isinstance(list_, (np.ndarray, list)):
list_ = list(list_)
seed_ = len(list_) + seed
np.random.seed(seed_)
np.random.shuffle(list_)
np.random.seed(rand_seed) # reseed
return list_
开发者ID:animalus,项目名称:utool,代码行数:30,代码来源:util_numpy.py
示例13: _load_MNIST
def _load_MNIST(datafile, labelfile):
#Get training data
df = open(datafile, 'rb')
magic = int(binascii.hexlify(df.read(4)), 16)
assert magic == 2051
num_examples = int(binascii.hexlify(df.read(4)), 16)
i = int(binascii.hexlify(df.read(4)), 16)
j = int(binascii.hexlify(df.read(4)), 16)
#I only have to work with the feature matrix in terms of its rows,
#so I store it as a list of <train.num_examples> rows.
one = np.array([np.uint(255)])
features = []
for example in range(0, num_examples):
#Create a numpy uint8 array of pixels. We set the first attribute to 1, because it corresponds to a y-intercept term in [theta].
features.append(np.concatenate((one, np.fromfile(df, dtype='u1', count=i*j))))
lf = open(labelfile, 'rb')
assert (int(binascii.hexlify(lf.read(4)), 16)) == 2049 #check magic
images = (int(binascii.hexlify(lf.read(4)), 16))
labels = np.fromfile(lf, dtype='u1', count=images)
data = Data(features=features, labels=labels, theta=np.zeros((10, 785)),
num_features=i*j, num_labels=10, num_examples=num_examples,
alpha=0.01, epsilon = 0.01)
return data
开发者ID:e-271,项目名称:ocr,代码行数:28,代码来源:Learn.py
示例14: __get_excit_wfm
def __get_excit_wfm(filepath):
"""
Returns the excitation BE waveform present in the more parms.mat file
Parameters
------------
filepath : String / unicode
Absolute filepath of the .mat parameter file
Returns
-----------
ex_wfm : 1D numpy float array
Band Excitation waveform
"""
if not path.exists(filepath):
warn('BEPSndfTranslator - NO more_parms.mat file found')
return np.zeros(1000, dtype=np.float32)
if 'more_parms' in filepath:
matread = loadmat(filepath, variable_names=['FFT_BE_wave'])
fft_full = np.complex64(np.squeeze(matread['FFT_BE_wave']))
bin_inds = None
fft_full_rev = None
else:
matread = loadmat(filepath, variable_names=['FFT_BE_wave', 'FFT_BE_rev_wave', 'BE_bin_ind'])
bin_inds = np.uint(np.squeeze(matread['BE_bin_ind'])) - 1
fft_full = np.complex64(np.squeeze(matread['FFT_BE_wave']))
fft_full_rev = np.complex64(np.squeeze(matread['FFT_BE_rev_wave']))
return fft_full, fft_full_rev, bin_inds
开发者ID:pycroscopy,项目名称:pycroscopy,代码行数:31,代码来源:beps_ndf.py
示例15: initialize_cost_map
def initialize_cost_map(self):
''' Performs all the neccessary initialization
and creation of the cost map graph.
'''
self.params['stripWidth'] = np.uint(np.double(self.costm.shape) \
/ self.params['pixels'])
#self._add_image_strips()
self.graph = build_graph(self.costm)
开发者ID:bashwork,项目名称:school,代码行数:8,代码来源:graph.py
示例16: createHashTable
def createHashTable(kd, vd, capacity):
table_capacity_gpu, _ = mod.get_global('table_capacity')
cuda.memcpy_htod(table_capacity_gpu, np.uint([capacity]))
# CUDA_SAFE_CALL(cudaMemcpyToSymbol(table_capacity,
# &capacity,
# sizeof(unsigned int)));
table_vals_gpu, table_vals_size = mod.get_global('table_values') # pointer-2-pointer
values_gpu = gpuarray.zeros((capacity*vd,1), dtype=np.float32)
# values_gpu = gpuarray.zeros((capacity*vd,1), dtype=np.float32)
# cuda.memset_d32(values_gpu.gpudata, 0, values_gpu.size)
cuda.memcpy_dtod(table_vals_gpu, values_gpu.gpudata, table_vals_size)
# float *values;
# allocateCudaMemory((void**)&values, capacity*vd*sizeof(float));
# CUDA_SAFE_CALL(cudaMemset((void *)values, 0, capacity*vd*sizeof(float)));
# CUDA_SAFE_CALL(cudaMemcpyToSymbol(table_values,
# &values,
# sizeof(float *)));
table_entries, table_entries_size = mod.get_global('table_entries')
entries_gpu = gpuarray.empty((capacity*2,1), dtype=np.int)
entries_gpu.fill(-1)
# cuda.memset_d32(entries_gpu.gpudata, 1, entries_gpu.size)
cuda.memcpy_dtod(table_entries, entries_gpu.gpudata, table_entries_size)
# int *entries;
# allocateCudaMemory((void **)&entries, capacity*2*sizeof(int));
# CUDA_SAFE_CALL(cudaMemset((void *)entries, -1, capacity*2*sizeof(int)));
# CUDA_SAFE_CALL(cudaMemcpyToSymbol(table_entries,
# &entries,
# sizeof(unsigned int *)));
########################################
# Assuming LINEAR_D_MEMORY not defined #
########################################
# #ifdef LINEAR_D_MEMORY
# char *ranks;
# allocateCudaMemory((void**)&ranks, capacity*sizeof(char));
# CUDA_SAFE_CALL(cudaMemcpyToSymbol(table_rank,
# &ranks,
# sizeof(char *)));
#
# signed short *zeros;
# allocateCudaMemory((void**)&zeros, capacity*sizeof(signed short));
# CUDA_SAFE_CALL(cudaMemcpyToSymbol(table_zeros,
# &zeros,
# sizeof(char *)));
#
# #else
table_keys_gpu, table_keys_size = mod.get_global('table_keys')
keys_gpu = gpuarray.zeros((capacity*kd,1), dtype=np.short)
# keys_gpu = gpuarray.empty((capacity*kd,1), dtype=np.short)
# cuda.memset_d32(keys_gpu.gpudata, 0, keys_gpu.size)
cuda.memcpy_dtod(table_keys_gpu, keys_gpu.gpudata, table_keys_size)
开发者ID:AdrianLsk,项目名称:permutohedral_pycuda,代码行数:58,代码来源:filter_pycuda.py
示例17: getInfoFromPath
def getInfoFromPath(fpath):
"""
:param fpath:
:return:
"""
if fpath.lower().endswith(".npy"):
fpath, fname = os.path.split(fpath)
return fpath.rsplit(os.path.sep, 3)[-1], np.uint(re.split('_|.npy', fname)[-2])
开发者ID:r-zemblys,项目名称:windowselect,代码行数:9,代码来源:window_selection.py
示例18: test_fill_value_uint
def test_fill_value_uint(self):
fill_value = np.uint(1234)
for dtype in self.dtypes:
data = np.array([0], dtype=dtype)
dm = DataManager(data)
dm.fill_value = fill_value
[expected] = np.array([fill_value], dtype=dtype)
self.assertEqual(dm.fill_value, expected)
self.assertEqual(dm.fill_value.dtype, dtype)
开发者ID:cpelley,项目名称:iris,代码行数:9,代码来源:test_DataManager.py
示例19: values_labels
def values_labels(self):
labels = self.stata_object.values_labels
new_labels_dict = dict()
for var in labels:
var_label = list(labels[var].items())
label_tuple = [(np.uint(item[0]).astype(int), item[1])
for item in var_label]
new_labels_dict[var] = dict(label_tuple)
return new_labels_dict
开发者ID:plutoese,项目名称:mars,代码行数:9,代码来源:class_CgssStataSheet.py
示例20: clean
def clean(self):
rtn_array = self.img.copy()
if self.color_flag:
red = rtn_array[:,:,0]
green = rtn_array[:,:,1]
blue = rtn_array[:,:,2]
a = numpy.array([red,green,blue])
rtn_array = numpy.bitwise_and(a.flatten(),numpy.uint(254))
rtn_array = rtn_array.reshape(3,-1)
rtn_array = numpy.dstack(tuple(rtn_array))
rtn_array = rtn_array.reshape(self.img_size[0],self.img_size[1],3)
else:
a = numpy.array([rtn_array])
rtn_array = numpy.bitwise_and(a.flatten(),numpy.uint(254))
rtn_array = rtn_array.reshape(self.img_size[0],self.img_size[1])
rtn_img = Payload(rtn_array)
return rtn_img.img
开发者ID:ChongjinChua,项目名称:ECE364-Software-Engineering-Tools,代码行数:18,代码来源:Steganography.py
注:本文中的numpy.uint函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论