当前位置: 首页>>代码示例>>Python>>正文


Python numpy.copy方法代码示例

本文整理汇总了Python中numpy.copy方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.copy方法的具体用法?Python numpy.copy怎么用?Python numpy.copy使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.copy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_border

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def add_border(self, val, img_shape=None):
        if val == 0:
            return self.copy()
        else:
            if isinstance(val, int):
                rect = Rectangle(x1=self.x1-val, x2=self.x2+val, y1=self.y1-val, y2=self.y2+val)
            elif isinstance(val, float):
                rect = Rectangle(x1=int(self.x1 - self.width*val), x2=int(self.x2 + self.width*val), y1=int(self.y1 - self.height*val), y2=int(self.y2 + self.height*val))
            elif isinstance(val, tuple):
                assert len(val) == 4, str(len(val))

                if all([isinstance(subval, int) for subval in val]):
                    rect = Rectangle(x1=self.x1-val[3], x2=self.x2+val[1], y1=self.y1-val[0], y2=self.y2+val[2])
                elif all([isinstance(subval, float) or subval == 0 for subval in val]): # "or subval==0" da sonst zB (0.1, 0, 0.1, 0) einen fehler erzeugt (0 ist int)
                    rect = Rectangle(x1=int(self.x1 - self.width*val[3]), x2=int(self.x2 + self.width*val[1]), y1=int(self.y1 - self.height*val[0]), y2=int(self.y2 + self.height*val[2]))
                else:
                    raise Exception("Tuple of all ints or tuple of all floats expected, got %s" % (str([type(v) for v in val]),))
            else:
                raise Exception("int or float or tuple of ints/floats expected, got %s" % (type(val),))

            if img_shape is not None:
                rect.fix_by_image_dimensions(height=img_shape[0], width=img_shape[1])

            return rect 
开发者ID:aleju,项目名称:cat-bbs,代码行数:26,代码来源:bbs.py

示例2: draw_on_image

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def draw_on_image(self, img, color=[0, 255, 0], alpha=1.0, copy=True, from_img=None):
        if copy:
            img = np.copy(img)

        orig_dtype = img.dtype
        if alpha != 1.0 and img.dtype != np.float32:
            img = img.astype(np.float32, copy=False)

        for rect in self:
            if from_img is not None:
                rect.resize(from_img, img).draw_on_image(img, color=color, alpha=alpha, copy=False)
            else:
                rect.draw_on_image(img, color=color, alpha=alpha, copy=False)

        if orig_dtype != img.dtype:
            img = img.astype(orig_dtype, copy=False)

        return img 
开发者ID:aleju,项目名称:cat-bbs,代码行数:20,代码来源:bbs.py

示例3: process_frame

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def process_frame(frame_idx, img, model, write_to_dir, conf_threshold, input_size=224):
    """Finds bounding boxes in a video frame, draws these bounding boxes
    and saves the result to HDD.
    """
    # find BBs in frame
    bbs, time_model = find_bbs(img, model, conf_threshold, input_size=input_size)

    # draw BBs
    img_out = np.copy(img)
    for (bb, score) in bbs:
        if score > conf_threshold and bb.width > 2 and bb.height > 2:
            img_out = bb.draw_on_image(img_out, color=[0, 255, 0], thickness=3)

    # save to output directory
    save_to_fp = os.path.join(write_to_dir, "%05d.jpg" % (frame_idx,))
    misc.imsave(save_to_fp, img_out)

    return time_model 
开发者ID:aleju,项目名称:cat-bbs,代码行数:20,代码来源:predict_video.py

示例4: _shrink_candidates

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _shrink_candidates(self, rect, depth):
        """Recursive function called by _shrink() to generate bounding box
        candidates that are smaller than the input bounding box."""
        result = [rect]

        if depth > 0:
            if rect.width > 1:
                rect_left = rect.copy(x1=rect.x1+1)
                rect_right = rect.copy(x2=rect.x2-1)
                result.extend(self._shrink_candidates(rect_left, depth=depth-1))
                result.extend(self._shrink_candidates(rect_right, depth=depth-1))

            if rect.height > 1:
                rect_top = rect.copy(y1=rect.y1+1)
                rect_bottom = rect.copy(y2=rect.y2-1)
                result.extend(self._shrink_candidates(rect_top, depth=depth-1))
                result.extend(self._shrink_candidates(rect_bottom, depth=depth-1))

        return result 
开发者ID:aleju,项目名称:cat-bbs,代码行数:21,代码来源:predict_video.py

示例5: _rects_reverse_projection

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _rects_reverse_projection(self, rects, img_shape, img_pad_shape, pad_top, pad_right, pad_bottom, pad_left):
        """Input images into the model are padded to make them squared. They
        are also resized to a smaller size. This function is supposed to
        remove both effects, i.e. to project the found bounding boxes from
        the padded and resized image to the unpadded und unresized (original)
        input image.
        """
        result = []
        for (rect, score) in rects:
            # project from resized padded (squared) image to unresized one
            rect_large = rect.on(img_pad_shape)
            # move rectangles to remove paddings
            rect_large_unpadded = rect_large.shift(top=-pad_top, left=-pad_left)
            # positions of corners are now correct, so switch underlying shape
            rect_large_unpadded = rect_large_unpadded.copy(shape=img_shape)
            result.append((rect_large_unpadded, score))
        return result 
开发者ID:aleju,项目名称:cat-bbs,代码行数:19,代码来源:predict_video.py

示例6: _get_rois_blob

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _get_rois_blob(im_rois, im_scale_factors):
    """Converts RoIs into network inputs.
    Arguments:
        im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
        im_scale_factors (list): scale factors as returned by _get_image_blob
    Returns:
        blob (ndarray): R x 5 matrix of RoIs in the image pyramid
    """
    rois_blob_real = []

    for i in range(len(im_scale_factors)):
        rois, levels = _project_im_rois(im_rois, np.array([im_scale_factors[i]]))
        rois_blob = np.hstack((levels, rois))
        rois_blob_real.append(rois_blob.astype(np.float32, copy=False))

    return rois_blob_real 
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:18,代码来源:test.py

示例7: _project_im_rois

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _project_im_rois(im_rois, scales):
    """Project image RoIs into the image pyramid built by _get_image_blob.
    Arguments:
        im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
        scales (list): scale factors as returned by _get_image_blob
    Returns:
        rois (ndarray): R x 4 matrix of projected RoI coordinates
        levels (list): image pyramid levels used by each projected RoI
    """
    im_rois = im_rois.astype(np.float, copy=False)

    if len(scales) > 1:
        widths = im_rois[:, 2] - im_rois[:, 0] + 1
        heights = im_rois[:, 3] - im_rois[:, 1] + 1
        areas = widths * heights
        scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2)
        diff_areas = np.abs(scaled_areas - 224 * 224)
        levels = diff_areas.argmin(axis=1)[:, np.newaxis]
    else:
        levels = np.zeros((im_rois.shape[0], 1), dtype=np.int)

    rois = im_rois * scales[levels]

    return rois, levels 
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:26,代码来源:test.py

示例8: perturb

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:20,代码来源:pgd_cw_whitebox.py

示例9: auto_inverse

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def auto_inverse(self, whole_spectrum):
        whole_spectrum = np.copy(whole_spectrum).astype(complex)
        whole_spectrum[whole_spectrum < 1] = 1
        overwrap = self.buffer_size * 2
        height = whole_spectrum.shape[0]
        parallel_dif = (height-overwrap) // self.parallel
        if height < self.parallel*overwrap:
            raise Exception('voice length is too small to use gpu, or parallel number is too big')

        spec = [self.inverse(whole_spectrum[range(i, i+parallel_dif*self.parallel, parallel_dif), :]) for i in tqdm.tqdm(range(parallel_dif+overwrap))]
        spec = spec[overwrap:]
        spec = np.concatenate(spec, axis=1)
        spec = spec.reshape(-1, self.wave_len)

        #Below code don't consider wave_len and wave_dif, I'll fix.
        wave = np.fft.ifft(spec, axis=1).real
        pad = np.zeros((wave.shape[0], 2), dtype=float)
        wave = np.concatenate([wave, pad], axis=1)

        dst = np.zeros((wave.shape[0]+3)*self.wave_dif, dtype=float)
        for i in range(4):
            w = wave[range(i, wave.shape[0], 4),:]
            w = w.reshape(-1)
            dst[i*self.wave_dif:i*self.wave_dif+len(w)] += w
        return dst*0.5 
开发者ID:pstuvwx,项目名称:Deep_VoiceChanger,代码行数:27,代码来源:gla_gpu.py

示例10: _get_constraints_data

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _get_constraints_data(self, frame):
        """Get constraint and data for given frame. This is meant to be used
        internally. If used wrong, engine values can be altered unvoluntarely.
        It's generally meant to be used for plot and export purposes.

        :Parameters:
            #. frame (string): can be a traditional frame a d subframe or
               a multiframe

        :Returns:
            #. dataLUT (dict): a dictionary where keys are the given frame and
               all subframes if a multiframe is given. Values are dictionaries
               of the constraint and data copy
        """
        dataLUT = self._get_constraints_copy(frame)
        for frm in dataLUT:
            _constraint = dataLUT[frm]
            _data       = _constraint.data
            if _data is None or _constraint.engine.state != _constraint.state:
                LOGGER.usage("Computing constraint '{name}' data @{frame} without updating nor altering constraint properties and stochastic engine repository files".format(name=self.constraintName, frame=frm))
                _data, _ = _constraint.compute_data(update=False)
            dataLUT[frm] = {'constraint':_constraint, 'data':_data}
        # return
        return dataLUT 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:26,代码来源:Constraint.py

示例11: _set_used_data_weights

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def _set_used_data_weights(self, limitsIndexStart=None, limitsIndexEnd=None):
        # set used dataWeights
        if self.__dataWeights is None:
            self._usedDataWeights = None
        else:
            if limitsIndexStart is None:
                limitsIndexStart = 0
            if limitsIndexEnd is None:
                limitsIndexEnd = self.__experimentalData.shape[0]
            self._usedDataWeights  = np.copy(self.dataWeights[limitsIndexStart:limitsIndexEnd+1])
            assert np.sum(self._usedDataWeights), LOGGER.error("used points dataWeights are all zero.")
            self._usedDataWeights /= FLOAT_TYPE( np.sum(self._usedDataWeights) )
            self._usedDataWeights *= FLOAT_TYPE( len(self._usedDataWeights) )
        # dump to repository
        if self.engine is not None:
            isNormalFrame, isMultiframe, isSubframe = self.engine.get_frame_category(frame=self.engine.usedFrame)
            if isSubframe:
                LOGGER.usage("Setting experimental data weight for multiframe '%s' subframe. This is not going to automatically propagate to all other subframes."%(self.engine.usedFrame,))
        self._dump_to_repository({'_usedDataWeights': self._usedDataWeights}) 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:21,代码来源:Constraint.py

示例12: almost_equal_ignore_nan

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):
    """Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.

    Parameters
    ----------
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
        The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
        The absolute threshold. Default threshold will be used if set to ``None``.
    """
    a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0

    return almost_equal(a, b, rtol, atol) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:25,代码来源:test_utils.py

示例13: assert_almost_equal_ignore_nan

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):
    """Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.

    Parameters
    ----------
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
        The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
        The absolute threshold. Default threshold will be used if set to ``None``.
    """
    a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0

    assert_almost_equal(a, b, rtol, atol, names) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:25,代码来源:test_utils.py

示例14: check_error

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def check_error(model, path, shapes, output = 'softmax_output', verbose = True):
    """
    Check the difference between predictions from MXNet and CoreML.
    """
    coreml_model = _coremltools.models.MLModel(path)
    input_data = {}
    input_data_copy = {}
    for ip in shapes:
        input_data[ip] = _np.random.rand(*shapes[ip]).astype('f')
        input_data_copy[ip] = _np.copy(input_data[ip])

    dataIter = _mxnet.io.NDArrayIter(input_data_copy)
    mx_out = model.predict(dataIter).flatten()

    e_out_dict = coreml_model.predict(_mxnet_remove_batch(input_data))
    e_out = e_out_dict[output].flatten()
    error = _np.linalg.norm(e_out - mx_out)

    if verbose:
        print("First few predictions from CoreML : %s" % e_out[0:10])
        print("First few predictions from MXNet  : %s" % e_out[0:10])
        print("L2 Error on random data %s" % error)
    return error 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:25,代码来源:_mxnet_converter.py

示例15: align_coordinates

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import copy [as 别名]
def align_coordinates(self, geom, *, reverse=False) -> Array:
        """suitable for geometry or displaced geometry"""

        algeom = np.copy(geom)
        if reverse:
            algeom = algeom.dot(self.rotation)
            algeom = algeom + self.shift
            if self.mirror:
                algeom[:, 1] *= -1.0
        else:
            if self.mirror:
                algeom[:, 1] *= -1.0
            algeom = algeom - self.shift
            algeom = algeom.dot(self.rotation)
        algeom = algeom[self.atommap, :]
        # mirror-wise, rsm/msr == rms/msr

        return algeom 
开发者ID:MolSSI,项目名称:QCElemental,代码行数:20,代码来源:align.py


注:本文中的numpy.copy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。