Python numpy.flipud() Examples

The following are 30 code examples of numpy.flipud(). 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 , or try the search function .
Example #1
```def convert_image(self, filename):
# Set FFT size to be double the image size so that the edge of the spectrum stays clear
# preventing some bandfilter artifacts
self.NFFT = 2*pic.shape[1]

# Repeat image lines until each one comes often enough to reach the desired line time
ffts = (np.flipud(np.repeat(pic[:, :, 0], self.repetitions, axis=0) / 16.)**2.) / 256.

# Embed image in center bins of the FFT
fftall = np.zeros((ffts.shape[0], self.NFFT))
startbin = int(self.NFFT/4)
fftall[:, startbin:(startbin+pic.shape[1])] = ffts

# Generate random phase vectors for the FFT bins, this is important to prevent high peaks in the output
# The phases won't be visible in the spectrum
phases = 2*np.pi*np.random.rand(*fftall.shape)
rffts = fftall * np.exp(1j*phases)

# Perform the FFT per image line, then concatenate them to form the final signal
timedata = np.fft.ifft(np.fft.ifftshift(rffts, axes=1), axis=1) / np.sqrt(float(self.NFFT))
linear = timedata.flatten()
linear = linear / np.max(np.abs(linear))
return linear ```
Example #2
 Source File: grid.py    From simnibs with GNU General Public License v3.0 7 votes
```def quadrature_cc_1D(N):
""" Computes the Clenshaw Curtis nodes and weights """
N = np.int(N)
if N == 1:
knots = 0
weights = 2
else:
n = N - 1
C = np.zeros((N,2))
k = 2*(1+np.arange(np.floor(n/2)))
C[::2,0] = 2/np.hstack((1, 1-k*k))
C[1,1] = -n
V = np.vstack((C,np.flipud(C[1:n,:])))
F = np.real(ifft(V, n=None, axis=0))
knots = F[0:N,1]
weights = np.hstack((F[0,0],2*F[1:n,0],F[n,0]))

return knots, weights ```
Example #3
```def save_movie_to_frame(images, filename, idx=0, cmap='Blues'):
# Collect to single image
image = movie_to_frame(images[idx])

# Flip it
# image = np.fliplr(image)
# image = np.flipud(image)

f = plt.figure(figsize=[12, 12])
plt.imshow(image, cmap=plt.cm.get_cmap(cmap), interpolation='none', vmin=0, vmax=1)

plt.axis('image')
plt.xticks([])
plt.yticks([])
plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
plt.close(f) ```
Example #4
 Source File: test_funcs.py    From me-ica with GNU Lesser General Public License v2.1 6 votes
```def test_closest_canonical():
arr = np.arange(24).reshape((2,3,4,1))
# no funky stuff, returns same thing
img = Nifti1Image(arr, np.eye(4))
xyz_img = as_closest_canonical(img)
assert_true(img is xyz_img)
# a axis flip
img = Nifti1Image(arr, np.diag([-1,1,1,1]))
xyz_img = as_closest_canonical(img)
assert_false(img is xyz_img)
out_arr = xyz_img.get_data()
assert_array_equal(out_arr, np.flipud(arr))
# no error for enforce_diag in this case
xyz_img = as_closest_canonical(img, True)
# but there is if the affine is not diagonal
aff = np.eye(4)
aff[0,1] = 0.1
# although it's more or less canonical already
img = Nifti1Image(arr, aff)
xyz_img = as_closest_canonical(img)
assert_true(img is xyz_img)
# it's still not diagnonal
assert_raises(OrientationError, as_closest_canonical, img, True) ```
Example #5
 Source File: test_orientations.py    From me-ica with GNU Lesser General Public License v2.1 6 votes
```def test_flip_axis():
a = np.arange(24).reshape((2,3,4))
assert_array_equal(
flip_axis(a),
np.flipud(a))
assert_array_equal(
flip_axis(a, axis=0),
np.flipud(a))
assert_array_equal(
flip_axis(a, axis=1),
np.fliplr(a))
# check accepts array-like
assert_array_equal(
flip_axis(a.tolist(), axis=0),
np.flipud(a))
# third dimension
b = a.transpose()
b = np.flipud(b)
b = b.transpose()
assert_array_equal(flip_axis(a, axis=2), b) ```
Example #6
```def augment_img(img, mode=0):
'''Kai Zhang (github: https://github.com/cszn)
'''
if mode == 0:
return img
elif mode == 1:
return np.flipud(np.rot90(img))
elif mode == 2:
return np.flipud(img)
elif mode == 3:
return np.rot90(img, k=3)
elif mode == 4:
return np.flipud(np.rot90(img, k=2))
elif mode == 5:
return np.rot90(img)
elif mode == 6:
return np.rot90(img, k=2)
elif mode == 7:
return np.flipud(np.rot90(img, k=3)) ```
Example #7
```def decompose_projection_matrix(P, return_t=True):
if P.shape[0] != 3 or P.shape[1] != 4:
raise Exception('P has to be 3x4')
M = P[:, :3]
C = -np.linalg.inv(M) @ P[:, 3:]

R,K = np.linalg.qr(np.flipud(M).T)
K = np.flipud(K.T)
K = np.fliplr(K)
R = np.flipud(R.T)

T = np.diag(np.sign(np.diag(K)))
K = K @ T
R = T @ R

if np.linalg.det(R) < 0:
R *= -1

K /= K[2,2]
if return_t:
return K, R, cameracenter_to_translation(R, C)
else:
return K, R, C ```
Example #8
```def draw_lane_fit(undist, warped ,Minv, left_fitx, right_fitx, ploty):
# Drawing
# Create an image to draw the lines on
warp_zero = np.zeros_like(warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))

# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))

# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))

# Warp the blank back to original image space using inverse perspective matrix(Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)

return result ```
Example #9
 Source File: beyeler2019.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 6 votes
```def calc_axon_contribution(self, axons):
xyret = np.column_stack((self.grid.xret.ravel(),
self.grid.yret.ravel()))
# Only include axon segments that are < `max_d2` from the soma. These
# axon segments will have `sensitivity` > `self.min_ax_sensitivity`:
max_d2 = -2.0 * self.axlambda ** 2 * np.log(self.min_ax_sensitivity)
axon_contrib = []
for xy, bundle in zip(xyret, axons):
idx = np.argmin((bundle[:, 0] - xy[0]) ** 2 +
(bundle[:, 1] - xy[1]) ** 2)
# Cut off the part of the fiber that goes beyond the soma:
axon = np.flipud(bundle[0: idx + 1, :])
# Add the exact location of the soma:
axon = np.insert(axon, 0, xy, axis=0)
# For every axon segment, calculate distance from soma by
# summing up the individual distances between neighboring axon
# segments (by "walking along the axon"):
d2 = np.cumsum(np.diff(axon[:, 0], axis=0) ** 2 +
np.diff(axon[:, 1], axis=0) ** 2)
idx_d2 = d2 < max_d2
sensitivity = np.exp(-d2[idx_d2] / (2.0 * self.axlambda ** 2))
idx_d2 = np.insert(idx_d2, 0, False)
contrib = np.column_stack((axon[idx_d2, :], sensitivity))
axon_contrib.append(contrib)
return axon_contrib ```
Example #10
```def update(self):
if self.inky_colour is None:
raise RuntimeError("You must specify which colour of Inky pHAT you're using: inkyphat.set_colour('red', 'black' or 'yellow')")

self._display_init()

x1, x2 = self.update_x1, self.update_x2
y1, y2 = self.update_y1, self.update_y2

region = self.buffer[y1:y2, x1:x2]

if self.v_flip:
region = numpy.fliplr(region)

if self.h_flip:
region = numpy.flipud(region)

buf_red = numpy.packbits(numpy.where(region == RED, 1, 0)).tolist()
if self.inky_version == 1:
buf_black = numpy.packbits(numpy.where(region == 0, 0, 1)).tolist()
else:
buf_black = numpy.packbits(numpy.where(region == BLACK, 0, 1)).tolist()

self._display_update(buf_black, buf_red)
self._display_fini() ```
Example #11
 Source File: strong_motion_selector.py    From gmpe-smtk with GNU Affero General Public License v3.0 6 votes
```def rank_sites_by_record_count(database, threshold=0):
"""
Function to determine count the number of records per site and return
the list ranked in descending order
"""
name_id_list = [(rec.site.id, rec.site.name) for rec in database.records]
name_id = dict([])
for name_id_pair in name_id_list:
if name_id_pair[0] in name_id:
name_id[name_id_pair[0]]["Count"] += 1
else:
name_id[name_id_pair[0]] = {"Count": 1, "Name": name_id_pair[1]}
counts = np.array([name_id[key]["Count"] for key in name_id])
sort_id = np.flipud(np.argsort(counts))

key_vals = list(name_id)
output_list = []
for idx in sort_id:
if name_id[key_vals[idx]]["Count"] >= threshold:
output_list.append((key_vals[idx], name_id[key_vals[idx]]))
return OrderedDict(output_list) ```
Example #12
```def save_pfm(fname, image, scale=1):
file = open(fname, 'w')
color = None

if image.dtype.name != 'float32':
raise Exception('Image dtype must be float32.')

if len(image.shape) == 3 and image.shape[2] == 3: # color image
color = True
elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale
color = False
else:
raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')

file.write('PF\n' if color else 'Pf\n')
file.write('%d %d\n' % (image.shape[1], image.shape[0]))

endian = image.dtype.byteorder

if endian == '<' or endian == '=' and sys.byteorder == 'little':
scale = -scale

file.write('%f\n' % scale)

np.flipud(image).tofile(file) ```
Example #13
```def hist_curve(im):
h = np.zeros((300, 256, 3))
if len(im.shape) == 2:
color = [(255, 255, 255)]
elif im.shape[2] == 3:
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
for ch, col in enumerate(color):
hist_item = cv2.calcHist([im], [ch], None, [256], [0, 256])
cv2.normalize(hist_item, hist_item, 0, 255, cv2.NORM_MINMAX)
hist = np.int32(np.around(hist_item))
pts = np.int32(np.column_stack((bins, hist)))
cv2.polylines(h, [pts], False, col)
y = np.flipud(h)
return y ```
Example #14
 Source File: wave.py    From ocelot with GNU General Public License v3.0 5 votes
```def dfl_trf(dfl, trf, mode, dump_proj=False):
"""
Multiplication of radiation field by given transfer function (transmission or ferlection, given by mode)
dfl is RadiationField() object (will be mutated)
trf is TransferFunction() object
mode is either 'tr' for transmission
or 'ref' for reflection
"""
# assert dfl.domain_z == 'f', 'dfl_trf works only in frequency domain!'
_logger.info('multiplying dfl by trf')
start = time.time()
# assert trf.__class__==TransferFunction,'Wrong TransferFunction class'
assert dfl.domain_z == 'f', 'wrong dfl domain (must be frequency)!'
if mode == 'tr':
filt = trf.tr
elif mode == 'ref':
filt = trf.ref
else:
raise AttributeError('Wrong z_domain attribute')
filt_lamdscale = 2 * np.pi / trf.k
if min(dfl.scale_z()) > max(filt_lamdscale) or max(dfl.scale_z()) < min(filt_lamdscale):
raise ValueError('frequency scales of dfl and transfer function do not overlap')

# filt_interp_re = np.flipud(np.interp(np.flipud(dfl.scale_z()), np.flipud(filt_lamdscale), np.flipud(np.real(filt))))
# filt_interp_im = np.flipud(np.interp(np.flipud(dfl.scale_z()), np.flipud(filt_lamdscale), np.flipud(np.imag(filt))))
# filt_interp = filt_interp_re - 1j * filt_interp_im
# del filt_interp_re, filt_interp_im
filt_interp_abs = np.flipud(np.interp(np.flipud(dfl.scale_z()), np.flipud(filt_lamdscale), np.flipud(np.abs(filt))))
filt_interp_ang = np.flipud(
np.interp(np.flipud(dfl.scale_z()), np.flipud(filt_lamdscale), np.flipud(np.angle(filt))))
filt_interp = filt_interp_abs * np.exp(-1j * filt_interp_ang)  # *(trf.xlamds/dfl.xlamds)
del filt_interp_abs, filt_interp_ang

dfl.fld = dfl.fld * filt_interp[:, np.newaxis, np.newaxis]

t_func = time.time() - start
_logger.debug(ind_str + 'done in %.2f sec' % t_func)
if dump_proj:
return filt_interp ```
Example #15
 Source File: _eigenpro.py    From scikit-learn-extra with BSD 3-Clause "New" or "Revised" License 5 votes
```def _nystrom_svd(self, X, n_components):
"""Compute the top eigensystem of a kernel
operator using Nystrom method

Parameters
----------
X : {float, array}, shape = [n_subsamples, n_features]
Subsample feature matrix.

n_components : int
Number of top eigencomponents to be restored.

Returns
-------
E : {float, array}, shape = [k]
Top eigenvalues.

Lambda : {float, array}, shape = [n_subsamples, k]
Top eigenvectors of a subsample kernel matrix (which can be
directly used to approximate the eigenfunctions of the kernel
operator).
"""
m, _ = X.shape
K = self._kernel(X, X)

W = K / m
try:
E, Lambda = eigh(W, eigvals=(m - n_components, m - 1))
except LinAlgError:
# Use float64 when eigh fails due to precision
W = np.float64(W)
E, Lambda = eigh(W, eigvals=(m - n_components, m - 1))
E, Lambda = np.float32(E), np.float32(Lambda)
# Flip so eigenvalues are in descending order.
E = np.maximum(np.float32(1e-7), np.flipud(E))
Lambda = np.fliplr(Lambda)[:, :n_components] / np.sqrt(
m, dtype="float32"
)

return E, Lambda ```
Example #16
```def test_4d(self):
a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
for i in range(a.ndim):
assert_equal(np.flip(a, i), np.flipud(a.swapaxes(0, i)).swapaxes(i, 0)) ```
Example #17
 Source File: detect_face.py    From TNT with GNU General Public License v3.0 5 votes
```def generateBoundingBox(imap, reg, scale, t):
"""Use heatmap to generate bounding boxes"""
stride=2
cellsize=12

imap = np.transpose(imap)
dx1 = np.transpose(reg[:,:,0])
dy1 = np.transpose(reg[:,:,1])
dx2 = np.transpose(reg[:,:,2])
dy2 = np.transpose(reg[:,:,3])
y, x = np.where(imap >= t)
if y.shape[0]==1:
dx1 = np.flipud(dx1)
dy1 = np.flipud(dy1)
dx2 = np.flipud(dx2)
dy2 = np.flipud(dy2)
score = imap[(y,x)]
reg = np.transpose(np.vstack([ dx1[(y,x)], dy1[(y,x)], dx2[(y,x)], dy2[(y,x)] ]))
if reg.size==0:
reg = np.empty((0,3))
bb = np.transpose(np.vstack([y,x]))
q1 = np.fix((stride*bb+1)/scale)
q2 = np.fix((stride*bb+cellsize-1+1)/scale)
boundingbox = np.hstack([q1, q2, np.expand_dims(score,1), reg])
return boundingbox, reg

# function pick = nms(boxes,threshold,type) ```
Example #18
```def vertical_flip(x):
for i in range(x.shape[0]):
x[i] = np.flipud(x[i])
return x ```
Example #19
```def testFlipExecution(self):
a = arange(8, chunk_size=2).reshape((2, 2, 2))

t = flip(a, 0)

res = self.executor.execute_tensor(t, concat=True)[0]
expected = np.flip(np.arange(8).reshape(2, 2, 2), 0)
np.testing.assert_equal(res, expected)

t = flip(a, 1)

res = self.executor.execute_tensor(t, concat=True)[0]
expected = np.flip(np.arange(8).reshape(2, 2, 2), 1)
np.testing.assert_equal(res, expected)

t = flipud(a)

res = self.executor.execute_tensor(t, concat=True)[0]
expected = np.flipud(np.arange(8).reshape(2, 2, 2))
np.testing.assert_equal(res, expected)

t = fliplr(a)

res = self.executor.execute_tensor(t, concat=True)[0]
expected = np.fliplr(np.arange(8).reshape(2, 2, 2))
np.testing.assert_equal(res, expected) ```
Example #20
```def per_channel_flipud(x):
x_ = x.copy()
for i, channel in enumerate(x):
x_[i, :, :] = np.flipud(channel)
return x_ ```
Example #21
```def test_time_augmentation_transform(image, tta_parameters):
if tta_parameters['ud_flip']:
image = np.flipud(image)
if tta_parameters['lr_flip']:
image = np.fliplr(image)
if tta_parameters['color_shift']:
tta_intensity = reseed(tta_intensity_seq, deterministic=False)
image = tta_intensity.augment_image(image)
image = rotate(image, tta_parameters['rotation'])
return image ```
Example #22
```def test_bartlett(self):
# check symmetry
w = bartlett(10)
assert_array_almost_equal(w, flipud(w), 7)
# check known value
assert_almost_equal(np.sum(w, axis=0), 4.4444, 4) ```
Example #23
 Source File: tapers.py    From pylops with GNU Lesser General Public License v3.0 5 votes
```def cosinetaper(nmask, ntap, square=False):
r"""1D Cosine or Cosine square taper

at edges of size ``ntap``

Parameters
----------
ntap : :obj:`int`
Number of samples of hanning tapering at edges
square : :obj:`bool`
Cosine square taper (``True``)or Cosine taper (``False``)

Returns
-------
taper : :obj:`numpy.ndarray`
taper

"""
exponent = 1 if not square else 2
cos_win = (0.5*(np.cos((np.arange(ntap * 2 - 1)-
(ntap * 2 - 2)/2)*np.pi/((ntap * 2 - 2)/2)) + 1.))**exponent
st_tpr = cos_win[:ntap, ]
mid_tpr = np.ones([nmask - (2 * ntap), ])
end_tpr = np.flipud(st_tpr)
tpr_1d = np.concatenate([st_tpr, mid_tpr, end_tpr])
return tpr_1d ```
Example #24
 Source File: tapers.py    From pylops with GNU Lesser General Public License v3.0 5 votes
```def hanningtaper(nmask, ntap):
r"""1D Hanning taper

at edges of size ``ntap``

Parameters
----------
ntap : :obj:`int`
Number of samples of hanning tapering at edges

Returns
-------
taper : :obj:`numpy.ndarray`
taper

"""
if ntap > 0:
raise ValueError('ntap=%d must be smaller or '
'equal than %d' %(ntap, ntap_min))
han_win = np.hanning(ntap*2-1)
st_tpr = han_win[:ntap, ]
mid_tpr = np.ones([nmask - (2 * ntap), ])
end_tpr = np.flipud(st_tpr)
tpr_1d = np.concatenate([st_tpr, mid_tpr, end_tpr])
return tpr_1d ```
Example #25
 Source File: wavelets.py    From pylops with GNU Lesser General Public License v3.0 5 votes
```def gaussian(t, std=1):
r"""Gaussian wavelet

Create a Gaussian wavelet given time axis ``t``
and standard deviation ``std`` using
:py:func:`scipy.signal.windows.gaussian`.

Parameters
----------
t : :obj:`numpy.ndarray`
Time axis (positive part including zero sample)
std : :obj:`float`, optional
Standard deviation of gaussian

Returns
-------
w : :obj:`numpy.ndarray`
Wavelet
t : :obj:`numpy.ndarray`
Symmetric time axis
wcenter : :obj:`int`
Index of center of wavelet

"""
if len(t)%2 == 0:
t = t[:-1]
warnings.warn('one sample removed from time axis...')

w = spgauss(len(t)*2-1, std=std)
t = np.concatenate((np.flipud(-t[1:]), t), axis=0)
wcenter = np.argmax(np.abs(w))

return w, t, wcenter ```
Example #26
 Source File: wavelets.py    From pylops with GNU Lesser General Public License v3.0 5 votes
```def ricker(t, f0=10):
r"""Ricker wavelet

Create a Ricker wavelet given time axis ``t`` and central frequency ``f_0``

Parameters
----------
t : :obj:`numpy.ndarray`
Time axis (positive part including zero sample)
f0 : :obj:`float`, optional
Central frequency

Returns
-------
w : :obj:`numpy.ndarray`
Wavelet
t : :obj:`numpy.ndarray`
Symmetric time axis
wcenter : :obj:`int`
Index of center of wavelet

"""
if len(t)%2 == 0:
t = t[:-1]
warnings.warn('one sample removed from time axis...')

w = (1 - 2 * (np.pi * f0 * t) ** 2) * np.exp(-(np.pi * f0 * t) ** 2)

w = np.concatenate((np.flipud(w[1:]), w), axis=0)
t = np.concatenate((np.flipud(-t[1:]), t), axis=0)
wcenter = np.argmax(np.abs(w))

return w, t, wcenter ```
Example #27
```def fullfp(truth):
rsize = np.flipud(truth.shape)
return buzz.Footprint(tl=(0, 0), rsize=rsize, size=rsize) ```
Example #28
```def shape(self):
"""Pixel quantities: (pixel per column, pixel per line)"""
return np.flipud(self._rsize) ```
Example #29
```def matrix_visualization(matrix,title=None):
""" Visualize 2D matrices like spectrograms or feature maps.
"""
plt.figure()
plt.imshow(np.flipud(matrix.T),interpolation=None)
plt.colorbar()
if title!=None:
plt.title(title)
plt.show() ```
Example #30
```def test_hamming(self):