本文整理汇总了Python中numpy.int8函数的典型用法代码示例。如果您正苦于以下问题:Python int8函数的具体用法?Python int8怎么用?Python int8使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了int8函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_sites_summary
def get_sites_summary(noaa_dir, stemxy=False):
"""create a pandas data frame with site code, lon and lat for all
sites with data files in the specified directory
ARGS:
noaa_dir (string): full path to a directory containing NOAA OCS observation
files
RETURNS:
pandas DataFrame object with columns site_code, lon, lat
"""
all_sites_df = get_all_NOAA_airborne_data(noaa_dir)
if stemxy:
dom = domain.STEM_Domain()
all_sites_df.get_stem_xy(dom.get_lon(), dom.get_lat())
summary_df = all_sites_df.obs.groupby('sample_site_code').mean()
if stemxy:
summary_df = summary_df[['sample_longitude', 'sample_latitude',
'x_stem', 'y_stem']]
# make sure x, y indices are integers
summary_df['x_stem'] = np.int8(np.round(summary_df['x_stem']))
summary_df['y_stem'] = np.int8(np.round(summary_df['y_stem']))
else:
summary_df = summary_df[['sample_longitude', 'sample_latitude']]
summary_df = summary_df.reset_index()
summary_df.rename(columns={k: k.replace('sample_', '')
for k in summary_df.columns.values},
inplace=True)
return(summary_df)
示例2: multi_where
def multi_where(vec1, vec2):
'''Given two vectors, multi_where returns a tuple of indices where those
two vectors overlap.
****THIS FUNCTION HAS NOT BEEN TESTED ON N-DIMENSIONAL ARRAYS*******
Inputs:
2 numpy vectors
Output:
(xy, yx) where xy is a numpy vector containing the indices of the
elements in vector 1 that are also in vector 2. yx is a vector
containing the indices of the elements in vector 2 that are also
in vector 1.
Example:
>> x = np.array([1,2,3,4,5])
>> y = np.array([3,4,5,6,7])
>> (xy,yx) = multi_where(x,y)
>> xy
array([2,3,4])
>> yx
array([0,1,2])
'''
OneInTwo = np.array([])
TwoInOne = np.array([])
for i in range(vec1.shape[0]):
if np.where(vec2 == vec1[i])[0].shape[0]:
OneInTwo = np.append(OneInTwo,i)
TwoInOne = np.append(TwoInOne, np.where(vec2 == vec1[i])[0][0])
return (np.int8(OneInTwo), np.int8(TwoInOne))
示例3: test_apply_scaling
def test_apply_scaling():
# Null scaling, same array returned
arr = np.zeros((3,), dtype=np.int16)
assert_true(apply_read_scaling(arr) is arr)
assert_true(apply_read_scaling(arr, np.float64(1.0)) is arr)
assert_true(apply_read_scaling(arr, inter=np.float64(0)) is arr)
f32, f64 = np.float32, np.float64
f32_arr = np.zeros((1,), dtype=f32)
i16_arr = np.zeros((1,), dtype=np.int16)
# Check float upcast (not the normal numpy scalar rule)
# This is the normal rule - no upcast from scalar
assert_equal((f32_arr * f64(1)).dtype, np.float32)
assert_equal((f32_arr + f64(1)).dtype, np.float32)
# The function does upcast though
ret = apply_read_scaling(np.float32(0), np.float64(2))
assert_equal(ret.dtype, np.float64)
ret = apply_read_scaling(np.float32(0), inter=np.float64(2))
assert_equal(ret.dtype, np.float64)
# Check integer inf upcast
big = f32(type_info(f32)['max'])
# Normally this would not upcast
assert_equal((i16_arr * big).dtype, np.float32)
# An equivalent case is a little hard to find for the intercept
nmant_32 = type_info(np.float32)['nmant']
big_delta = np.float32(2**(floor_log2(big)-nmant_32))
assert_equal((i16_arr * big_delta + big).dtype, np.float32)
# Upcasting does occur with this routine
assert_equal(apply_read_scaling(i16_arr, big).dtype, np.float64)
assert_equal(apply_read_scaling(i16_arr, big_delta, big).dtype, np.float64)
assert_equal(apply_read_scaling(np.int8(0), -1.0, 0.0).dtype, np.float32)
assert_equal(apply_read_scaling(np.int8(0), 1e38, 0.0).dtype, np.float64)
assert_equal(apply_read_scaling(np.int8(0), -1e38, 0.0).dtype, np.float64)
示例4: test_NumPy_arrayview_deletion_sitkImage_1
def test_NumPy_arrayview_deletion_sitkImage_1(self):
# 2D image
image = sitk.Image(sizeX, sizeY, sitk.sitkInt32)
for j in range(sizeY):
for i in range(sizeX):
image[i, j] = j*sizeX + i
npview = sitk.GetArrayFromImage(image, arrayview = True, writeable = True)
image.SetPixel(0,0, newSimpleITKPixelValueInt32)
del image
carr = np.array(npview, copy = False)
rarr = np.reshape(npview, (1, npview.size))
varr = npview.view(dtype=np.int8)
self.assertEqual( carr[0,0],newSimpleITKPixelValueInt32)
self.assertEqual( rarr[0,0],newSimpleITKPixelValueInt32)
self.assertEqual( varr[0,0],np.int8(newSimpleITKPixelValueInt32))
npview[0,0] = newNumPyElementValueInt32
del npview
self.assertEqual( carr[0,0],newNumPyElementValueInt32)
self.assertEqual( rarr[0,0],newNumPyElementValueInt32)
self.assertEqual( varr[0,0],np.int8(newNumPyElementValueInt32))
示例5: moveObject
def moveObject(initial_depthMAT):
###########################################################################
## Checking each pixel and invoking functions to process pixels on the vessels.
###########################################################################
global done,startx,starty,clock,screen,endx,endy
global im
global endpoint
global current_depth
global depthMAT
global rough_range
global modified_depthMAT,mask_depthMAT
if np.amax(im)!=1:
ret,im = cv2.threshold(im, 250, 1, cv2.THRESH_BINARY)
else:
print np.amax(im)
np.int8(im)
mask_depthMAT=initial_depthMAT
modified_depthMAT=initial_depthMAT
depthMAT=getDepth(im,modified_depthMAT)
rough_range=np.median(depthMAT[depthMAT>0])/LEVEL
im0=np.copy(im)
convalue_n=Neigh_Cov(im0)
cols=im.shape[1]
rows=im.shape[0]
for y in range(0,rows,1):
for x in range(0,cols,1):
if im[y][x]==1:
fillPixel(x,y,convalue_n)
return convalue_n
示例6: classify
def classify(self, inputs):
# switch to test mode
self.mode.set_value(np.int8(1))
rval = self._classify(inputs)
# switch to train mode
self.mode.set_value(np.int8(0))
return rval
示例7: process
def process(self, target, **kwargs):
""" Filter the image leaving only the required annulus. """
# Check target type
if target.name() != 'Image':
self.logger.warning("[%s] Input variable is not an image. Skipping.", self.name())
return {'output': None}
# Check that inner and outer diameter are defined
if self._inner is None or self._outer is None:
self.logger.warning("[%s] One of the required diameter is not set. Skipping.", self.name())
return {'output': None}
# If size has changed or mask is not defined, we prepare it
if self._mask is None or target.value.shape[1:] != self._size:
self._size = target.value.shape[1:]
if self._center is None:
self._center = [int(target.value.shape[2] / 2), int(target.value.shape[1] / 2)]
# Build the mask
y, x = np.ogrid[0:self._size[0], 0:self._size[1]]
x -= self._center[0]
y -= self._center[1]
r_in = x ** 2 / self._inner[0] + y ** 2 / self._inner[1]
r_out = x ** 2 / self._outer[0] + y ** 2 / self._outer[1]
self._mask = np.int8(r_in > 1) * np.int8(r_out < 1)
# Filter the image using the defined mask
self.logger.debug("[%s] Image shape %s, Mask shape %s.", self.name(), target.value.shape, self._mask.shape)
out = Image()
out.value = np.copy(target.value) * np.tile(self._mask, (target.value.shape[0], 1, 1))
return {'output': out}
示例8: add_vars_to_grp
def add_vars_to_grp(grp,types, **kwargs):
v = grp.createVariable(kwargs.get('var1','var1'),numpy.int8)
v[:] = numpy.int8(8)
v.foo = 'bar'
v = grp.createVariable(kwargs.get('var2','var2'),numpy.int8, (dim3._name,), fill_value=5)
v[:] = numpy.int8(8)
v.foo = 'bar'
v = grp.createVariable(kwargs.get('var3','var3'),numpy.int8, (dim1._name,dim4._name,))
v[:] = numpy.arange(8,dtype=numpy.int8).reshape(2,4)
v.foo = 'bar'
v = grp.createVariable(kwargs.get('var4','var4'),'S1', (dim1._name,dim4._name,))
#v[:] = numpy.ndarray(8,dtype='S1').reshape(2,4)
v[:] = 'a'
v.foo = 'bar'
for num,type in enumerate(types):
default_name = 'var{}'.format(num+5)
print default_name
v = grp.createVariable(kwargs.get(default_name,default_name),type, (dim4._name,))
try:
v[:] = numpy.iinfo(type).max
continue
except ValueError:
pass
try:
for i,c in enumerate('char'):
v[i] = c
continue
except ValueError:
pass
v[:] = numpy.pi
示例9: parse_objects
def parse_objects(self, data):
x = y = dx = dy = count = 0
addr = None
objects = []
data = np.array(data, dtype=np.uint8)
last = len(data)
index = 0
while index < last:
c = data[index]
log.debug("index=%d, command=%x" % (index, c))
self.pick_index += 1
index += 1
command = None
if c < 0xfb:
if addr is not None:
obj = self.get_object(self.pick_index, x, y, c, dx, dy, addr)
objects.append(obj)
elif c >= 0xfc and c <= 0xfe:
arg1 = data[index]
arg2 = data[index + 1]
index += 2
if c == 0xfc:
addr = arg2 * 256 + arg1
elif c == 0xfd:
x = int(arg1)
y = int(arg2)
else:
dx = int(np.int8(arg1)) # signed!
dy = int(np.int8(arg2))
elif c == 0xff:
last = 0 # force the end
return objects
示例10: test_valid
def test_valid(self):
prop = bcpp.Int()
assert prop.is_valid(None)
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(np.int8(0))
assert prop.is_valid(np.int8(1))
assert prop.is_valid(np.int16(0))
assert prop.is_valid(np.int16(1))
assert prop.is_valid(np.int32(0))
assert prop.is_valid(np.int32(1))
assert prop.is_valid(np.int64(0))
assert prop.is_valid(np.int64(1))
assert prop.is_valid(np.uint8(0))
assert prop.is_valid(np.uint8(1))
assert prop.is_valid(np.uint16(0))
assert prop.is_valid(np.uint16(1))
assert prop.is_valid(np.uint32(0))
assert prop.is_valid(np.uint32(1))
assert prop.is_valid(np.uint64(0))
assert prop.is_valid(np.uint64(1))
# TODO (bev) should fail
assert prop.is_valid(False)
assert prop.is_valid(True)
示例11: test_numpy
def test_numpy(self):
assert chash(np.bool_(True)) == chash(np.bool_(True))
assert chash(np.int8(1)) == chash(np.int8(1))
assert chash(np.int16(1))
assert chash(np.int32(1))
assert chash(np.int64(1))
assert chash(np.uint8(1))
assert chash(np.uint16(1))
assert chash(np.uint32(1))
assert chash(np.uint64(1))
assert chash(np.float32(1)) == chash(np.float32(1))
assert chash(np.float64(1)) == chash(np.float64(1))
assert chash(np.float128(1)) == chash(np.float128(1))
assert chash(np.complex64(1+1j)) == chash(np.complex64(1+1j))
assert chash(np.complex128(1+1j)) == chash(np.complex128(1+1j))
assert chash(np.complex256(1+1j)) == chash(np.complex256(1+1j))
assert chash(np.datetime64('2000-01-01')) == chash(np.datetime64('2000-01-01'))
assert chash(np.timedelta64(1,'W')) == chash(np.timedelta64(1,'W'))
self.assertRaises(ValueError, chash, np.object())
assert chash(np.array([[1, 2], [3, 4]])) == \
chash(np.array([[1, 2], [3, 4]]))
assert chash(np.array([[1, 2], [3, 4]])) != \
chash(np.array([[1, 2], [3, 4]]).T)
assert chash(np.array([1, 2, 3])) == chash(np.array([1, 2, 3]))
assert chash(np.array([1, 2, 3], dtype=np.int32)) != \
chash(np.array([1, 2, 3], dtype=np.int64))
示例12: chain2image
def chain2image(chaincode,start_pix):
"""
Method to compute the pixel contour providing the chain code string
and the starting pixel location [X,Y].
Author: Xavier Bonnin (LESIA)
"""
if (type(chaincode) != str):
print "First input argument must be a string!"
return None
if (len(start_pix) != 2):
print "Second input argument must be a 2-elements vector!"
return None
ardir = np.array([[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]])
ccdir = np.array([0,7,6,5,4,3,2,1])
X=[start_pix[0]]
Y=[start_pix[1]]
for c in chaincode:
if (abs(np.int8(c)) > 7):
print "Wrong chain code format!"
return None
wc = np.where(np.int8(c) == np.int8(ccdir))[0]
X.append(X[-1] + np.int(ardir[wc,0]))
Y.append(Y[-1] + np.int(ardir[wc,1]))
return X,Y
示例13: result_dict_to_hdf5
def result_dict_to_hdf5(f, rd):
for name, data in rd.items():
flag = None
# beware: isinstance(True/False, int) == True
if isinstance(data, bool):
data = np.int8(data)
flag = "py_bool"
elif isinstance(data, int):
data = np.int64(data)
flag = "py_int"
if isinstance(data, np.ndarray):
dataset = f.create_dataset(name, data=data)
else:
ty = type(data)
if ty is str:
ty_h5 = "S{}".format(len(data))
data = data.encode()
else:
try:
ty_h5 = _type_to_hdf5[ty]
except KeyError:
raise TypeError("Type {} is not supported for HDF5 output"
.format(ty)) from None
dataset = f.create_dataset(name, (), ty_h5)
dataset[()] = data
if flag is not None:
dataset.attrs[flag] = np.int8(1)
示例14: conv_int8
def conv_int8( value ):
if( len(value) == 0 ):
rval = imiss
else:
rval = int( value )
assert numpy.int8( rval ) == numpy.int32( rval ) , " conv_int8: value out of range"
return numpy.int8( rval )
示例15: process
def process(self, image,
dark=None,
variance=None,
dark_variance=None,
normalization_factor=1.0
):
"""Perform the pixel-wise operation of the array
:param raw: numpy array with the input image
:param dark: numpy array with the dark-current image
:param variance: numpy array with the variance of input image
:param dark_variance: numpy array with the variance of dark-current image
:param normalization_factor: divide the result by this
:return: array with processed data,
may be an array of (data,variance,normalization) depending on class initialization
"""
with self.sem:
if id(image) != id(self.on_device.get("image")):
self.send_buffer(image, "image")
if dark is not None:
do_dark = numpy.int8(1)
if id(dark) != id(self.on_device.get("dark")):
self.send_buffer(dark, "dark")
else:
do_dark = numpy.int8(0)
if (variance is not None) and self.on_host.get("calc_variance"):
if id(variance) != id(self.on_device.get("variance")):
self.send_buffer(variance, "variance")
if (dark_variance is not None) and self.on_host.get("calc_variance"):
if id(dark_variance) != id(self.on_device.get("dark_variance")):
self.send_buffer(dark_variance, "dark_variance")
if self.on_host.get("poissonian"):
kernel_name = "corrections3Poisson"
elif self.on_host.get("calc_variance"):
kernel_name = "corrections3"
elif self.on_host.get("split_result"):
kernel_name = "corrections2"
else:
kernel_name = "corrections"
kwargs = self.cl_kernel_args[kernel_name]
kwargs["do_dark"] = do_dark
kwargs["normalization_factor"] = numpy.float32(normalization_factor)
if (kernel_name == "corrections3") and (self.on_device.get("dark_variance") is not None):
kwargs["do_dark_variance"] = do_dark
kernel = self.kernels.get_kernel(kernel_name)
evt = kernel(self.queue, (self.size,), None, *list(kwargs.values()))
if kernel_name.startswith("corrections3"):
dest = numpy.empty(self.on_device.get("image").shape + (3,), dtype=numpy.float32)
elif kernel_name == "corrections2":
dest = numpy.empty(self.on_device.get("image").shape + (2,), dtype=numpy.float32)
else:
dest = numpy.empty(self.on_device.get("image").shape, dtype=numpy.float32)
copy_result = pyopencl.enqueue_copy(self.queue, dest, self.cl_mem["output"])
copy_result.wait()
if self.profile:
self.events += [EventDescription("preproc", evt), EventDescription("copy result", copy_result)]
return dest