def readFlow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
with open(fn, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if 202021.25 != magic:
print 'Magic number incorrect. Invalid .flo file'
return None
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
#print 'Reading %d x %d flo file' % (w, h)
data = np.fromfile(f, np.float32, count=2*w*h)
# Reshape data into 3D array (columns, rows, bands)
return np.resize(data, (h, w, 2))
python类resize()的实例源码
def readFlow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
with open(fn, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if 202021.25 != magic:
print 'Magic number incorrect. Invalid .flo file'
return None
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
#print 'Reading %d x %d flo file' % (w, h)
data = np.fromfile(f, np.float32, count=2*w*h)
# Reshape data into 3D array (columns, rows, bands)
# The reshape here is for visualization, the original code is (w,h,2)
return np.resize(data, (h, w, 2))
def read_flow(filename):
"""
read optical flow from Middlebury .flo file
:param filename: name of the flow file
:return: optical flow data in matrix
"""
f = open(filename, 'rb')
magic = np.fromfile(f, np.float32, count=1)
data2d = None
if 202021.25 != magic:
print 'Magic number incorrect. Invalid .flo file'
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
print "Reading %d x %d flo file" % (h, w)
data2d = np.fromfile(f, np.float32, count=2 * w * h)
# reshape data into 3D array (columns, rows, channels)
data2d = np.resize(data2d, (h[0], w[0], 2))
f.close()
return data2d
def label_preproc(label_string):
"""
This function is supposed to prepare the label so that it fits the standard of the rnn_ctc network.
It computes following steps:
1. make list of integers out of string e.g. [hallo] --> [8,1,12,12,15]
:param label_string: a string of the label
:return: label_int: the string represented in integers
"""
chars = char_alpha.chars
label_int = []
for letter in label_string:
label_int.append(chars.index(letter))
label_int_arr = np.resize(np.asarray(label_int), (1, len(label_int)))
# print(label_int_arr.shape)
return label_int_arr
def squeeze(image, width_max, border):
"""
This function squeezes images in the width.
:param image: Numpy array of image
:param width_max: max image width
:param border: border left and right of squeezed image
:return: Squeezed Image
"""
image_wd = image.shape[1]
image_ht = image.shape[0]
basewidth = width_max - border
wpercent = basewidth / image_wd
dim = (int(wpercent*image_wd), image_ht)
img_squeeze = cv.resize(image, dim, interpolation=cv.INTER_NEAREST)
return img_squeeze
def string_to_array(label_string):
"""
This function converts string into integers. e.g. [hallo] --> [8,1,12,12,15]
:param label_string: a string of the label
:return: label_int: the string represented in integers
"""
chars = char_alpha.chars
label_int = []
for letter in label_string:
label_int.append(chars.index(letter))
label_int_arr = np.resize(np.asarray(label_int), (1, len(label_int)))
# print(label_int_arr.shape)
return label_int_arr
def plot_Reynolds_number(Fr, ReyNum, edge):
# figr = Fr.plot_fracture("complete", "footPrint")
# ax = figr.axes[0]
figr = plt.figure()
ax = figr.add_subplot(111)
ReMesh = np.resize(ReyNum[edge, :], (Fr.mesh.ny, Fr.mesh.nx))
x = np.linspace(-Fr.mesh.Lx, Fr.mesh.Lx, Fr.mesh.nx)
y = np.linspace(-Fr.mesh.Ly, Fr.mesh.Ly, Fr.mesh.ny)
xv, yv = np.meshgrid(x, y)
# cax = ax.contourf(xv, yv, ReMesh, levels=[0, 100, 2100, 10000])
cax = ax.matshow(ReMesh)
figr.colorbar(cax)
plt.title("Reynolds number")
plt.show()
return figr
#-----------------------------------------------------------------------------------------------------------------------
def MakeVisual( X_src, X_tar):
#LAB pair
#pdb.set_trace()
#X_rst = np.zeros( X_src.shape, np.float32)
#for i in range( X_src.shape[0]):
# X_rst[i,:,:,:] = np.concatenate(
# (np.resize( X_src[i,:,:,:], (1,nc,npx,npx/2)),
# np.resize( X_tar[i,:,:,:], (1,nc,npx,npx/2))), axis =3 )
X_src = np.resize(X_src,(X_src.shape[0],nc,npx,npx/2))
X_tar = np.resize(X_tar,(X_tar.shape[0],nc,npx,npx/2))
return X_tar
#return np.concatenate( (X_src,X_tar), axis = 2)
# SET PARAMETERS.
def MakeVisual( X_src, X_tar):
#LAB pair
#pdb.set_trace()
#X_rst = np.zeros( X_src.shape, np.float32)
#for i in range( X_src.shape[0]):
# X_rst[i,:,:,:] = np.concatenate(
# (np.resize( X_src[i,:,:,:], (1,nc,npx,npx/2)),
# np.resize( X_tar[i,:,:,:], (1,nc,npx,npx/2))), axis =3 )
X_src = np.resize(X_src,(X_src.shape[0],nc,npx,npx/2))
X_tar = np.resize(X_tar,(X_tar.shape[0],nc,npx,npx/2))
return X_tar
#return np.concatenate( (X_src,X_tar), axis = 2)
# SET PARAMETERS.
def MakeVisual( X_src, X_tar):
#LAB pair
#pdb.set_trace()
#X_rst = np.zeros( X_src.shape, np.float32)
#for i in range( X_src.shape[0]):
# X_rst[i,:,:,:] = np.concatenate(
# (np.resize( X_src[i,:,:,:], (1,nc,npx,npx/2)),
# np.resize( X_tar[i,:,:,:], (1,nc,npx,npx/2))), axis =3 )
X_src = np.resize(X_src,(X_src.shape[0],nc,npx,npx/2))
X_tar = np.resize(X_tar,(X_tar.shape[0],nc,npx,npx/2))
return X_tar
#return np.concatenate( (X_src,X_tar), axis = 2)
# SET PARAMETERS.
test_indexing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 44
收藏 0
点赞 0
评论 0
def test_mask_broadcast(self):
# GH 8801
# copied from test_where_broadcast
for size in range(2, 6):
for selection in [
# First element should be set
np.resize([True, False, False, False, False], size),
# Set alternating elements]
np.resize([True, False], size),
# No element should be set
np.resize([False], size)]:
for item in [2.0, np.nan, np.finfo(np.float).max,
np.finfo(np.float).min]:
for arr in [np.array([item]), [item], (item, )]:
data = np.arange(size, dtype=float)
s = Series(data)
result = s.mask(selection, arr)
expected = Series([item if use_item else data[
i] for i, use_item in enumerate(selection)])
assert_series_equal(result, expected)
core.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def resize(self, newshape, refcheck=True, order=False):
"""
.. warning::
This method does nothing, except raise a ValueError exception. A
masked array does not own its data and therefore cannot safely be
resized in place. Use the `numpy.ma.resize` function instead.
This method is difficult to implement safely and may be deprecated in
future releases of NumPy.
"""
# Note : the 'order' keyword looks broken, let's just drop it
errmsg = "A masked array does not own its data "\
"and therefore cannot be resized.\n" \
"Use the numpy.ma.resize function instead."
raise ValueError(errmsg)
def test_wahba():
lat = 45
Cnb = dcm.from_hpr(45, -30, 60)
dt = 1e-1
n = 1000
gyro = np.array([0, 1 / np.sqrt(2), 1 / np.sqrt(2)]) * earth.RATE * dt
gyro = Cnb.T.dot(gyro)
gyro = np.resize(gyro, (n, 3))
accel = np.array([0, 0, earth.gravity(1 / np.sqrt(2))]) * dt
accel = Cnb.T.dot(accel)
accel = np.resize(accel, (n, 3))
np.random.seed(0)
gyro += 1e-6 * np.random.randn(*gyro.shape) * dt
accel += 1e-4 * np.random.randn(*accel.shape) * dt
phi, dv = coning_sculling(gyro, accel)
hpr, P = align.align_wahba(dt, phi, dv, lat)
assert_allclose(hpr, [45, -30, 60], rtol=1e-3)
def _verify_param(param, name, only_positive=False):
if param is None:
return None
param = np.asarray(param)
if param.ndim == 0:
param = np.resize(param, 3)
if param.shape != (3,):
raise ValueError("`{}` might be float or array with "
"3 elements.".format(name))
if only_positive and np.any(param <= 0):
raise ValueError("`{}` must contain positive values.".format(name))
elif np.any(param < 0):
raise ValueError("`{}` must contain non-negative values."
.format(name))
return param
def __init__(self, doc=None, lda=None, max_doc_len=None, num_topics=None, gamma=None, lhood=None):
self.doc = doc
self.lda = lda
self.gamma = gamma
self.lhood = lhood
if self.gamma is None:
self.gamma = np.zeros(num_topics)
if self.lhood is None:
self.lhood = np.zeros(num_topics + 1)
if max_doc_len is not None and num_topics is not None:
self.phi = np.resize(np.zeros(max_doc_len * num_topics), (max_doc_len, num_topics))
self.log_phi = np.resize(np.zeros(max_doc_len * num_topics), (max_doc_len, num_topics))
# the following are class variables which are to be integrated during Document Influence Model
self.doc_weight = None
self.renormalized_doc_weight = None
def resize(self, newshape, refcheck=True, order=False):
"""
.. warning::
This method does nothing, except raise a ValueError exception. A
masked array does not own its data and therefore cannot safely be
resized in place. Use the `numpy.ma.resize` function instead.
This method is difficult to implement safely and may be deprecated in
future releases of NumPy.
"""
# Note : the 'order' keyword looks broken, let's just drop it
errmsg = "A masked array does not own its data "\
"and therefore cannot be resized.\n" \
"Use the numpy.ma.resize function instead."
raise ValueError(errmsg)
def PostprocessImage(img):
"""
Postprocess target style image
1. add the images dataset mean to optimized image
2. swap axis (b,g,r) to (r,g,b) and save it
Parameters
--------
img: ndarray (1x3xMxN), optimized image
Returns
out : ndarray (3xMxN), Postprocessed image
"""
img = np.resize(img, (3, img.shape[2], img.shape[3]))
img[0, :] += 123.68
img[1, :] += 116.779
img[2, :] += 103.939
img = np.swapaxes(img, 0, 2)
img = np.swapaxes(img, 0, 1)
img = np.clip(img, 0, 255)
return img.astype('uint8')
def read_lines(self, track_id, offset, count):
lines = []
max_num_values = 0
for i in range(0, count - 1):
num_values = self.RA.get_values_count(track_id, i) #????? ????? ????? ? ??????
if num_values > max_num_values:
max_num_values = num_values
buffer_output = (c_float * num_values)() #??????????? ????? ? ??????
num_values = self.RA.get_values(track_id, offset + i, byref(buffer_output), num_values) #?????? ?????? ?? ??
lines.append(buffer_output)
retval = np.zeros((count, max_num_values), dtype=np.uint16)
for i in range(count-1):
nparr = np.asarray(lines[i], dtype=np.float16)
nparr = np.multiply(nparr, 65535)
nparr = np.asarray(nparr, dtype=np.uint16)
a = np.resize(nparr, retval[i].shape)
retval[i] += a
return retval
#< gidroGraf_DBreader.c_float_Array_6252 object at 0x7fcb40a2df28 >
#< gidroGraf_DBreader.c_float_Array_20837 object at 0x7f142f2eef28 >
def add_col_mult(self, vec, mult, target = None):
"""
Add a multiple of vector vec to every column of the matrix. If a target
is provided, it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (b_ == 1 and a_ == a):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = self.numpy_array + vec.numpy_array * mult
return target
def add_row_vec(self, vec, target = None):
"""
Add vector vec to every row of the matrix. If a target is provided,
it is used to store the result instead of self.
"""
a, b = self.shape
a_, b_ = vec.shape
if not (a_ == 1 and b_ == b):
raise IncompatibleDimensionsException
if target is None:
target = self
target.resize(self.shape)
target.numpy_array[:] = vec.numpy_array + self.numpy_array
return target