Python numpy.resize() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            if hasattr(self, 'param') and self.param: # not self.param is None
                tmp = self.param
            else:
                tmp = self.condition
            self.scales = tmp ** linspace(0, 1, dim)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 2

def initwithsize(self, curshape, dim):
        # DIM-dependent initialisation
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape)
            self.arrscales = resize(self.scales, curshape)
            self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) 

Example 3

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.xopt[:min(dim, self.maxindex):2] = abs(self.xopt[:min(dim, self.maxindex):2])
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape)
            self.arrscales = resize(self.scales, curshape) 

Example 4

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = self.condition ** linspace(0, 1, dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim),
                                diag(((self.condition / 10.)**.5) ** linspace(0, 1, dim)))

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 5

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            scale = max(1, dim ** .5 / 8.) # nota: different from scales in F8
            self.linearTF = scale * compute_rotation(self.rseed, dim)
            self.xopt = np.hstack(dot(.5 * np.ones((1, dim)), self.linearTF.T)) / scale ** 2

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 6

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
            self.linearTF = dot(self.linearTF, self.rotation)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 7

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
            # decouple scaling from function definition
            self.linearTF = dot(self.linearTF, self.rotation)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape)
            self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) 

Example 8

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (1. / self.condition ** .5) ** linspace(0, 1, dim) # CAVE?
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
            # decouple scaling from function definition
            self.linearTF = dot(self.linearTF, self.rotation)
            K = np.arange(0, 12)
            self.aK = np.reshape(0.5 ** K, (1, 12))
            self.bK = np.reshape(3. ** K, (1, 12))
            self.f0 = np.sum(self.aK * np.cos(2 * np.pi * self.bK * 0.5)) # optimal value

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 9

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1 , dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape)
            self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape) 

Example 10

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = 0.5 * sign(unif(dim, self.rseed) - 0.5) * 4.2096874633
            self.scales = (self.condition ** .5) ** np.linspace(0, 1, dim)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(2 * np.abs(self.xopt), curshape)
            self.arrscales = resize(self.scales, curshape)
            self.arrsigns = resize(sign(self.xopt), curshape) 

Example 11

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
            # decouple scaling from function definition
            self.linearTF = dot(self.linearTF, self.rotation)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape) 

Example 12

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = .5 * self._mu1 * sign(gauss(dim, self.rseed))
            self.rotation = compute_rotation(self.rseed + 1e6, dim)
            self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
            self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
            # decouple scaling from function definition
            self.linearTF = dot(self.linearTF, self.rotation)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            # self.arrxopt = resize(self.xopt, curshape)
            self.arrscales = resize(2. * sign(self.xopt), curshape) # makes up for xopt 

Example 13

def initwithsize(self, curshape, dim):
        # DIM-dependent initialization
        if self.dim != dim:
            if self.zerox:
                self.xopt = zeros(dim)
            else:
                self.xopt = compute_xopt(self.rseed, dim)

        # DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
        if self.lastshape != curshape:
            self.dim = dim
            self.lastshape = curshape
            self.arrxopt = resize(self.xopt, curshape)

        self.linearTf = None
        self.rotation = None 

Example 14

def __call__(self, ts=None, constrains=False):

        if ts is None:
            if constrains:
                if self.J.constrains.size:
                    A = np.resize(self, (self.shape[0] + self.J.constrains.shape[0], self.shape[1]))
                    A[-self.J.constrains.shape[0] - 1:-1,self.L.params:self.L.params + self.J.params] = self.J.constrains
                    return A

                else:
                    return self

            else:
                return self

        else:
            Al = self.L.GetDesignTs(ts)
            Aj = self.J.GetDesignTs(ts)
            Ap = self.P.GetDesignTs(ts)

            As = np.column_stack((Al, Aj)) if Aj.size else Al
            As = np.column_stack((As, Ap)) if Ap.size else As

            return As 

Example 15

def apply_motion_blur(image, kernel_size, strength = 1.0):
    """Applies motion blur on image 
    """
    # generating the kernel
    kernel_motion_blur = np.zeros((kernel_size, kernel_size))
    kernel_motion_blur[int((kernel_size - 1) / 2), :] = np.ones(kernel_size)
    kernel_motion_blur = kernel_motion_blur / kernel_size

    rotation_kernel = np.random.uniform(0, 360)
    kernel_motion_blur = rotate(kernel_motion_blur, rotation_kernel)
    #cv2.imshow("kernel", cv2.resize(kernel_motion_blur, (100, 100)))
    kernel_motion_blur *= strength

    # applying the kernel to the input image
    output = cv2.filter2D(image, -1, kernel_motion_blur)
    return output 

Example 16

def train(self, tran, selected):
        self.targetNet.blobs['frames'].data[...] \
            = tran.frames[selected + 1].copy()
        netOut = self.targetNet.forward()

        target = np.tile(tran.reward[selected]
                         + pms.discount
                         * tran.n_last[selected]
                         * np.resize(netOut['value_q'].max(1),
                                     (pms.batchSize, 1)),
                         (pms.actionSize,)
                         ) * tran.action[selected]

        self.solver.net.blobs['target'].data[...] = target
        self.solver.net.blobs['frames'].data[...] = tran.frames[selected].copy()
        self.solver.net.blobs['filter'].data[...] = tran.action[selected].copy()
        self.solver.step(1) 

Example 17

def read_data(dataFile,size,Transpose=False,resize=False):
	f             =      h5py.File(dataFile,'r')
	result_data   =      np.zeros(size)
	result_label  =      np.zeros(size)
	if Transpose == True:
		data      =      np.transpose(np.array(f['data']),(3,2,1,0))
		label     =      np.transpose(np.array(f['label']),(3,2,1,0))
	else:
		data      =      np.array(f['data'])
		label     =      np.array(f['label'])
	[d1,d2,d3,d4] =      data.shape
	if resize == True:
		for p in range(d1):
			for d in range(d2):
				result_data[p,d,:,:]     =      np.resize(data[p,d,:,:],(size[2],size[3]))
				result_label[p,d,:,:]    =      np.resize(label[p,d,:,:],(size[2],size[3]))
		data      =      result_data
		label     =      result_label
	return data, label 

Example 18

def run_test_r2c_dtype(self, shape, axes, dtype=np.float32, scale=1., misalign=0):
        known_data = np.random.normal(size=shape).astype(np.float32)
        known_data = (known_data * scale).astype(dtype)

        # Force misaligned data
        padded_shape = shape[:-1] + (shape[-1] + misalign,)
        known_data = np.resize(known_data, padded_shape)
        idata = bf.ndarray(known_data, space='cuda')
        known_data = known_data[..., misalign:]
        idata = idata[..., misalign:]

        oshape = list(shape)
        oshape[axes[-1]] = shape[axes[-1]] // 2 + 1
        odata = bf.ndarray(shape=oshape, dtype='cf32', space='cuda')
        fft = Fft()
        fft.init(idata, odata, axes=axes)
        fft.execute(idata, odata)
        known_result = gold_rfftn(known_data.astype(np.float32) / scale, axes=axes)
        compare(odata.copy('system'), known_result) 

Example 19

def resize(vec, size):
   """
   Resizes a vector such that it has the right size. This is done by repeating the vector
   in each dimension until the required size is reached. Note an error is thrown if 'size'
   is not a multiple of the size of vec.

   vec      A 1D or 2D numpy array
   size     A list of dimension sizes (e.g. [2,3])
   """
   if not isinstance(vec, (np.ndarray)):
      vec_resized = vec * np.ones(size)
   elif vec.shape[0] == size[0] and len(vec.shape) == 1:
      vec_resized = np.reshape(np.repeat(vec, size[1]), size)
   elif vec.shape[0] == 1 and len(vec.shape) == 1:
      vec_resized = vec*np.ones(size)
   else:
      # Check that the output dims are multiples of input dims
      assert(size[0] % vec.shape[0] == 0)
      assert(size[1] % vec.shape[1] == 0)
      vec_resized = np.tile(vec, (size[0] // vec.shape[0], size[1] // vec.shape[1]))
   return vec_resized 

Example 20

def _read_particle_coords(self, chunks, ptf):
        # This will read chunks and yield the results.
        chunks = list(chunks)
        data_files = set([])
        for chunk in chunks:
            for obj in chunk.objs:
                data_files.update(obj.data_files)
        for data_file in sorted(data_files):
            with h5py.File(data_file.filename, "r") as f:
                for ptype, field_list in sorted(ptf.items()):
                    pcount = data_file.total_particles[ptype]
                    coords = f[ptype]["%sPos" % ptype].value.astype("float64")
                    coords = np.resize(coords, (pcount, 3))
                    x = coords[:, 0]
                    y = coords[:, 1]
                    z = coords[:, 2]
                    yield ptype, (x, y, z) 

Example 21

def _read_particle_coords(self, chunks, ptf):
        # This will read chunks and yield the results.
        chunks = list(chunks)
        data_files = set([])
        for chunk in chunks:
            for obj in chunk.objs:
                data_files.update(obj.data_files)
        for data_file in sorted(data_files, key=lambda f: f.filename):
            with h5py.File(data_file.filename, "r") as f:
                for ptype, field_list in sorted(ptf.items()):
                    pcount = data_file.total_particles[ptype]
                    coords = f[ptype]["CenterOfMass"].value.astype("float64")
                    coords = np.resize(coords, (pcount, 3))
                    x = coords[:, 0]
                    y = coords[:, 1]
                    z = coords[:, 2]
                    yield ptype, (x, y, z) 

Example 22

def get_cloud_colors(data):
        """ Get colors from the cloud """
        dtype = np.dtype('float32')
        dtype = dtype.newbyteorder('<')
        buf = np.frombuffer(data.data, dtype)
        buf = np.resize(buf, (data.width * data.height, 8))
        buf = np.compress([True, True, True, False, True, False, False,
                           False], buf, axis=1)
        cond = np.isnan(buf).any(1)
        buf[cond] = [0.0, 0.0, 0.0, 0.0]
        buf = np.compress([False, False, False, True], buf, axis=1)
        nstr = buf.tostring()
        rgb = np.fromstring(nstr, dtype='uint8')
        rgb.resize((data.height * data.width), 4)
        rgb = np.compress([True, True, True, False], rgb, axis=1)
        return np.array([rgb]) 

Example 23

def plot_RF(rf, sample_shape):
    norm = matplotlib.colors.Normalize()
    norm.autoscale(rf)
    rf = np.resize(rf, np.prod(sample_shape)).reshape(sample_shape)
    norm_zero = min(max(norm(0.0), 0.0+1e-6), 1.0-1e-6)
    cdict = {
             'red'  :  ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)),
             'green':  ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)),
             'blue' :  ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.))
             }
    #generate the colormap with 1024 interpolated values
    my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)                
    plt.imshow(rf, interpolation='nearest', origin='upper', cmap=my_cmap)   
    ax = plt.gca()
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False) 

Example 24

def plot_examples(nade, dataset, shape, name, rows=5, cols=10):    
    #Show some samples
    images = list()
    for row in xrange(rows):                     
        for i in xrange(cols):
            nade.setup_n_orderings(n=1)
            sample = dataset.sample_data(1)[0].T
            dens = nade.logdensity(sample)
            images.append((sample, dens))
    images.sort(key=lambda x: -x[1])
    
    plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100)
    plt.gray()            
    for row in xrange(rows):                     
        for col in xrange(cols):
            i = row*cols+col
            sample, dens = images[i]
            plt.subplot(rows, cols, i+1)
            plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper")
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04)
    type_1_font()
    plt.savefig(os.path.join(DESTINATION_PATH, name)) 

Example 25

def plot_samples(nade, shape, name, rows=5, cols=10):    
    #Show some samples
    images = list()
    for row in xrange(rows):                     
        for i in xrange(cols):
            nade.setup_n_orderings(n=1)
            sample = nade.sample(1)[:,0]
            dens = nade.logdensity(sample[:, np.newaxis])
            images.append((sample, dens))
    images.sort(key=lambda x: -x[1])
    
    plt.figure(figsize=(0.5*cols,0.5*rows), dpi=100)
    plt.gray()            
    for row in xrange(rows):                     
        for col in xrange(cols):
            i = row*cols+col
            sample, dens = images[i]
            plt.subplot(rows, cols, i+1)
            plot_sample(np.resize(sample, np.prod(shape)).reshape(shape), shape, origin="upper")
    plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, hspace=0.04, wspace=0.04)
    type_1_font()
    plt.savefig(os.path.join(DESTINATION_PATH, name))                
    #plt.show() 

Example 26

def _create_batches(self, X, batch_size, shuffle_data=False):
        """
        Create batches out of a sequence of data.

        This function will append zeros to the end of your data to ensure that
        all batches are even-sized. These are masked out during training.
        """
        if shuffle_data:
            X = shuffle(X)

        if batch_size > X.shape[0]:
            batch_size = X.shape[0]

        max_x = int(np.ceil(X.shape[0] / batch_size))
        # This line first resizes the data to
        X = np.resize(X, (batch_size, max_x, X.shape[1]))
        # Transposes it to (len(X) / batch_size, batch_size, data_dim)

        return X.transpose((1, 0, 2)) 

Example 27

def _create_batches(self, X, batch_size, shuffle_data=True):
        """
        Create batches out of a sequence of data.

        This function will append zeros to the end of your data to ensure that
        all batches are even-sized. These are masked out during training.
        """
        if shuffle_data:
            X = shuffle(X)

        if batch_size > X.shape[0]:
            batch_size = X.shape[0]

        max_x = int(np.ceil(X.shape[0] / batch_size))
        X = np.resize(X, (max_x, batch_size, X.shape[-1]))

        return X 

Example 28

def predict():
    logger.info('/predict, hostname: ' + str(socket.gethostname()))

    if 'image' not in request.files:
        logger.info('Missing image parameter')
        return Response('Missing image parameter', 400)

    # Write image to disk
    with open('request.png', 'wb') as f:
        f.write(request.files['image'].read())

    img = cv2.imread('request.png', 0)
    img = np.resize(img, (28, 28, 1))

    ''' Return value will be None if model not running on host '''
    prediction = mnist_client.predict(np.array([img]))

    logger.info('Prediction of length: ' + str(len(prediction)))

    ''' Convert the dict to json and return response '''
    return jsonify(
        prediction=prediction,
        prediction_length=len(prediction),
        hostname=str(socket.gethostname())
    ) 

Example 29

def predict():
    logger.info('/predict, hostname: ' + str(socket.gethostname()))

    if 'image' not in request.files:
        logger.info('Missing image parameter')
        return Response('Missing image parameter', 400)

    # Write image to disk
    with open('request.png', 'wb') as f:
        f.write(request.files['image'].read())

    img = cv2.imread('request.png', 0)
    img = np.resize(img, (28, 28, 1))
    prediction = mnist_client.predict(np.array([img]))

    logger.info('Prediction of length:' + str(len(prediction)))

    ''' Convert the dict to json and return response '''
    return jsonify(
        prediction=prediction,
        prediction_length=len(prediction),
        hostname=str(socket.gethostname())
    ) 

Example 30

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)) 

Example 31

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)) 

Example 32

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)) 

Example 33

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 

Example 34

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 

Example 35

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 

Example 36

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 

Example 37

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

#----------------------------------------------------------------------------------------------------------------------- 

Example 38

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. 

Example 39

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. 

Example 40

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. 

Example 41

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) 

Example 42

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) 

Example 43

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) 

Example 44

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 

Example 45

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 

Example 46

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) 

Example 47

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') 

Example 48

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 > 

Example 49

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 

Example 50

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 
点赞