Python numpy.ascontiguousarray() Examples

The following are 30 code examples of numpy.ascontiguousarray(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: serialization.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, obj: Any) -> Any:
        try:
            return pydantic_encoder(obj)
        except TypeError:
            pass

        if isinstance(obj, np.ndarray):
            if obj.shape:
                data = {"_nd_": True, "dtype": obj.dtype.str, "data": np.ascontiguousarray(obj).tobytes().hex()}
                if len(obj.shape) > 1:
                    data["shape"] = obj.shape
                return data

            else:
                # Converts np.array(5) -> 5
                return obj.tolist()

        return json.JSONEncoder.default(self, obj) 
Example #2
Source File: call_engine_to_infer_all_print_predict_on_image_6classes.py    From iAI with MIT License 6 votes vote down vote up
def load_image(img_path, net_input_shape):
    imgBGR = cv2.imread(img_path)
    img = cv2.resize(imgBGR, net_input_shape)
    # BGR -> RGB
    #img = img[:,:, (2, 1, 0)]

    ## Method 1
    # imgT = np.transpose(img, (2, 0, 1))  # c,w,h
    # imgF = np.asarray(imgT, dtype=np.float32)
    # mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
    # imgS = np.subtract(imgF,mean)

    ## Method 2
    imgF = np.asarray(img, dtype=np.float32)
    mean = [128.0, 128.0, 128.0] # Caffe image mean
    # mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
    imgSS = np.subtract(imgF, mean)/128.0
    imgS = np.transpose(imgSS, (2, 0, 1))  # c,w,h

    # RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)

    return imgBGR, np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous 
Example #3
Source File: call_engine_to_infer_all.py    From iAI with MIT License 6 votes vote down vote up
def load_image(img_path, net_input_shape):
    img = cv2.resize(cv2.imread(img_path), net_input_shape)
    # BGR -> RGB
    #img = img[:,:, (2, 1, 0)]

    ## Method 1
    # imgT = np.transpose(img, (2, 0, 1))  # c,w,h
    # imgF = np.asarray(imgT, dtype=np.float32)
    # mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
    # imgS = np.subtract(imgF,mean)

    ## Method 2
    imgF = np.asarray(img, dtype=np.float32)
    mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
    imgSS = np.subtract(imgF, mean)
    imgS = np.transpose(imgSS, (2, 0, 1))  # CHW

    # RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)

    return np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous 
Example #4
Source File: call_engine_to_infer_all_analysis_error_6classes.py    From iAI with MIT License 6 votes vote down vote up
def load_image(img_path, net_input_shape):
    imgBGR = cv2.imread(img_path)
    img = cv2.resize(imgBGR, net_input_shape)
    # BGR -> RGB
    #img = img[:,:, (2, 1, 0)]

    ## Method 1
    # imgT = np.transpose(img, (2, 0, 1))  # c,w,h
    # imgF = np.asarray(imgT, dtype=np.float32)
    # mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
    # imgS = np.subtract(imgF,mean)

    ## Method 2
    imgF = np.asarray(img, dtype=np.float32)
    mean = [128.0, 128.0, 128.0] # Caffe image mean
    # mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
    imgSS = np.subtract(imgF, mean)/128.0
    imgS = np.transpose(imgSS, (2, 0, 1))  # c,w,h

    # RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)

    return imgBGR, np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous 
Example #5
Source File: call_engine_to_infer_one.py    From iAI with MIT License 6 votes vote down vote up
def load_image(img_path, net_input_shape):
    img = cv2.resize(cv2.imread(img_path), net_input_shape)
    # BGR -> RGB
    #img = img[:,:, (2, 1, 0)]

    ## Method 1
    # imgT = np.transpose(img, (2, 0, 1))  # c,w,h
    # imgF = np.asarray(imgT, dtype=np.float32)
    # mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
    # imgS = np.subtract(imgF,mean)

    ## Method 2
    imgF = np.asarray(img, dtype=np.float32)
    mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
    imgSS = np.subtract(imgF, mean)
    imgS = np.transpose(imgSS, (2, 0, 1))  # CHW

    # RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)

    return np.ascontiguousarray(imgS, dtype=np.float32)   # avoid error: ndarray is not contiguous 
Example #6
Source File: call_engine_to_infer_all_print_predict_on_image.py    From iAI with MIT License 6 votes vote down vote up
def load_image(img_path, net_input_shape):
    imgBGR = cv2.imread(img_path)
    img = cv2.resize(imgBGR, net_input_shape)
    # BGR -> RGB
    #img = img[:,:, (2, 1, 0)]

    ## Method 1
    # imgT = np.transpose(img, (2, 0, 1))  # c,w,h
    # imgF = np.asarray(imgT, dtype=np.float32)
    # mean = [[[88.159309]], [[97.966286]], [[103.66106]]] # Caffe image mean
    # imgS = np.subtract(imgF,mean)

    ## Method 2
    imgF = np.asarray(img, dtype=np.float32)
    mean = [88.159309, 97.966286, 103.66106] # Caffe image mean
    imgSS = np.subtract(imgF, mean)
    imgS = np.transpose(imgSS, (2, 0, 1))  # c,w,h

    # RGB_MEAN_PIXELS = np.array([88.159309, 97.966286, 103.66106]).reshape((1,1,1,3)).astype(np.float32)

    return imgBGR, np.ascontiguousarray(imgS, dtype=np.float32) # avoid error: ndarray is not contiguous 
Example #7
Source File: boxes.py    From Parsing-R-CNN with MIT License 6 votes vote down vote up
def soft_nms(
    dets, sigma=0.5, overlap_thresh=0.3, score_thresh=0.001, method='linear'
):
    """Apply the soft NMS algorithm from https://arxiv.org/abs/1704.04503."""
    if dets.shape[0] == 0:
        return dets, []

    methods = {'hard': 0, 'linear': 1, 'gaussian': 2}
    assert method in methods, 'Unknown soft_nms method: {}'.format(method)

    dets, keep = cython_nms.soft_nms(
        np.ascontiguousarray(dets, dtype=np.float32),
        np.float32(sigma),
        np.float32(overlap_thresh),
        np.float32(score_thresh),
        np.uint8(methods[method])
    )
    return dets, keep 
Example #8
Source File: kaldi_io.py    From audio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _convert_method_output_to_tensor(file_or_fd: Any,
                                     fn: Callable,
                                     convert_contiguous: bool = False) -> Iterable[Tuple[str, Tensor]]:
    r"""Takes a method invokes it. The output is converted to a tensor.

    Args:
        file_or_fd (str/FileDescriptor): File name or file descriptor
        fn (Callable): Function that has the signature (file name/descriptor) and converts it to
            Iterable[Tuple[str, Tensor]].
        convert_contiguous (bool, optional): Determines whether the array should be converted into a
            contiguous layout. (Default: ``False``)

    Returns:
        Iterable[Tuple[str, Tensor]]: The string is the key and the tensor is vec/mat
    """
    for key, np_arr in fn(file_or_fd):
        if convert_contiguous:
            np_arr = np.ascontiguousarray(np_arr)
        yield key, torch.from_numpy(np_arr) 
Example #9
Source File: utils.py    From VTuber_Unity with MIT License 6 votes vote down vote up
def transform_np(point, center, scale, resolution, invert=False):
    _pt = np.ones(3)
    _pt[0] = point[0]
    _pt[1] = point[1]

    h = 200.0 * scale
    t = np.eye(3)
    t[0, 0] = resolution / h
    t[1, 1] = resolution / h
    t[0, 2] = resolution * (-center[0] / h + 0.5)
    t[1, 2] = resolution * (-center[1] / h + 0.5)

    if invert:
        t = np.ascontiguousarray(np.linalg.pinv(t))

    new_point = np.dot(t, _pt)[0:2]

    return new_point.astype(np.int32) 
Example #10
Source File: spamvec.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, outcomes):
        """
        Initialize a StabilizerEffectVec object.

        Parameters
        ----------
        outcomes : iterable
            A list or other iterable of integer 0 or 1 outcomes specifying
            which POVM effect vector this object represents within the
            full `stabilizerPOVM`
        """
        self._outcomes = _np.ascontiguousarray(_np.array(outcomes, int), _np.int64)
        #Note: dtype='i' => int in Cython, whereas dtype=int/np.int64 => long in Cython
        rep = replib.SBEffectRep(self._outcomes)  # dim == 2**nqubits == 2**len(outcomes)
        SPAMVec.__init__(self, rep, "stabilizer", "effect")

    #def torep(self, typ, outvec=None):
    #    # changes to_statevec/to_dmvec -> todense, and have
    #    # torep create an effect rep object...
    #    return replib.SBEffectRep(_np.ascontiguousarray(self._outcomes, _np.int64)) 
Example #11
Source File: env_utils.py    From Pytorch-Project-Template with MIT License 6 votes vote down vote up
def get_screen(self, env):
        screen = env.render(mode='rgb_array').transpose((2, 0, 1))  # transpose into torch order (CHW)
        # Strip off the top and bottom of the screen
        screen = screen[:, 160:320]
        view_width = 320
        cart_location = self.get_cart_location(env)
        if cart_location < view_width // 2:
            slice_range = slice(view_width)
        elif cart_location > (self.screen_width - view_width // 2):
            slice_range = slice(-view_width, None)
        else:
            slice_range = slice(cart_location - view_width // 2,
                                cart_location + view_width // 2)
        # Strip off the edges, so that we have a square image centered on a cart
        screen = screen[:, :, slice_range]
        # Convert to float, rescale, convert to torch tensor
        screen = np.ascontiguousarray(screen, dtype=np.float32) / 255
        screen = torch.from_numpy(screen)
        # Resize, and add a batch dimension (BCHW)
        return resize(screen).unsqueeze(0) 
Example #12
Source File: datasets.py    From pruning_yolov3 with GNU General Public License v3.0 6 votes vote down vote up
def __next__(self):
        self.count += 1
        img0 = self.imgs.copy()
        if cv2.waitKey(1) == ord('q'):  # q to quit
            cv2.destroyAllWindows()
            raise StopIteration

        # Letterbox
        img = [letterbox(x, new_shape=self.img_size, interp=cv2.INTER_LINEAR)[0] for x in img0]

        # Stack
        img = np.stack(img, 0)

        # Normalize RGB
        img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)  # BGR to RGB
        img = np.ascontiguousarray(img, dtype=np.float16 if self.half else np.float32)  # uint8 to fp16/fp32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0

        return self.sources, img, img0, None 
Example #13
Source File: termforwardsim.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def _fill_hprobs_block(self, mxToFill, dest_indices, dest_param_indices1,
                           dest_param_indices2, evalTree, param_slice1, param_slice2,
                           comm=None, memLimit=None):
        if param_slice1 is None or param_slice1.start is None: param_slice1 = slice(0, self.Np)
        if param_slice2 is None or param_slice2.start is None: param_slice2 = slice(0, self.Np)
        if dest_param_indices1 is None: dest_param_indices1 = slice(0, _slct.length(param_slice1))
        if dest_param_indices2 is None: dest_param_indices2 = slice(0, _slct.length(param_slice2))

        if self.mode == "direct":
            raise NotImplementedError("hprobs does not support direct path-integral evaluation yet")
            # hprobs = self.hprs_directly(evalTree, ...)
        else:  # "pruned" or "taylor order"
            # evaluate derivative of polys
            nEls = evalTree.num_final_elements()
            polys = evalTree.merged_compact_polys
            wrtInds1 = _np.ascontiguousarray(_slct.indices(param_slice1), _np.int64)
            wrtInds2 = _np.ascontiguousarray(_slct.indices(param_slice2), _np.int64)
            dpolys = _compact_deriv(polys[0], polys[1], wrtInds1)
            hpolys = _compact_deriv(dpolys[0], dpolys[1], wrtInds2)
            hprobs = _safe_bulk_eval_compact_polys(
                hpolys[0], hpolys[1], self.paramvec, (nEls, len(wrtInds1), len(wrtInds2)))
        _fas(mxToFill, [dest_indices, dest_param_indices1, dest_param_indices2], hprobs) 
Example #14
Source File: swiftshader_renderer.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def _load_mesh_into_gl(self, mesh, material):
    vvt = np.concatenate((mesh.vertices, mesh.texturecoords[0,:,:2]), axis=1)
    vvt = np.ascontiguousarray(vvt[mesh.faces.reshape((-1)),:], dtype=np.float32)
    num = vvt.shape[0]
    vvt = np.reshape(vvt, (-1))

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vvt.dtype.itemsize*vvt.size, vvt, GL_STATIC_DRAW)

    tbo = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, tbo)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, material.shape[1],
                 material.shape[0], 0, GL_RGB, GL_UNSIGNED_BYTE,
                 np.reshape(material, (-1)))
    return num, vbo, tbo 
Example #15
Source File: swiftshader_renderer.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def load_default_object(self):
    v = np.array([[0.0, 0.5, 0.0, 1.0, 1.0, 0.0, 1.0],
                  [-0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0],
                  [0.5, -0.5, 0.0, 1.0, 1.0, 1.0, 1.0]], dtype=np.float32)
    v = np.concatenate((v,v+0.1), axis=0)
    v = np.ascontiguousarray(v, dtype=np.float32)

    vbo = glGenBuffers(1)
    glBindBuffer (GL_ARRAY_BUFFER, vbo)
    glBufferData (GL_ARRAY_BUFFER, v.dtype.itemsize*v.size, v, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(0))
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(12))
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    self.num_to_render = 6; 
Example #16
Source File: misc.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
    """Convert tensor to images.

    Args:
        tensor (torch.Tensor): Tensor that contains multiple images
        mean (tuple[float], optional): Mean of images. Defaults to (0, 0, 0).
        std (tuple[float], optional): Standard deviation of images.
            Defaults to (1, 1, 1).
        to_rgb (bool, optional): Whether convert the images to RGB format.
            Defaults to True.

    Returns:
        list[np.ndarray]: A list that contains multiple images.
    """
    num_imgs = tensor.size(0)
    mean = np.array(mean, dtype=np.float32)
    std = np.array(std, dtype=np.float32)
    imgs = []
    for img_id in range(num_imgs):
        img = tensor[img_id, ...].cpu().numpy().transpose(1, 2, 0)
        img = mmcv.imdenormalize(
            img, mean, std, to_bgr=to_rgb).astype(np.uint8)
        imgs.append(np.ascontiguousarray(img))
    return imgs 
Example #17
Source File: utils_image.py    From KAIR with MIT License 6 votes vote down vote up
def augment_img_tensor(img, mode=0):
    '''Kai Zhang (github: https://github.com/cszn)
    '''
    img_size = img.size()
    img_np = img.data.cpu().numpy()
    if len(img_size) == 3:
        img_np = np.transpose(img_np, (1, 2, 0))
    elif len(img_size) == 4:
        img_np = np.transpose(img_np, (2, 3, 1, 0))
    img_np = augment_img(img_np, mode=mode)
    img_tensor = torch.from_numpy(np.ascontiguousarray(img_np))
    if len(img_size) == 3:
        img_tensor = img_tensor.permute(2, 0, 1)
    elif len(img_size) == 4:
        img_tensor = img_tensor.permute(3, 2, 0, 1)

    return img_tensor.type_as(img) 
Example #18
Source File: json_serializers.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def serialize_ndarray_b64(o):
    """
    Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
    human-readable, but the array data itself is binary64 encoded.

    Args:
        o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if o.flags['C_CONTIGUOUS']:
        o_data = o.data
    else:
        o_data = np.ascontiguousarray(o).data
    data_b64 = base64.b64encode(o_data)
    return dict(
        _type='np.ndarray',
        data=data_b64.decode('utf-8'),
        dtype=o.dtype,
        shape=o.shape) 
Example #19
Source File: utils_image.py    From KAIR with MIT License 5 votes vote down vote up
def single2tensor3(img):
    return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float()


# convert single (HxWxC) to 4-dimensional torch tensor 
Example #20
Source File: utils_image.py    From KAIR with MIT License 5 votes vote down vote up
def uint2tensor4(img):
    if img.ndim == 2:
        img = np.expand_dims(img, axis=2)
    return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.).unsqueeze(0)


# convert uint to 3-dimensional torch tensor 
Example #21
Source File: utils_image.py    From KAIR with MIT License 5 votes vote down vote up
def uint2tensor3(img):
    if img.ndim == 2:
        img = np.expand_dims(img, axis=2)
    return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.)


# convert 2/3/4-dimensional torch tensor to uint 
Example #22
Source File: numeric.py    From recruit with Apache License 2.0 5 votes vote down vote up
def asfortranarray(a, dtype=None):
    """
    Return an array (ndim >= 1) laid out in Fortran order in memory.

    Parameters
    ----------
    a : array_like
        Input array.
    dtype : str or dtype object, optional
        By default, the data-type is inferred from the input data.

    Returns
    -------
    out : ndarray
        The input `a` in Fortran, or column-major, order.

    See Also
    --------
    ascontiguousarray : Convert input to a contiguous (C order) array.
    asanyarray : Convert input to an ndarray with either row or
        column-major memory order.
    require : Return an ndarray that satisfies requirements.
    ndarray.flags : Information about the memory layout of the array.

    Examples
    --------
    >>> x = np.arange(6).reshape(2,3)
    >>> y = np.asfortranarray(x)
    >>> x.flags['F_CONTIGUOUS']
    False
    >>> y.flags['F_CONTIGUOUS']
    True

    Note: This function returns an array with at least one-dimension (1-d) 
    so it will not preserve 0-d arrays.  

    """
    return array(a, dtype, copy=False, order='F', ndmin=1) 
Example #23
Source File: numeric.py    From recruit with Apache License 2.0 5 votes vote down vote up
def ascontiguousarray(a, dtype=None):
    """
    Return a contiguous array (ndim >= 1) in memory (C order).

    Parameters
    ----------
    a : array_like
        Input array.
    dtype : str or dtype object, optional
        Data-type of returned array.

    Returns
    -------
    out : ndarray
        Contiguous array of same shape and content as `a`, with type `dtype`
        if specified.

    See Also
    --------
    asfortranarray : Convert input to an ndarray with column-major
                     memory order.
    require : Return an ndarray that satisfies requirements.
    ndarray.flags : Information about the memory layout of the array.

    Examples
    --------
    >>> x = np.arange(6).reshape(2,3)
    >>> np.ascontiguousarray(x, dtype=np.float32)
    array([[ 0.,  1.,  2.],
           [ 3.,  4.,  5.]], dtype=float32)
    >>> x.flags['C_CONTIGUOUS']
    True

    Note: This function returns an array with at least one-dimension (1-d) 
    so it will not preserve 0-d arrays.  

    """
    return array(a, dtype, copy=False, order='C', ndmin=1) 
Example #24
Source File: termforwardsim.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def _fill_dprobs_block(self, mxToFill, dest_indices, dest_param_indices, evalTree, param_slice, comm=None,
                           memLimit=None):
        if param_slice is None: param_slice = slice(0, self.Np)
        if dest_param_indices is None: dest_param_indices = slice(0, _slct.length(param_slice))

        if self.mode == "direct":
            dprobs = self.dprs_directly(evalTree, param_slice, comm, memLimit)
        else:  # "pruned" or "taylor order"
            # evaluate derivative of polys
            nEls = evalTree.num_final_elements()
            polys = evalTree.merged_compact_polys
            wrtInds = _np.ascontiguousarray(_slct.indices(param_slice), _np.int64)  # for Cython arg mapping
            dpolys = _compact_deriv(polys[0], polys[1], wrtInds)
            dprobs = _safe_bulk_eval_compact_polys(dpolys[0], dpolys[1], self.paramvec, (nEls, len(wrtInds)))
        _fas(mxToFill, [dest_indices, dest_param_indices], dprobs) 
Example #25
Source File: misc.py    From AerialDetection with Apache License 2.0 5 votes vote down vote up
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
    num_imgs = tensor.size(0)
    mean = np.array(mean, dtype=np.float32)
    std = np.array(std, dtype=np.float32)
    imgs = []
    for img_id in range(num_imgs):
        img = tensor[img_id, ...].cpu().numpy().transpose(1, 2, 0)
        img = mmcv.imdenormalize(
            img, mean, std, to_bgr=to_rgb).astype(np.uint8)
        imgs.append(np.ascontiguousarray(img))
    return imgs 
Example #26
Source File: post_process_crf.py    From Attention-Gated-Networks with MIT License 5 votes vote down vote up
def apply_crf(input_image, input_prob, theta_a, theta_b, theta_r, mu1, mu2):
    n_slices = input_image.shape[2]
    output = np.zeros(input_image.shape)
    for slice_id in range(n_slices):
        image = input_image[:,:,slice_id]
        prob = input_prob[:,:,slice_id,:]

        n_pixel = image.shape[0] * image.shape[1]
        n_class = prob.shape[-1]

        P = np.transpose(prob, axes=(2, 0, 1))

        # Setup the CRF model
        d = dcrf.DenseCRF(n_pixel, n_class)

        # Set unary potentials (negative log probability)
        U = - np.log(P + 1e-10)
        U = np.ascontiguousarray(U.reshape((n_class, n_pixel)))
        d.setUnaryEnergy(U)

        # Set edge potential
        # This creates the color-dependent features and then add them to the CRF
        feats = create_pairwise_bilateral(sdims=(theta_a, theta_a), schan=(theta_b,), img=image, chdim=-1)
        d.addPairwiseEnergy(feats, compat=mu1, kernel=dcrf.DIAG_KERNEL, normalization=dcrf.NORMALIZE_SYMMETRIC)

        # This creates the color-independent features and then add them to the CRF
        feats = create_pairwise_gaussian(sdims=(theta_r, theta_r), shape=image.shape)
        d.addPairwiseEnergy(feats, compat=mu2, kernel=dcrf.DIAG_KERNEL, normalization=dcrf.NORMALIZE_SYMMETRIC)

        # Perform the inference
        Q = d.inference(5)
        res = np.argmax(Q, axis=0).astype('float32')
        res = np.reshape(res, image.shape).astype(dtype='int8')
        output[:,:,slice_id] = res

    return output 
Example #27
Source File: matrixtools.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def csr_sum_flat(data, coeffs, flat_dest_index_array, flat_csr_mx_data, mx_nnz_indptr):
        coeffs_complex = _np.ascontiguousarray(coeffs, dtype=complex)
        return _fastcalc.fast_csr_sum_flat(data, coeffs_complex, flat_dest_index_array, flat_csr_mx_data, mx_nnz_indptr) 
Example #28
Source File: spamvec.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def todense(self, scratch=None):
        """
        Return this SPAM vector as a (dense) numpy array.  The memory
        in `scratch` maybe used when it is not-None.
        """
        if self._evotype == "densitymx":
            v0 = 1.0 / _np.sqrt(2) * _np.array((1, 0, 0, 1), 'd')  # '0' qubit state as Pauli dmvec
            v1 = 1.0 / _np.sqrt(2) * _np.array((1, 0, 0, -1), 'd')  # '1' qubit state as Pauli dmvec
        elif self._evotype in ("statevec", "stabilizer"):
            v0 = _np.array((1, 0), complex)  # '0' qubit state as complex state vec
            v1 = _np.array((0, 1), complex)  # '1' qubit state as complex state vec
        elif self._evotype in ("svterm", "cterm"):
            raise NotImplementedError("todense() is not implemented for evotype %s!" %
                                      self._evotype)
        else: raise ValueError("Invalid `evotype`: %s" % self._evotype)

        v = (v0, v1)
        return _functools.reduce(_np.kron, [v[i] for i in self._zvals])

    #def torep(self, typ, outvec=None):
    #    if typ == "prep":
    #        if self._evotype == "statevec":
    #            return replib.SVStateRep(self.todense())
    #        elif self._evotype == "densitymx":
    #            return replib.DMStateRep(self.todense())
    #        elif self._evotype == "stabilizer":
    #            sframe = _stabilizer.StabilizerFrame.from_zvals(len(self._zvals), self._zvals)
    #            return sframe.torep()
    #        raise NotImplementedError("torep(%s) not implemented for %s objects!" %
    #                                  (self._evotype, self.__class__.__name__))
    #    elif typ == "effect":
    #        if self._evotype == "statevec":
    #            return replib.SVEffectRep_Computational(self._zvals, self.dim)
    #        elif self._evotype == "densitymx":
    #            return replib.DMEffectRep_Computational(self._zvals, self.dim)
    #        elif self._evotype == "stabilizer":
    #            return replib.SBEffectRep(_np.ascontiguousarray(self._zvals, _np.int64))
    #        raise NotImplementedError("torep(%s) not implemented for %s objects!" %
    #                                  (self._evotype, self.__class__.__name__))
    #    else:
    #        raise ValueError("Invalid `typ` argument for torep(): %s" % typ) 
Example #29
Source File: slowreplib.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def aslinearoperator(self):
        def mv(v):
            if v.ndim == 2 and v.shape[1] == 1: v = v[:, 0]
            in_state = DMStateRep(_np.ascontiguousarray(v, 'd'))
            return self.acton(in_state).todense()

        def rmv(v):
            if v.ndim == 2 and v.shape[1] == 1: v = v[:, 0]
            in_state = DMStateRep(_np.ascontiguousarray(v, 'd'))
            return self.adjoint_acton(in_state).todense()
        return LinearOperator((self.dim, self.dim), matvec=mv, rmatvec=rmv)  # transpose, adjoint, dot, matmat? 
Example #30
Source File: gpc.py    From simnibs with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, mesh, poslist, fn_hdf5, fnamecoil, matsimnibs, didt, roi=[2]):
        super(TMSgPCSampler, self).__init__(
            mesh, poslist, fn_hdf5, roi=roi)
        self.matsimnibs = np.ascontiguousarray(matsimnibs)
        self.didt = didt
        self.fnamecoil = fnamecoil
        self.constant_dAdt = True