Python numpy.atleast_3d() Examples

The following are 30 code examples for showing how to use numpy.atleast_3d(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: quail   Author: ContextLab   File: recmat.py    License: 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 2
Project: buzzard   Author: airware   File: computer.py    License: 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 3
Project: buzzard   Author: airware   File: merger.py    License: 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 4
Project: phocnet   Author: ssudholt   File: augmentation.py    License: 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 5
Project: phocnet   Author: ssudholt   File: augmentation.py    License: 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 6
Project: tf_unet   Author: jakeret   File: util.py    License: 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 7
Project: imgaug   Author: aleju   File: blend.py    License: 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 8
Project: opendr   Author: mattloper   File: renderer.py    License: 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 9
Project: opendr   Author: mattloper   File: renderer.py    License: 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 10
Project: opendr   Author: mattloper   File: common.py    License: 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 11
Project: seglearn   Author: dmbee   File: feature_functions.py    License: 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 12
Project: deconvfaces   Author: zo7   File: instance.py    License: 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 13
Project: Unet_pytorch   Author: jakeoung   File: dataset.py    License: 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 14
Project: holoviews   Author: holoviz   File: image.py    License: 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 15
Project: pyem   Author: asarnow   File: mrc.py    License: 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 16
Project: pyem   Author: asarnow   File: mrc.py    License: 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 17
Project: pyfinance   Author: bsolomon1124   File: ols.py    License: 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 18
Project: xclim   Author: Ouranosinc   File: conftest.py    License: 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
Project: dcscn-super-resolution   Author: jiny2001   File: utilty.py    License: 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
Project: porespy   Author: PMEAL   File: __funcs__.py    License: 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
Project: tangent   Author: google   File: grads.py    License: Apache License 2.0 5 votes vote down vote up
def atleast_3d(y, x):
  d[x] = numpy.reshape(d[y], numpy.shape(x)) 
Example 22
Project: tangent   Author: google   File: tangents.py    License: Apache License 2.0 5 votes vote down vote up
def tatleast_3d(z, x):
  d[z] = numpy.atleast_3d(d[x]) 
Example 23
Project: MaskTrack   Author: omkar13   File: io.py    License: MIT License 5 votes vote down vote up
def imread_indexed(filename):
  """ Load image given filename."""

  im = Image.open(filename)
  annotation = np.atleast_3d(im)[...,0]
  return annotation,np.array(im.getpalette()).reshape((-1,3)) 
Example 24
Project: MaskTrack   Author: omkar13   File: io.py    License: MIT License 5 votes vote down vote up
def imwrite_indexed(filename,array,color_palette=cfg.palette):
  """ Save indexed png."""

  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 25
Project: buzzard   Author: airware   File: _numpy_raster.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, back_ds, fp, array, channels_schema, wkt, mode):
        array = np.atleast_3d(array)
        self._arr = array
        channel_count = array.shape[-1]

        if 'nodata' not in channels_schema:
            channels_schema['nodata'] = [None] * channel_count

        if 'interpretation' not in channels_schema:
            channels_schema['interpretation'] = ['undefined'] * channel_count

        if 'offset' not in channels_schema:
            channels_schema['offset'] = [0.] * channel_count

        if 'scale' not in channels_schema:
            channels_schema['scale'] = [1.] * channel_count

        if 'mask' not in channels_schema:
            channels_schema['mask'] = ['all_valid']

        super(BackNumpyRaster, self).__init__(
            back_ds=back_ds,
            wkt_stored=wkt,
            channels_schema=channels_schema,
            dtype=array.dtype,
            fp_stored=fp,
            mode=mode,
        )

        self._should_tranform = (
            any(v != 0 for v in channels_schema['offset']) or
            any(v != 1 for v in channels_schema['scale'])
        ) 
Example 26
Project: mars   Author: mars-project   File: test_base_execute.py    License: Apache License 2.0 5 votes vote down vote up
def testAtleast3dExecution(self):
        x = 1
        y = ones(3, chunk_size=2)
        z = ones((3, 4), chunk_size=2)

        t = atleast_3d(x, y, z)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in t]

        self.assertTrue(np.array_equal(res[0], np.atleast_3d(x)))
        self.assertTrue(np.array_equal(res[1], np.atleast_3d(np.ones(3))))
        self.assertTrue(np.array_equal(res[2], np.atleast_3d(np.ones((3, 4))))) 
Example 27
Project: mars   Author: mars-project   File: test_core_execute.py    License: Apache License 2.0 5 votes vote down vote up
def testViewDataOnAtleast3d(self):
        data = np.random.rand(10, 20)
        a = atleast_3d(tensor(data, chunk_size=5))
        b = a[:, :5, :10][0]
        c = add(b[:4], b[1:], out=a[0, 16:])

        npa = np.atleast_3d(data.copy())
        npb = npa[:, :5, :10][0]
        npc = np.add(npb[:4], npb[1:], out=npa[0, 16:])

        np.testing.assert_array_equal(c.execute(), npc)
        np.testing.assert_array_equal(b.execute(), npb)
        np.testing.assert_array_equal(a.execute(), npa) 
Example 28
Project: phocnet   Author: ssudholt   File: augmentation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rotate_image(image, angle):
        '''
        Rotates the given image by the given angle.
        '''
        
        rows, cols, _ = np.atleast_3d(image).shape
        rot_mat = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
        
        return cv2.warpAffine(image, rot_mat, (cols, rows)) 
Example 29
Project: phocnet   Author: ssudholt   File: augmentation.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def translate_image(image, translation):
        '''
        Translates the given image with the given translation vector.
        '''
        
        rows, cols, _ = np.atleast_3d(image).shape
        trans_mat = np.array([[1, 0, translation[0]*cols], [0, 1, translation[1]*rows]])
        
        return cv2.warpAffine(image, trans_mat, (cols, rows)) 
Example 30
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: image.py    License: MIT License 5 votes vote down vote up
def img_to_graph(img, mask=None, return_as=sparse.coo_matrix, dtype=None):
    """Graph of the pixel-to-pixel gradient connections

    Edges are weighted with the gradient values.

    Read more in the :ref:`User Guide <image_feature_extraction>`.

    Parameters
    ----------
    img : ndarray, 2D or 3D
        2D or 3D image
    mask : ndarray of booleans, optional
        An optional mask of the image, to consider only part of the
        pixels.
    return_as : np.ndarray or a sparse matrix class, optional
        The class to use to build the returned adjacency matrix.
    dtype : None or dtype, optional
        The data of the returned sparse matrix. By default it is the
        dtype of img

    Notes
    -----
    For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
    handled by returning a dense np.matrix instance.  Going forward, np.ndarray
    returns an np.ndarray, as expected.

    For compatibility, user code relying on this method should wrap its
    calls in ``np.asarray`` to avoid type issues.
    """
    img = np.atleast_3d(img)
    n_x, n_y, n_z = img.shape
    return _to_graph(n_x, n_y, n_z, mask, img, return_as, dtype)