Python numpy.swapaxes() Examples
The following are 30 code examples for showing how to use numpy.swapaxes(). 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: fenics-topopt Author: zfergus File: stress_gui.py License: MIT License | 6 votes |
def update(self, xPhys, u, title=None): """Plot to screen""" self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T) stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu) # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu) self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress))) stress_rgba = self.myColorMap.to_rgba(stress) stress_rgba[:, :, 3] = xPhys.reshape(-1, 1) self.stress_im.set_array(np.swapaxes( stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1)) self.fig.canvas.draw() self.fig.canvas.flush_events() if title is not None: plt.title(title) else: plt.xlabel("Max stress = {:.2f}".format(max(stress)[0])) plt.pause(0.01)
Example 2
Project: fenics-topopt Author: zfergus File: stress_gui.py License: MIT License | 6 votes |
def update(self, xPhys, u, title=None): """Plot to screen""" self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T) stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu) # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu) self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress))) stress_rgba = self.myColorMap.to_rgba(stress) stress_rgba[:, :, 3] = xPhys.reshape(-1, 1) self.stress_im.set_array(np.swapaxes( stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1)) self.fig.canvas.draw() self.fig.canvas.flush_events() if title is not None: plt.title(title) else: plt.xlabel("Max stress = {:.2f}".format(max(stress)[0])) plt.pause(0.01)
Example 3
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: image_segmentaion.py License: Apache License 2.0 | 6 votes |
def get_data(img_path): """get the (1, 3, h, w) np.array data for the supplied image Args: img_path (string): the input image path Returns: np.array: image data in a (1, 3, h, w) shape """ mean = np.array([123.68, 116.779, 103.939]) # (R,G,B) img = Image.open(img_path) img = np.array(img, dtype=np.float32) reshaped_mean = mean.reshape(1, 1, 3) img = img - reshaped_mean img = np.swapaxes(img, 0, 2) img = np.swapaxes(img, 1, 2) img = np.expand_dims(img, axis=0) return img
Example 4
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: nstyle.py License: Apache License 2.0 | 6 votes |
def PreprocessContentImage(path, long_edge): img = io.imread(path) logging.info("load the content image, size = %s", img.shape[:2]) factor = float(long_edge) / max(img.shape[:2]) new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor)) resized_img = transform.resize(img, new_size) sample = np.asarray(resized_img) * 256 # swap axes to make image from (224, 224, 3) to (3, 224, 224) sample = np.swapaxes(sample, 0, 2) sample = np.swapaxes(sample, 1, 2) # sub mean sample[0, :] -= 123.68 sample[1, :] -= 116.779 sample[2, :] -= 103.939 logging.info("resize the content image to %s", new_size) return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
Example 5
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: mxnet_predict_example.py License: Apache License 2.0 | 6 votes |
def PreprocessImage(path, show_img=False): # load image img = io.imread(path) print("Original Image Shape: ", img.shape) # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + short_egde] # resize to 224, 224 resized_img = transform.resize(crop_img, (224, 224)) # convert to numpy.ndarray sample = np.asarray(resized_img) * 255 # swap axes to make image from (224, 224, 3) to (3, 224, 224) sample = np.swapaxes(sample, 0, 2) sample = np.swapaxes(sample, 1, 2) # sub mean return sample # Get preprocessed batch (single image batch)
Example 6
Project: Deep_Learning_Weather_Forecasting Author: BruceBinBoxing File: competition_model_class.py License: Apache License 2.0 | 6 votes |
def linear_ensemble_strategy(self, pred_mean, pred_var, ruitu_inputs, feature_name,\ timestep_to_ensemble=21, alpha=1): ''' This stratergy aims to calculate linear weighted at specific timestep (timestep_to_ensemble) between prediction and ruitu as formula: (alpha)*pred_mean + (1-alpha)*ruitu_inputs pred_mean: (10, 37, 3) pred_var: (10, 37, 3) ruitu_inputs: (37,10,29). Need Swamp to(10,37,29) FIRSTLY!! timestep_to_ensemble: int32 (From 0 to 36) ''' assert 0<= alpha <=1, 'Please ensure 0<= alpha <=1 !' assert pred_mean.shape == (10, 37, 3), 'Error! This funtion ONLY works for \ one data sample with shape (10, 37, 3). Any data shape (None, 10, 37, 3) will leads this error!' #pred_std = np.sqrt(np.exp(pred_var)) ruitu_inputs = np.swapaxes(ruitu_inputs,0,1) print('alpha:',alpha) pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] = \ (alpha)*pred_mean[:,timestep_to_ensemble:,self.obs_and_output_feature_index_map[feature_name]] + \ (1-alpha)*ruitu_inputs[:,timestep_to_ensemble:, self.ruitu_feature_index_map[feature_name]] print('Corrected pred_mean shape:', pred_mean.shape) return pred_mean
Example 7
Project: kvae Author: simonkamronn File: plotting.py License: MIT License | 6 votes |
def plot_ball_and_alpha(alpha, trajectory, filename, cmap='Blues'): f, ax = plt.subplots(nrows=1, ncols=2, figsize=[12, 6]) collection = construct_ball_trajectory(trajectory, r=1., cmap=cmap) x_min, y_min = np.min(trajectory, axis=0) x_max, y_max = np.max(trajectory, axis=0) ax[0].add_collection(collection) ax[0].set_xlim([x_min, x_max]) ax[0].set_ylim([y_min, y_max]) # ax[0].set_xticks([]) # ax[0].set_yticks([]) ax[0].axis("equal") for line in np.swapaxes(alpha, 1, 0): ax[1].plot(line, linestyle='-') plt.savefig(filename, format='png', bbox_inches='tight', dpi=80) plt.close()
Example 8
Project: kvae Author: simonkamronn File: movie.py License: MIT License | 6 votes |
def save_movies_to_frame(images, filename, cmap='Blues'): # Binarize images # images[images > 0] = 1. # Grid images images = np.swapaxes(images, 1, 0) images = np.array([combine_multiple_img(image) for image in images]) # Collect to single image image = movie_to_frame(images) 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.savefig(filename, format='png', bbox_inches='tight', dpi=80) plt.close(f)
Example 9
Project: Attentive-Filtering-Network Author: jefflai108 File: feat_slicing.py License: MIT License | 6 votes |
def tensor_cnn_frame(mat, M): """Construct a tensor of shape (C x H x W) given an utterance matrix for CNN """ slice_mat = [] for index in np.arange(len(mat)): if index < M: to_left = np.tile(mat[index], M).reshape((M,-1)) rest = mat[index:index+M+1] context = np.vstack((to_left, rest)) elif index >= len(mat)-M: to_right = np.tile(mat[index], M).reshape((M,-1)) rest = mat[index-M:index+1] context = np.vstack((rest, to_right)) else: context = mat[index-M:index+M+1] slice_mat.append(context) slice_mat = np.array(slice_mat) slice_mat = np.expand_dims(slice_mat, axis=1) slice_mat = np.swapaxes(slice_mat, 2, 3) return slice_mat
Example 10
Project: Attentive-Filtering-Network Author: jefflai108 File: feat_slicing.py License: MIT License | 6 votes |
def tensor_cnngru(mat): """Construct an utterance tensor for a given utterance matrix mat for CNN+GRU """ mat = np.swapaxes(mat, 0, 1) div = int(mat.shape[1]/400) if div == 0: # short utt tensor_mat = mat while True: shape = tensor_mat.shape[1] if shape + mat.shape[1] < 400: tensor_mat = np.hstack((tensor_mat,mat)) else: tensor_mat = np.hstack((tensor_mat,mat[:,:400-shape])) break elif div == 1: # truncate to 1 tensor_mat = mat[:,:400] else: # TO DO: cut into 2 tensor_mat = mat[:,:400] tensor_mat = np.expand_dims(tensor_mat, axis=2) print(tensor_mat.shape) return tensor_mat
Example 11
Project: pyGSTi Author: pyGSTio File: matrixforwardsim.py License: Apache License 2.0 | 6 votes |
def doperation(self, opLabel, flat=False, wrtFilter=None): """ Return the derivative of a length-1 (single-gate) sequence """ dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays too # Compute the derivative of the entire operation sequence with respect to the # gate's parameters and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim))
Example 12
Project: recruit Author: Frank-qlu File: test_numeric.py License: Apache License 2.0 | 6 votes |
def setup(self): self.data = [ # Array scalars (np.array(3.), None), (np.array(3), 'f8'), # 1D arrays (np.arange(6, dtype='f4'), None), (np.arange(6), 'c16'), # 2D C-layout arrays (np.arange(6).reshape(2, 3), None), (np.arange(6).reshape(3, 2), 'i1'), # 2D F-layout arrays (np.arange(6).reshape((2, 3), order='F'), None), (np.arange(6).reshape((3, 2), order='F'), 'i1'), # 3D C-layout arrays (np.arange(24).reshape(2, 3, 4), None), (np.arange(24).reshape(4, 3, 2), 'f4'), # 3D F-layout arrays (np.arange(24).reshape((2, 3, 4), order='F'), None), (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'), # 3D non-C/F-layout arrays (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None), (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'), ]
Example 13
Project: tenpy Author: tenpy File: np_conserved.py License: GNU General Public License v3.0 | 6 votes |
def iswapaxes(self, axis1, axis2): """Similar as ``np.swapaxes``; in place.""" axis1 = self.get_leg_index(axis1) axis2 = self.get_leg_index(axis2) if axis1 == axis2: return self # nothing to do swap = np.arange(self.rank, dtype=np.intp) swap[axis1], swap[axis2] = axis2, axis1 legs = self.legs legs[axis1], legs[axis2] = legs[axis2], legs[axis1] labels = self._labels labels[axis1], labels[axis2] = labels[axis2], labels[axis1] self._set_shape() self._qdata = self._qdata[:, swap] self._qdata_sorted = False self._data = [t.swapaxes(axis1, axis2) for t in self._data] return self
Example 14
Project: pylops Author: equinor File: FirstDerivative.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _rmatvec_forward(self, x): if not self.reshape: x = x.squeeze() y = np.zeros(self.N, self.dtype) y[:-1] -= x[:-1] / self.sampling y[1:] += x[:-1] / self.sampling else: x = np.reshape(x, self.dims) if self.dir > 0: # need to bring the dim. to derive to first dim. x = np.swapaxes(x, self.dir, 0) y = np.zeros(x.shape, self.dtype) y[:-1] -= x[:-1] / self.sampling y[1:] += x[:-1] / self.sampling if self.dir > 0: y = np.swapaxes(y, 0, self.dir) y = y.ravel() return y
Example 15
Project: pylops Author: equinor File: FirstDerivative.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _matvec_centered(self, x): if not self.reshape: x = x.squeeze() y = np.zeros(self.N, self.dtype) y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling if self.edge: y[0] = (x[1] - x[0]) / self.sampling y[-1] = (x[-1] - x[-2]) / self.sampling else: x = np.reshape(x, self.dims) if self.dir > 0: # need to bring the dim. to derive to first dim. x = np.swapaxes(x, self.dir, 0) y = np.zeros(x.shape, self.dtype) y[1:-1] = (0.5 * x[2:] - 0.5 * x[0:-2]) / self.sampling if self.edge: y[0] = (x[1] - x[0]) / self.sampling y[-1] = (x[-1] - x[-2]) / self.sampling if self.dir > 0: y = np.swapaxes(y, 0, self.dir) y = y.ravel() return y
Example 16
Project: pylops Author: equinor File: FirstDerivative.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _rmatvec_backward(self, x): if not self.reshape: x = x.squeeze() y = np.zeros(self.N, self.dtype) y[:-1] -= x[1:] / self.sampling y[1:] += x[1:] / self.sampling else: x = np.reshape(x, self.dims) if self.dir > 0: # need to bring the dim. to derive to first dim. x = np.swapaxes(x, self.dir, 0) y = np.zeros(x.shape, self.dtype) y[:-1] -= x[1:] / self.sampling y[1:] += x[1:] / self.sampling if self.dir > 0: y = np.swapaxes(y, 0, self.dir) y = y.ravel() return y
Example 17
Project: pylops Author: equinor File: SecondDerivative.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _matvec(self, x): if not self.reshape: x = x.squeeze() y = np.zeros(self.N, self.dtype) y[1:-1] = (x[2:] - 2*x[1:-1] + x[0:-2]) / self.sampling**2 if self.edge: y[0] = (x[0] - 2*x[1] + x[2]) / self.sampling**2 y[-1] = (x[-3] - 2*x[-2] + x[-1]) / self.sampling**2 else: x = np.reshape(x, self.dims) if self.dir > 0: # need to bring the dim. to derive to first dim. x = np.swapaxes(x, self.dir, 0) y = np.zeros(x.shape, self.dtype) y[1:-1] = (x[2:] - 2*x[1:-1] + x[0:-2])/self.sampling**2 if self.edge: y[0] = (x[0] - 2*x[1] + x[2]) / self.sampling ** 2 y[-1] = (x[-3] - 2*x[-2] + x[-1]) / self.sampling ** 2 if self.dir > 0: y = np.swapaxes(y, 0, self.dir) y = y.ravel() return y
Example 18
Project: lambda-deep-learning-demo Author: lambdal File: vgg_16_reduced.py License: Apache License 2.0 | 6 votes |
def vgg_block(outputs, params, name, data_format, num_conv): for i in range(num_conv): layer_name = name + "_" + str(i + 1) w = np.swapaxes(np.swapaxes(np.swapaxes(params[layer_name][0], 0, 3), 1, 2), 0, 1) b = params[layer_name][1] outputs = tf.layers.conv2d( outputs, filters=w.shape[3], kernel_size=(w.shape[0], w.shape[1]), strides=(1, 1), padding=("SAME"), data_format=data_format, kernel_initializer=tf.constant_initializer(w), bias_initializer=tf.constant_initializer(b), activation=tf.nn.relu, name=layer_name) return outputs
Example 19
Project: lambda-deep-learning-demo Author: lambdal File: vgg_16_reduced.py License: Apache License 2.0 | 6 votes |
def vgg_mod(outputs, params, name, data_format, dilation=1): w = np.swapaxes(np.swapaxes(np.swapaxes(params[name][0], 0, 3), 1, 2), 0, 1) b = params[name][1] outputs = tf.layers.conv2d( outputs, filters=w.shape[3], kernel_size=(w.shape[0], w.shape[1]), strides=(1, 1), padding=("SAME"), data_format=data_format, dilation_rate=(dilation, dilation), kernel_initializer=tf.constant_initializer(w), bias_initializer=tf.constant_initializer(b), activation=tf.nn.relu, name=name) return outputs
Example 20
Project: lambda-packs Author: ryfeus File: basic.py License: MIT License | 6 votes |
def _raw_fft(x, n, axis, direction, overwrite_x, work_function): """ Internal auxiliary function for fft, ifft, rfft, irfft.""" if n is None: n = x.shape[axis] elif n != x.shape[axis]: x, copy_made = _fix_shape(x,n,axis) overwrite_x = overwrite_x or copy_made if n < 1: raise ValueError("Invalid number of FFT data points " "(%d) specified." % n) if axis == -1 or axis == len(x.shape)-1: r = work_function(x,n,direction,overwrite_x=overwrite_x) else: x = swapaxes(x, axis, -1) r = work_function(x,n,direction,overwrite_x=overwrite_x) r = swapaxes(r, axis, -1) return r
Example 21
Project: fenics-topopt Author: zfergus File: stress_gui.py License: MIT License | 5 votes |
def __init__(self, nelx, nely, stress_calculator, nu, title=""): """Initialize plot and plot the initial design""" super(StressGUI, self).__init__(nelx, nely, title) self.stress_im = self.ax.imshow( np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1), norm=colors.Normalize(vmin=0, vmax=1), cmap='jet') self.fig.colorbar(self.stress_im) self.stress_calculator = stress_calculator self.nu = nu self.myColorMap = colormaps.ScalarMappable( norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet)
Example 22
Project: fenics-topopt Author: zfergus File: stress_gui.py License: MIT License | 5 votes |
def __init__(self, nelx, nely, stress_calculator, nu, title=""): """Initialize plot and plot the initial design""" super(StressGUI, self).__init__(nelx, nely, title) self.stress_im = self.ax.imshow( np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1), norm=colors.Normalize(vmin=0, vmax=1), cmap='jet') self.fig.colorbar(self.stress_im) self.stress_calculator = stress_calculator self.nu = nu self.myColorMap = colormaps.ScalarMappable( norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet)
Example 23
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: data.py License: Apache License 2.0 | 5 votes |
def _read_img(self, img_name, label_name): img = Image.open(os.path.join(self.root_dir, img_name)) label = Image.open(os.path.join(self.root_dir, label_name)) assert img.size == label.size img = np.array(img, dtype=np.float32) # (h, w, c) label = np.array(label) # (h, w) if self.cut_off_size is not None: max_hw = max(img.shape[0], img.shape[1]) min_hw = min(img.shape[0], img.shape[1]) if min_hw > self.cut_off_size: rand_start_max = int(np.random.uniform(0, max_hw - self.cut_off_size - 1)) rand_start_min = int(np.random.uniform(0, min_hw - self.cut_off_size - 1)) if img.shape[0] == max_hw : img = img[rand_start_max : rand_start_max + self.cut_off_size, rand_start_min : rand_start_min + self.cut_off_size] label = label[rand_start_max : rand_start_max + self.cut_off_size, rand_start_min : rand_start_min + self.cut_off_size] else : img = img[rand_start_min : rand_start_min + self.cut_off_size, rand_start_max : rand_start_max + self.cut_off_size] label = label[rand_start_min : rand_start_min + self.cut_off_size, rand_start_max : rand_start_max + self.cut_off_size] elif max_hw > self.cut_off_size: rand_start = int(np.random.uniform(0, max_hw - min_hw - 1)) if img.shape[0] == max_hw : img = img[rand_start : rand_start + min_hw, :] label = label[rand_start : rand_start + min_hw, :] else : img = img[:, rand_start : rand_start + min_hw] label = label[:, rand_start : rand_start + min_hw] reshaped_mean = self.mean.reshape(1, 1, 3) img = img - reshaped_mean img = np.swapaxes(img, 0, 2) img = np.swapaxes(img, 1, 2) # (c, h, w) img = np.expand_dims(img, axis=0) # (1, c, h, w) label = np.array(label) # (h, w) label = np.expand_dims(label, axis=0) # (1, h, w) return (img, label)
Example 24
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: nstyle.py License: Apache License 2.0 | 5 votes |
def PreprocessStyleImage(path, shape): img = io.imread(path) resized_img = transform.resize(img, (shape[2], shape[3])) sample = np.asarray(resized_img) * 256 sample = np.swapaxes(sample, 0, 2) sample = np.swapaxes(sample, 1, 2) sample[0, :] -= 123.68 sample[1, :] -= 116.779 sample[2, :] -= 103.939 return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
Example 25
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: nstyle.py License: Apache License 2.0 | 5 votes |
def PostprocessImage(img): 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, 1, 2) img = np.swapaxes(img, 0, 2) img = np.clip(img, 0, 255) return img.astype('uint8')
Example 26
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: data_processing.py License: Apache License 2.0 | 5 votes |
def PreprocessStyleImage(path, shape): img = io.imread(path) resized_img = transform.resize(img, (shape[2], shape[3])) sample = np.asarray(resized_img) * 256 sample = np.swapaxes(sample, 0, 2) sample = np.swapaxes(sample, 1, 2) sample[0, :] -= 123.68 sample[1, :] -= 116.779 sample[2, :] -= 103.939 return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))
Example 27
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: data_processing.py License: Apache License 2.0 | 5 votes |
def PostprocessImage(img): 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, 1, 2) img = np.swapaxes(img, 0, 2) img = np.clip(img, 0, 255) return img.astype('uint8')
Example 28
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: imagehelper.py License: Apache License 2.0 | 5 votes |
def PreprocessImage(img): img = np.array(img) print("Original Image Shape: ", img.shape) # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + short_egde] # resize to 224, 224 resized_img = transform.resize(crop_img, (224, 224)) # convert to numpy.ndarray sample = np.asarray(resized_img) * 256 #------------------------------------------------------------------- # Note: The decoded image should be in BGR channel (opencv output) # For RGB output such as from skimage, we need to convert it to BGR # WRONG channel will lead to WRONG result #------------------------------------------------------------------- # swap channel from RGB to BGR # sample = sample[:, :, [2,1,0]] sample = sample[:, :, [0,1,2]] # actually, in this pre-trained model RGB is used # swap axes to make image from (224, 224, 4) to (3, 224, 224) sample = np.swapaxes(sample, 0, 2) sample = np.swapaxes(sample, 1, 2) sample.resize(3,224,224) return sample
Example 29
Project: DOTA_models Author: ringringyi File: tf_utils.py License: Apache License 2.0 | 5 votes |
def concat_state_x(f, names): af = {} for k in names: af[k] = np.concatenate([x[k] for x in f], axis=1) # af[k] = np.swapaxes(af[k], 0, 1) return af
Example 30
Project: DOTA_models Author: ringringyi File: controller.py License: Apache License 2.0 | 5 votes |
def convert_to_batched_episodes(self, episodes, max_length=None): """Convert batch-major list of episodes to time-major batch of episodes.""" lengths = [len(ep[-2]) for ep in episodes] max_length = max_length or max(lengths) new_episodes = [] for ep, length in zip(episodes, lengths): initial, observations, actions, rewards, terminated = ep observations = [np.resize(obs, [max_length + 1] + list(obs.shape)[1:]) for obs in observations] actions = [np.resize(act, [max_length + 1] + list(act.shape)[1:]) for act in actions] pads = np.array([0] * length + [1] * (max_length - length)) rewards = np.resize(rewards, [max_length]) * (1 - pads) new_episodes.append([initial, observations, actions, rewards, terminated, pads]) (initial, observations, actions, rewards, terminated, pads) = zip(*new_episodes) observations = [np.swapaxes(obs, 0, 1) for obs in zip(*observations)] actions = [np.swapaxes(act, 0, 1) for act in zip(*actions)] rewards = np.transpose(rewards) pads = np.transpose(pads) return (initial, observations, actions, rewards, terminated, pads)