Python numpy.atleast_3d() Examples

The following are 30 code examples of numpy.atleast_3d(). 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: mrc.py    From pyem with GNU General Public License v3.0 6 votes vote down vote up
def append(fname, data):
    data = np.atleast_3d(data)
    with open(fname, 'r+b') as f:
        nx, ny, nz = np.fromfile(f, dtype=np.int32, count=3)
        f.seek(36)  # First byte of zlen.
        zlen = np.fromfile(f, dtype=np.float32, count=1)
        if data.shape[0] != nx or data.shape[1] != ny:
            raise ValueError("Data has different shape than destination file")
        f.seek(0, os.SEEK_END)
        f.write(np.require(data, dtype=np.float32).tobytes(order="F"))
        # Update header after new data is written.
        apix = zlen / nz
        nz += data.shape[2]
        zlen += apix * data.shape[2]
        f.seek(8)
        nz.astype(np.int32).tofile(f)
        f.seek(36)
        zlen.astype(np.float32).tofile(f) 
Example #2
Source File: image.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def range(cls, obj, dim):
        dim_idx = obj.get_dimension_index(dim)
        if dim_idx in [0, 1] and obj.bounds:
            l, b, r, t = obj.bounds.lbrt()
            if dim_idx:
                (low, high) = (b, t)
                density = obj.ydensity
            else:
                low, high = (l, r)
                density = obj.xdensity
            halfd = (1./density)/2.
            if isinstance(low, util.datetime_types):
                halfd = np.timedelta64(int(round(halfd)), obj._time_unit)
            drange = (low+halfd, high-halfd)
        elif 1 < dim_idx < len(obj.vdims) + 2:
            dim_idx -= 2
            data = np.atleast_3d(obj.data)[:, :, dim_idx]
            drange = (np.nanmin(data), np.nanmax(data))
        else:
            drange = (None, None)
        return drange 
Example #3
Source File: dataset.py    From Unet_pytorch with MIT License 6 votes vote down vote up
def __getitem__(self, idx):
    if self.train:
      img_path, gt_path = self.train_set_path[idx]

      img = imread(img_path)
      img = img[0:self.nRow, 0:self.nCol]
      img = np.atleast_3d(img).transpose(2, 0, 1).astype(np.float32)
      img = (img - img.min()) / (img.max() - img.min())
      img = torch.from_numpy(img).float()

      gt = imread(gt_path)[0:self.nRow, 0:self.nCol]
      gt = np.atleast_3d(gt).transpose(2, 0, 1)
      gt = gt / 255.0
      gt = torch.from_numpy(gt).float()

      return img, gt 
Example #4
Source File: util.py    From tf_unet with GNU General Public License v3.0 6 votes vote down vote up
def to_rgb(img):
    """
    Converts the given array into a RGB image. If the number of channels is not
    3 the array is tiled such that it has 3 channels. Finally, the values are
    rescaled to [0,255)

    :param img: the array to convert [nx, ny, channels]

    :returns img: the rgb image [nx, ny, 3]
    """
    img = np.atleast_3d(img)
    channels = img.shape[2]
    if channels < 3:
        img = np.tile(img, 3)

    img[np.isnan(img)] = 0
    img -= np.amin(img)
    if np.amax(img) != 0:
        img /= np.amax(img)

    img *= 255
    return img 
Example #5
Source File: renderer.py    From opendr with MIT License 6 votes vote down vote up
def draw_color_image(self, gl):
        self._call_on_changed()
        gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        # use face colors if given
        # FIXME: this won't work for 2 channels
        draw_colored_verts(gl, self.v.r, self.f, self.vc.r)

        result = np.asarray(deepcopy(gl.getImage()[:,:,:self.num_channels].squeeze()), np.float64)

        if hasattr(self, 'background_image'):
            bg_px = np.tile(np.atleast_3d(self.visibility_image) == 4294967295, (1,1,self.num_channels)).squeeze()
            fg_px = 1 - bg_px
            result = bg_px * self.background_image + fg_px * result

        return result 
Example #6
Source File: renderer.py    From opendr with MIT License 6 votes vote down vote up
def color_image(self):
        gl = self.glf
        gl.PolygonMode(GL_FRONT_AND_BACK, GL_FILL)
        no_overdraw = self.draw_color_image(gl)

        if not self.overdraw:
            return no_overdraw

        gl.PolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        overdraw = self.draw_color_image(gl)
        gl.PolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        boundarybool_image = self.boundarybool_image
        if self.num_channels > 1:
            boundarybool_image = np.atleast_3d(boundarybool_image)
        return np.asarray((overdraw*boundarybool_image + no_overdraw*(1-boundarybool_image)), order='C') 
Example #7
Source File: common.py    From opendr with MIT License 6 votes vote down vote up
def nangradients(arr):
    dy = np.expand_dims(arr[:-1,:,:] - arr[1:,:,:], axis=3)
    dx = np.expand_dims(arr[:,:-1,:] - arr[:, 1:, :], axis=3)

    dy = np.concatenate((dy[1:,:,:], dy[:-1,:,:]), axis=3)
    dy = nanmean(dy, axis=3)
    dx = np.concatenate((dx[:,1:,:], dx[:,:-1,:]), axis=3)
    dx = nanmean(dx, axis=3)

    if arr.shape[2] > 1:
        gy, gx, _ = np.gradient(arr)
    else:
        gy, gx = np.gradient(arr.squeeze())
        gy = np.atleast_3d(gy)
        gx = np.atleast_3d(gx)
    gy[1:-1,:,:] = -dy
    gx[:,1:-1,:] = -dx

    return gy, gx 
Example #8
Source File: instance.py    From deconvfaces with MIT License 6 votes vote down vote up
def __init__(self, directory, filepath, image_size):
        """
        Constructor for an JAFFEInstance object.

        Args:
            directory (str): Base directory where the example lives.
            filename (str): The name of the file of the example.
            image_size (tuple<int>): Size to resize the image to.
        """

        filename = filepath.split('/')[-1]

        self.image = misc.imread( os.path.join(directory, filepath) )
        # some of the jaffe images are 3-channel greyscale, some are 1-channel!
        self.image = np.atleast_3d(self.image)[...,0] # make image 2d for sure
        # Resize and scale values to [0 1]
        self.image = misc.imresize( self.image, image_size )
        self.image = self.image / 255.0
        ident, _, N, _ = filename.split('.')
        # Note: the emotion encoded in the filename is the dominant
        # scoring emotion, but we ignore this and use precise emotion scores
        # from the semantic ratings table
        self.identity, self.N = ident, int(N) - 1 # 0-based instance numbering 
Example #9
Source File: feature_functions.py    From seglearn with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def corr2(X):
    """ computes correlations between all variable pairs in a segmented time series

    .. note:: this feature is expensive to compute with the current implementation, and cannot be
    used with univariate time series
    """
    X = np.atleast_3d(X)
    N = X.shape[0]
    D = X.shape[2]

    if D == 1:
        return np.zeros(N, dtype=np.float)

    trii = np.triu_indices(D, k=1)
    DD = len(trii[0])
    r = np.zeros((N, DD))
    for i in np.arange(N):
        rmat = np.corrcoef(X[i])  # get the ith window from each signal, result will be DxD
        r[i] = rmat[trii]
    return r 
Example #10
Source File: augmentation.py    From phocnet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def rotate_bboxes(image, obj_list, angle):
        '''
        Rotates the bounding boxes of the given objects by the given angle. The bounding box will be
        translated into absolute coordinates. Therefore the image (resp. its shape) is needed.
        '''
        
        rotated_obj_list = []
        cosOfAngle = np.cos(2 * np.pi / 360 * -angle)
        sinOfAngle = np.sin(2 * np.pi / 360 * -angle)
        image_shape = np.array(np.atleast_3d(image).shape[0:2][::-1])
        rot_mat = np.array([[cosOfAngle, -sinOfAngle], [sinOfAngle, cosOfAngle]])
        for obj in obj_list:
            obj_name = obj[0]
            upper_left = obj[1]['upper_left'] * image_shape
            lower_right = obj[1]['lower_right'] * image_shape
            upper_left = AugmentationCreator._rotate_vector_around_point(image_shape/2, upper_left, rot_mat) / image_shape
            lower_right = AugmentationCreator._rotate_vector_around_point(image_shape/2, lower_right, rot_mat) / image_shape
            rotated_obj_list.append((obj_name, {'upper_left' : upper_left, 'lower_right' : lower_right}))
            
        return rotated_obj_list 
Example #11
Source File: augmentation.py    From phocnet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def rotate_points(image, obj_list, angle):
        '''
        Rotates the points of the given objects by the given angle. The points will be translated
        into absolute coordinates. Therefore the image (resp. its shape) is needed.
        '''
        
        rotated_obj_list = []
        cosOfAngle = np.cos(2 * np.pi / 360 * -angle)
        sinOfAngle = np.sin(2 * np.pi / 360 * -angle)
        image_shape = np.array(np.atleast_3d(image).shape[0:2][::-1])
        rot_mat = np.array([[cosOfAngle, -sinOfAngle], [sinOfAngle, cosOfAngle]])
        for obj in obj_list:
            obj_name = obj[0]
            point = obj[1] * image_shape
            rotated_point = AugmentationCreator._rotate_vector_around_point(image_shape/2, point, rot_mat) / image_shape
            rotated_obj_list.append((obj_name, (rotated_point[0], rotated_point[1])))
            
        return rotated_obj_list 
Example #12
Source File: mrc.py    From pyem with GNU General Public License v3.0 6 votes vote down vote up
def write(fname, data, psz=1, origin=None, fast=False):
    """
    Write a MRC file. Fortran axes order is assumed.
    :param fname: Destination path.
    :param data: Array to write.
    :param psz: Pixel size in Å for MRC header.
    :param origin: Coordinate of origin voxel.
    :param fast: Skip computing density statistics in header. Default is False.
    """
    data = np.atleast_3d(data)
    if fast:
        header = mrc_header(data.shape, dtype=data.dtype, psz=psz)
    else:
        header = mrc_header_complete(data, psz=psz, origin=origin)
    with open(fname, 'wb') as f:
        f.write(header.tobytes())
        f.write(np.require(data, dtype=np.float32).tobytes(order="F")) 
Example #13
Source File: ols.py    From pyfinance with MIT License 6 votes vote down vote up
def _rolling_lstsq(x, y):
    """Finds solution for the rolling case.  Matrix formulation."""
    if x.ndim == 2:
        # Treat everything as 3d and avoid AxisError on .swapaxes(1, 2) below
        # This means an original input of:
        #     array([0., 1., 2., 3., 4., 5., 6.])
        # becomes:
        # array([[[0.],
        #         [1.],
        #         [2.],
        #         [3.]],
        #
        #        [[1.],
        #         [2.],
        #         ...
        x = x[:, :, None]
    elif x.ndim <= 1:
        raise np.AxisError("x should have ndmi >= 2")
    return np.squeeze(
        np.matmul(
            np.linalg.inv(np.matmul(x.swapaxes(1, 2), x)),
            np.matmul(x.swapaxes(1, 2), np.atleast_3d(y)),
        )
    ) 
Example #14
Source File: blend.py    From imgaug with MIT License 6 votes vote down vote up
def _binarize_mask(cls, mask, arr_height, arr_width):
        # Average over channels, resize to heatmap/segmap array size
        # (+clip for cubic interpolation). We can use none-NN interpolation
        # for segmaps here as this is just the mask and not the segmap
        # array.
        mask_3d = np.atleast_3d(mask)

        # masks with zero-sized axes crash in np.average() and cannot be
        # upscaled in imresize_single_image()
        if mask.size == 0:
            mask_rs = np.zeros((arr_height, arr_width),
                               dtype=np.float32)
        else:
            mask_avg = (
                np.average(mask_3d, axis=2) if mask_3d.shape[2] > 0 else 1.0)
            mask_rs = ia.imresize_single_image(mask_avg,
                                               (arr_height, arr_width))
        mask_arr = iadt.clip_(mask_rs, 0, 1.0)
        mask_arr_binarized = (mask_arr >= 0.5)
        return mask_arr_binarized

    # Added in 0.4.0. 
Example #15
Source File: merger.py    From buzzard with Apache License 2.0 6 votes vote down vote up
def _normalize_user_result(self, cache_fp, res):
        try:
            res = np.atleast_3d(res)
        except: # pragma: no cover
            raise ValueError("Result of recipe's `merge_arrays` has type {}, it can't be converted to ndarray".format(
                type(res)
            ))
        y, x, c = res.shape
        if (y, x) != tuple(cache_fp.shape): # pragma: no cover
            raise ValueError("Result of recipe's `merge_arrays` has shape `{}`, should start with {}".format(
                res.shape,
                cache_fp.shape,
            ))
        if c != len(self._raster): # pragma: no cover
            raise ValueError("Result of recipe's `merge_arrays` has shape `{}`, should have {} bands".format(
                res.shape,
                len(self._raster),
            ))
        res = res.astype(self._raster.dtype, copy=False)
        return res

    # ******************************************************************************************* ** 
Example #16
Source File: computer.py    From buzzard with Apache License 2.0 6 votes vote down vote up
def _normalize_user_result(self, compute_fp, res):
        if not isinstance(res, np.ndarray): # pragma: no cover
            raise ValueError("Result of recipe's `compute_array` have type {}, it should be ndarray".format(
                type(res)
            ))
        res = np.atleast_3d(res)
        y, x, c = res.shape
        if (y, x) != tuple(compute_fp.shape): # pragma: no cover
            raise ValueError("Result of recipe's `compute_array` have shape `{}`, should start with {}".format(
                res.shape,
                compute_fp.shape,
            ))
        if c != len(self._raster): # pragma: no cover
            raise ValueError("Result of recipe's `compute_array` have shape `{}`, should have {} bands".format(
                res.shape,
                len(self._raster),
            ))
        res = res.astype(self._raster.dtype, copy=False)
        return res

    # ******************************************************************************************* ** 
Example #17
Source File: recmat.py    From quail with MIT License 6 votes vote down vote up
def _recmat_smooth(presented, recalled, features, distance, match):

    if match == 'best':
        func = np.argmax
    elif match == 'smooth':
        func = np.nanmean

    simmtx = _similarity_smooth(presented, recalled, features, distance)


    if match == 'best':
        recmat = np.atleast_3d([func(s, 1) for s in simmtx]).astype(np.float64)
        recmat+=1
        recmat[np.isnan(simmtx).any(2)]=np.nan
    elif match == 'smooth':
        recmat = np.atleast_3d([func(s, 0) for s in simmtx]).astype(np.float64)


    return recmat 
Example #18
Source File: conftest.py    From xclim with Apache License 2.0 6 votes vote down vote up
def pr_ndseries():
    def _pr_series(values, start="1/1/2000"):
        nt, nx, ny = np.atleast_3d(values).shape
        time = pd.date_range(start, periods=nt, freq=pd.DateOffset(days=1))
        x = np.arange(nx)
        y = np.arange(ny)
        return xr.DataArray(
            values,
            coords=[time, x, y],
            dims=("time", "x", "y"),
            name="pr",
            attrs={
                "standard_name": "precipitation_flux",
                "cell_methods": "time: sum over day",
                "units": "kg m-2 s-1",
            },
        )

    return _pr_series 
Example #19
Source File: utilty.py    From dcscn-super-resolution with MIT License 6 votes vote down vote up
def load_image(filename, width=0, height=0, channels=0, alignment=0, print_console=True):
    if not os.path.isfile(filename):
        raise LoadError("File not found [%s]" % filename)

    try:
        image = np.atleast_3d(misc.imread(filename))

        if (width != 0 and image.shape[1] != width) or (height != 0 and image.shape[0] != height):
            raise LoadError("Attributes mismatch")
        if channels != 0 and image.shape[2] != channels:
            raise LoadError("Attributes mismatch")
        if alignment != 0 and ((width % alignment) != 0 or (height % alignment) != 0):
            raise LoadError("Attributes mismatch")

        # if there is alpha plane, cut it
        if image.shape[2] >= 4:
            image = image[:, :, 0:3]

        if print_console:
            print("Loaded [%s]: %d x %d x %d" % (filename, image.shape[1], image.shape[0], image.shape[2]))
    except IndexError:
        print("IndexError: file:[%s] shape[%s]" % (filename, image.shape))
        return None

    return image 
Example #20
Source File: __funcs__.py    From porespy with MIT License 6 votes vote down vote up
def porosity_profile(im, axis):
    r"""
    Returns a porosity profile along the specified axis

    Parameters
    ----------
    im : ND-array
        The volumetric image for which to calculate the porosity profile
    axis : int
        The axis (0, 1, or 2) along which to calculate the profile.  For
        instance, if `axis` is 0, then the porosity in each YZ plane is
        calculated and returned as 1D array with 1 value for each X position.

    Returns
    -------
    result : 1D-array
        A 1D-array of porosity along the specified axis
    """
    if axis >= im.ndim:
        raise Exception('axis out of range')
    im = np.atleast_3d(im)
    a = set(range(im.ndim)).difference(set([axis]))
    a1, a2 = a
    prof = np.sum(np.sum(im, axis=a2), axis=a1)/(im.shape[a2]*im.shape[a1])
    return prof*100 
Example #21
Source File: reordering.py    From chumpy with MIT License 5 votes vote down vote up
def compute_r(self):
        xr = self.x.r
        if self.ndims == 1:
            target_shape = np.atleast_1d(xr).shape
        elif self.ndims == 2:
            target_shape = np.atleast_2d(xr).shape
        elif self.ndims == 3:
            target_shape = np.atleast_3d(xr).shape
        else:
            raise Exception('Need ndims to be 1, 2, or 3.')

        return xr.reshape(target_shape) 
Example #22
Source File: bootstrapped_results.py    From pyblp with MIT License 5 votes vote down vote up
def _coerce_optional_costs(self, costs: Optional[Any], market_ids: Array) -> Array:
        """Coerce optional array-like costs into a column vector tensor and validate it."""
        if costs is None:
            return None
        costs = np.atleast_3d(np.asarray(costs, options.dtype))
        rows = sum(i.size for t, i in self.problem._product_market_indices.items() if t in market_ids)
        if costs.shape != (self.draws, rows, 1):
            raise ValueError(f"costs must be None or {self.draws} by {rows}.")
        return costs 
Example #23
Source File: image_reporting.py    From trains with Apache License 2.0 5 votes vote down vote up
def report_debug_images(logger, iteration=0):
    # type: (Logger, int) -> ()
    """
    reporting images to debug samples section
    :param logger: The task.logger to use for sending the plots
    :param iteration: The iteration number of the current reports
    """

    # report image as float image
    m = np.eye(256, 256, dtype=np.float)
    logger.report_image("image", "image float", iteration=iteration, image=m)

    # report image as uint8
    m = np.eye(256, 256, dtype=np.uint8) * 255
    logger.report_image("image", "image uint8", iteration=iteration, image=m)

    # report image as uint8 RGB
    m = np.concatenate((np.atleast_3d(m), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2)
    logger.report_image("image", "image color red", iteration=iteration, image=m)

    # report PIL Image object
    image_open = Image.open(os.path.join("data_samples", "picasso.jpg"))
    logger.report_image("image", "image PIL", iteration=iteration, image=image_open)

    # Image can be uploaded via 'report_media' too.
    logger.report_media(
        "image",
        "image with report media",
        iteration=iteration,
        local_path=os.path.join("data_samples", "picasso.jpg"),
        file_extension="jpg",
    ) 
Example #24
Source File: bootstrapped_results.py    From pyblp with MIT License 5 votes vote down vote up
def _coerce_optional_delta(self, delta: Optional[Any], market_ids: Array) -> Array:
        """Coerce optional array-like mean utilities into a column vector tensor and validate it."""
        if delta is None:
            return None
        delta = np.atleast_3d(np.asarray(delta, options.dtype))
        rows = sum(i.size for t, i in self.problem._product_market_indices.items() if t in market_ids)
        if delta.shape != (self.draws, rows, 1):
            raise ValueError(f"delta must be None or {self.draws} by {rows}.")
        return delta 
Example #25
Source File: utilities.py    From uois with GNU General Public License v3.0 5 votes vote down vote up
def imwrite_indexed(filename,array):
    """ Save indexed png with palette."""

    palette_abspath = '/data/tabletop_dataset_v5/palette.txt' # hard-coded filepath
    color_palette = np.loadtxt(palette_abspath, dtype=np.uint8).reshape(-1,3)

    if np.atleast_3d(array).shape[2] != 1:
        raise Exception("Saving indexed PNGs requires 2D array.")

    im = Image.fromarray(array)
    im.putpalette(color_palette.ravel())
    im.save(filename, format='PNG') 
Example #26
Source File: bootstrapped_results.py    From pyblp with MIT License 5 votes vote down vote up
def _coerce_matrices(self, matrices: Any, market_ids: Array) -> Array:
        """Coerce array-like stacked matrix tensors into a stacked matrix tensor and validate it."""
        matrices = np.atleast_3d(np.asarray(matrices, options.dtype))
        rows = sum(i.size for t, i in self.problem._product_market_indices.items() if t in market_ids)
        columns = max(i.size for t, i in self.problem._product_market_indices.items() if t in market_ids)
        if matrices.shape != (self.draws, rows, columns):
            raise ValueError(f"matrices must be {self.draws} by {rows} by {columns}.")
        return matrices 
Example #27
Source File: feature_functions.py    From seglearn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, X):
        X = np.atleast_3d(X)
        N = X.shape[0]
        D = X.shape[2]
        histogram = np.zeros((N, D * self.bins))
        for i in np.arange(N):
            for j in np.arange(D):
                # for each variable, advance by bins
                histogram[i, (j * self.bins):((j + 1) * self.bins)] = \
                    np.histogram(X[i, :, j], bins=self.bins, density=True)[0]

        return histogram 
Example #28
Source File: feature_functions.py    From seglearn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mean_crossings(X):
    """ Computes number of mean crossings for each variable in a segmented time series """
    X = np.atleast_3d(X)
    N = X.shape[0]
    D = X.shape[2]
    mnx = np.zeros((N, D))
    for i in range(D):
        pos = X[:, :, i] > 0
        npos = ~pos
        c = (pos[:, :-1] & npos[:, 1:]) | (npos[:, :-1] & pos[:, 1:])
        mnx[:, i] = np.count_nonzero(c, axis=1)
    return mnx 
Example #29
Source File: transform.py    From seglearn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _select(Xt, cols):
        """
        Select slices of the last dimension from time series data of the form
        num_samples x segment_size x num_features.
        """
        return np.atleast_3d(Xt)[:, :, cols] 
Example #30
Source File: grads.py    From tangent with Apache License 2.0 5 votes vote down vote up
def atleast_3d(y, x):
  d[x] = numpy.reshape(d[y], numpy.shape(x))