Python numpy.flipud() Examples
The following are 30 code examples for showing how to use numpy.flipud(). 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: spectrum_painter Author: polygon File: spectrum_painter.py License: MIT License | 7 votes |
def convert_image(self, filename): pic = img.imread(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
Project: kvae Author: simonkamronn File: movie.py License: MIT License | 7 votes |
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 3
Project: simnibs Author: simnibs File: grid.py License: 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 4
Project: me-ica Author: ME-ICA File: test_orientations.py License: 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 5
Project: me-ica Author: ME-ICA File: test_funcs.py License: 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 6
Project: connecting_the_dots Author: autonomousvision File: geometry.py License: MIT License | 6 votes |
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 7
Project: Advanced_Lane_Lines Author: ChengZhongShen File: image_process.py License: MIT License | 6 votes |
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 8
Project: pulse2percept Author: pulse2percept File: beyeler2019.py License: 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 9
Project: gmpe-smtk Author: GEMScienceTools File: strong_motion_selector.py License: 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 10
Project: DSMnet Author: wyf2017 File: img_rw_pfm.py License: Apache License 2.0 | 6 votes |
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 11
Project: KAIR Author: cszn File: utils_image.py License: MIT License | 6 votes |
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 12
Project: inky-phat Author: pimoroni File: inky212x104.py License: MIT License | 6 votes |
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 13
Project: sklearn-audio-transfer-learning Author: jordipons File: utils.py License: ISC License | 5 votes |
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 14
Project: PSMNet Author: JiaRenChang File: readpfm.py License: MIT License | 5 votes |
def readPFM(file): file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if header == 'PF': color = True elif header == 'Pf': color = False else: raise Exception('Not a PFM file.') dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline()) if dim_match: width, height = map(int, dim_match.groups()) else: raise Exception('Malformed PFM header.') scale = float(file.readline().rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width) data = np.reshape(data, shape) data = np.flipud(data) return data, scale
Example 15
Project: PSMNet Author: JiaRenChang File: readpfm.py License: MIT License | 5 votes |
def readPFM(file): file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() encode_type = chardet.detect(header) header = header.decode(encode_type['encoding']) if header == 'PF': color = True elif header == 'Pf': color = False else: raise Exception('Not a PFM file.') dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode(encode_type['encoding'])) if dim_match: width, height = map(int, dim_match.groups()) else: raise Exception('Malformed PFM header.') scale = float(file.readline().rstrip().decode(encode_type['encoding'])) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width) data = np.reshape(data, shape) data = np.flipud(data) return data, scale
Example 16
Project: NeuroKit Author: neuropsychology File: ecg_simulate.py License: MIT License | 5 votes |
def _ecg_simulate_rrprocess( flo=0.1, fhi=0.25, flostd=0.01, fhistd=0.01, lfhfratio=0.5, hrmean=60, hrstd=1, sfrr=1, n=256 ): w1 = 2 * np.pi * flo w2 = 2 * np.pi * fhi c1 = 2 * np.pi * flostd c2 = 2 * np.pi * fhistd sig2 = 1 sig1 = lfhfratio rrmean = 60 / hrmean rrstd = 60 * hrstd / (hrmean * hrmean) df = sfrr / n w = np.arange(n) * 2 * np.pi * df dw1 = w - w1 dw2 = w - w2 Hw1 = sig1 * np.exp(-0.5 * (dw1 / c1) ** 2) / np.sqrt(2 * np.pi * c1 ** 2) Hw2 = sig2 * np.exp(-0.5 * (dw2 / c2) ** 2) / np.sqrt(2 * np.pi * c2 ** 2) Hw = Hw1 + Hw2 Hw0 = np.concatenate((Hw[0 : int(n / 2)], Hw[int(n / 2) - 1 :: -1])) Sw = (sfrr / 2) * np.sqrt(Hw0) ph0 = 2 * np.pi * np.random.uniform(size=int(n / 2 - 1)) ph = np.concatenate([[0], ph0, [0], -np.flipud(ph0)]) SwC = Sw * np.exp(1j * ph) x = (1 / n) * np.real(np.fft.ifft(SwC)) xstd = np.std(x) ratio = rrstd / xstd return rrmean + x * ratio # Return RR
Example 17
Project: me-ica Author: ME-ICA File: orientations.py License: GNU Lesser General Public License v2.1 | 5 votes |
def apply_orientation(arr, ornt): ''' Apply transformations implied by `ornt` to the first n axes of the array `arr` Parameters ---------- arr : array-like of data with ndim >= n ornt : (n,2) orientation array orientation transform. ``ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0`` and ``ornt[0,1] == -1``, and there's an array ``arr`` of shape `shape`, the flip would correspond to the effect of ``np.flipud(arr)``. ``ornt[:,0]`` is the transpose that needs to be done to the implied array, as in ``arr.transpose(ornt[:,0])`` Returns ------- t_arr : ndarray data array `arr` transformed according to ornt ''' t_arr = np.asarray(arr) ornt = np.asarray(ornt) n = ornt.shape[0] if t_arr.ndim < n: raise OrientationError('Data array has fewer dimensions than ' 'orientation') # no coordinates can be dropped for applying the orientations if np.any(np.isnan(ornt[:, 0])): raise OrientationError('Cannot drop coordinates when ' 'applying orientation to data') # apply ornt transformations for ax, flip in enumerate(ornt[:, 1]): if flip == -1: t_arr = flip_axis(t_arr, axis=ax) full_transpose = np.arange(t_arr.ndim) # ornt indicates the transpose that has occurred - we reverse it full_transpose[:n] = np.argsort(ornt[:, 0]) t_arr = t_arr.transpose(full_transpose) return t_arr
Example 18
Project: me-ica Author: ME-ICA File: orientations.py License: GNU Lesser General Public License v2.1 | 5 votes |
def flip_axis(arr, axis=0): ''' Flip contents of `axis` in array `arr` ``flip_axis`` is the same transform as ``np.flipud``, but for any axis. For example ``flip_axis(arr, axis=0)`` is the same transform as ``np.flipud(arr)``, and ``flip_axis(arr, axis=1)`` is the same transform as ``np.fliplr(arr)`` Parameters ---------- arr : array-like axis : int, optional axis to flip. Default `axis` == 0 Returns ------- farr : array Array with axis `axis` flipped Examples -------- >>> a = np.arange(6).reshape((2,3)) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> flip_axis(a, axis=0) array([[3, 4, 5], [0, 1, 2]]) >>> flip_axis(a, axis=1) array([[2, 1, 0], [5, 4, 3]]) ''' arr = np.asanyarray(arr) arr = arr.swapaxes(0, axis) arr = np.flipud(arr) return arr.swapaxes(axis, 0)
Example 19
Project: insightface Author: deepinsight File: detect_face.py License: MIT License | 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 20
Project: gradio-UI Author: gradio-app File: webcam.py License: Apache License 2.0 | 5 votes |
def snap(image): return np.flipud(image)
Example 21
Project: PyTorchConv3D Author: tomrunia File: spatial_transforms.py License: Apache License 2.0 | 5 votes |
def __call__(self, img): """ Args: img (PIL.Image): Image to be flipped. Returns: PIL.Image: Randomly flipped image. """ if self.p < 0.5: if isinstance(img, np.ndarray): return np.flipud(img).copy() else: return img.transpose(Image.FLIP_TOP_BOTTOM) return img
Example 22
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 5 votes |
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 23
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 5 votes |
def test_hanning(self): # check symmetry w = hanning(10) assert_array_almost_equal(w, flipud(w), 7) # check known value assert_almost_equal(np.sum(w, axis=0), 4.500, 4)
Example 24
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 5 votes |
def test_hamming(self): # check symmetry w = hamming(10) assert_array_almost_equal(w, flipud(w), 7) # check known value assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)
Example 25
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 5 votes |
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 26
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 5 votes |
def test_blackman(self): # check symmetry w = blackman(10) assert_array_almost_equal(w, flipud(w), 7) # check known value assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
Example 27
Project: DSMnet Author: wyf2017 File: img_rw_pfm.py License: Apache License 2.0 | 5 votes |
def load_pfm(fname): assert os.path.isfile(fname) color = None width = None height = None scale = None endian = None file = open(fname) header = file.readline().rstrip() if header == 'PF': color = True elif header == 'Pf': color = False else: raise Exception('Not a PFM file.') dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline()) if dim_match: width, height = map(int, dim_match.groups()) else: raise Exception('Malformed PFM header.') scale = float(file.readline().rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width) return np.flipud(np.reshape(data, shape)).copy(), scale
Example 28
Project: deepchem Author: deepchem File: transformers.py License: MIT License | 5 votes |
def flip(self, direction="lr"): """ Flips the image Parameters: direction - "lr" denotes left-right fliplr "ud" denotes up-down flip """ if direction == "lr": return np.fliplr(self.Image) elif direction == "ud": return np.flipud(self.Image) else: raise ValueError( "Invalid flip command : Enter either lr (for left to right flip) or ud (for up to down flip)" )
Example 29
Project: deepchem Author: deepchem File: test_transformers.py License: MIT License | 5 votes |
def test_flipping(self): # Check flip dt = DataTransforms(self.d) flip_lr = dt.flip(direction="lr") flip_ud = dt.flip(direction="ud") check_lr = np.fliplr(self.d) check_ud = np.flipud(self.d) assert np.allclose(flip_ud, check_ud) assert np.allclose(flip_lr, check_lr)
Example 30
Project: typhon Author: atmtools File: common.py License: MIT License | 5 votes |
def cmap_from_act(file, name=None): """Import colormap from Adobe Color Table file. Parameters: file (str): Path to act file. name (str): Colormap name. Defaults to filename without extension. Returns: LinearSegmentedColormap. """ # Extract colormap name from filename. if name is None: name = os.path.splitext(os.path.basename(file))[0] # Read binary file and determine number of colors rgb = np.fromfile(file, dtype=np.uint8) if rgb.shape[0] >= 770: ncolors = rgb[768] * 2**8 + rgb[769] else: ncolors = 256 colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255 # Create and register colormap... cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors) plt.register_cmap(cmap=cmap) # Register colormap. # ... and the reversed colormap. cmap_r = LinearSegmentedColormap.from_list( name + '_r', np.flipud(colors), N=ncolors) plt.register_cmap(cmap=cmap_r) return cmap