Python numpy.dsplit() Examples

The following are 14 code examples of numpy.dsplit(). 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: process_semantic_masks.py    From segmentation with Apache License 2.0 6 votes vote down vote up
def preprocess(self, image_path: Path) -> None:
        """Process single mask.

        Args:
            image_path (Path): path to the mask
        """
        image = imread(image_path, rootpath=str(self.in_dir))
        heigth, width = image.shape[:2]

        mask = np.zeros((heigth, width, len(self.index2color)), dtype=np.uint8)
        for index, color in self.index2color.items():
            mask[np.all((image == color), axis=-1), index] = 255

        target_path = self.out_dir / f"{image_path.stem}.tiff"
        target_path.parent.mkdir(parents=True, exist_ok=True)

        mimwrite_with_meta(
            target_path, np.dsplit(mask, mask.shape[2]), {"compress": 9}
        ) 
Example #2
Source File: color.py    From snowy with MIT License 5 votes vote down vote up
def rgb_to_luminance(image: np.ndarray):
    "Read the first three color planes and return a grayscale image."
    assert image.shape[2] >= 3
    r, g, b = np.dsplit(image[:,:,:3], image.shape[2])
    return io.reshape(0.2125 * r + 0.7154 * g + 0.0721 * b) 
Example #3
Source File: io.py    From snowy with MIT License 5 votes vote down vote up
def extract_alpha(image: np.ndarray) -> np.ndarray:
    """Extract the alpha plane from an RGBA image.
    
    Note that this returns a copy, not a view. To manipulate the pixels
    in a <i>view</i> of the alpha plane, simply make a numpy slice, as
    in: <code>alpha_view = myimage[:,:,3]</code>.
    """
    assert len(image.shape) == 3 and image.shape[2] == 4
    return np.dsplit(image, 4)[3].copy() 
Example #4
Source File: io.py    From snowy with MIT License 5 votes vote down vote up
def extract_rgb(image: np.ndarray) -> np.ndarray:
    """Extract the RGB planes from an RGBA image.
    
    Note that this returns a copy. If you wish to obtain a view that
    allows mutating pixels, simply use slicing instead. For
    example, to invert the colors of an image while leaving alpha
    intact, you can do:
    <code>myimage[:,:,:3] = 1.0 - myimage[:,:,:3]</code>.
    """
    assert len(image.shape) == 3 and image.shape[2] >= 3
    planes = np.dsplit(image, image.shape[2])
    return np.dstack(planes[:3]) 
Example #5
Source File: io.py    From snowy with MIT License 5 votes vote down vote up
def to_planar(image: np.ndarray) -> np.ndarray:
    """Convert a row-major image into a channel-major image.
    
    This creates a copy, not a view.
    """
    assert len(image.shape) == 3
    result = np.array(np.dsplit(image, image.shape[2]))
    return np.reshape(result, result.shape[:-1]) 
Example #6
Source File: loader.py    From hover_net with MIT License 5 votes vote down vote up
def visualize(datagen, batch_size, view_size=4):
    """
    Read the batch from 'datagen' and display 'view_size' number of
    of images and their corresponding Ground Truth
    """
    def prep_imgs(img, ann):
        cmap = plt.get_cmap('viridis')
        # cmap may randomly fails if of other types
        ann = ann.astype('float32')
        ann_chs = np.dsplit(ann, ann.shape[-1])
        for i, ch in enumerate(ann_chs):
            ch = np.squeeze(ch)
            # normalize to -1 to 1 range else
            # cmap may behave stupidly
            ch = ch / (np.max(ch) - np.min(ch) + 1.0e-16)
            # take RGB from RGBA heat map
            ann_chs[i] = cmap(ch)[...,:3]
        img = img.astype('float32') / 255.0
        prepped_img = np.concatenate([img] + ann_chs, axis=1)
        return prepped_img

    assert view_size <= batch_size, 'Number of displayed images must <= batch size'
    ds = RepeatedData(datagen, -1)    
    ds.reset_state()
    for imgs, segs in ds.get_data():
        for idx in range (0, view_size):
            displayed_img = prep_imgs(imgs[idx], segs[idx])
            plt.subplot(view_size, 1, idx+1)
            plt.imshow(displayed_img)
        plt.show()
    return
###

########################################################################### 
Example #7
Source File: split.py    From cupy with MIT License 5 votes vote down vote up
def dsplit(ary, indices_or_sections):
    """Splits an array into multiple sub arrays along the third axis.

    This is equivalent to ``split`` with ``axis=2``.

    .. seealso:: :func:`cupy.split` for more detail, :func:`numpy.dsplit`

    """
    if ary.ndim <= 2:
        raise ValueError('Cannot dsplit an array with less than 3 dimensions')
    return split(ary, indices_or_sections, 2) 
Example #8
Source File: split.py    From cupy with MIT License 5 votes vote down vote up
def vsplit(ary, indices_or_sections):
    """Splits an array into multiple sub arrays along the first axis.

    This is equivalent to ``split`` with ``axis=0``.

    .. seealso:: :func:`cupy.split` for more detail, :func:`numpy.dsplit`

    """
    if ary.ndim <= 1:
        raise ValueError('Cannot vsplit an array with less than 2 dimensions')
    return split(ary, indices_or_sections, 0) 
Example #9
Source File: gif2numpy.py    From giftolottie with MIT License 5 votes vote down vote up
def cvtColor(image):
    "converts color from BGR to RGB and BGRA to RGBA and vice versa"
    if len(image.shape)>=3:
        np8_image = image.astype(np.uint8)
        if image.shape[2] == 3:
            b, g, r = np.dsplit(np8_image, np8_image.shape[-1])
            return np.dstack([r, g, b])
        elif image.shape[2] == 4:
            b, g, r, a = np.dsplit(np8_image, np8_image.shape[-1])
            return np.dstack([r, g, b, a])
    return image

#================================================================
# LZW compression algorithms
#================================================================ 
Example #10
Source File: util.py    From gbdxtools with MIT License 5 votes vote down vote up
def _rpc(self, x):
        L, P, H = np.dsplit(x, 3)
        return np.dstack([np.ones((x.shape[0], x.shape[1]), dtype=np.float32), L, P, H, L*P, L*H, P*H, L**2, P**2, H**2,
                           L*P*H, L**3, L*(P**2), L*(H**2), (L**2)*P, P**3, P*(H**2),
                           (L**2)*H, (P**2)*H, H**3]) 
Example #11
Source File: synthgen.py    From SynthText with Apache License 2.0 5 votes vote down vote up
def char2wordBB(self, charBB, text):
        """
        Converts character bounding-boxes to word-level
        bounding-boxes.

        charBB : 2x4xn matrix of BB coordinates
        text   : the text string

        output : 2x4xm matrix of BB coordinates,
                 where, m == number of words.
        """
        wrds = text.split()
        bb_idx = np.r_[0, np.cumsum([len(w) for w in wrds])]
        wordBB = np.zeros((2,4,len(wrds)), 'float32')
        
        for i in xrange(len(wrds)):
            cc = charBB[:,:,bb_idx[i]:bb_idx[i+1]]

            # fit a rotated-rectangle:
            # change shape from 2x4xn_i -> (4*n_i)x2
            cc = np.squeeze(np.concatenate(np.dsplit(cc,cc.shape[-1]),axis=1)).T.astype('float32')
            rect = cv2.minAreaRect(cc.copy())
            box = np.array(cv2.cv.BoxPoints(rect))

            # find the permutation of box-coordinates which
            # are "aligned" appropriately with the character-bb.
            # (exhaustive search over all possible assignments):
            cc_tblr = np.c_[cc[0,:],
                            cc[-3,:],
                            cc[-2,:],
                            cc[3,:]].T
            perm4 = np.array(list(itertools.permutations(np.arange(4))))
            dists = []
            for pidx in xrange(perm4.shape[0]):
                d = np.sum(np.linalg.norm(box[perm4[pidx],:]-cc_tblr,axis=1))
                dists.append(d)
            wordBB[:,:,i] = box[perm4[np.argmin(dists)],:].T

        return wordBB 
Example #12
Source File: primesense_sensor.py    From perception with Apache License 2.0 5 votes vote down vote up
def _ros_read_images(self, stream_buffer, number, staleness_limit = 10.):
        """ Reads images from a stream buffer
        
        Parameters
        ----------
        stream_buffer : string
            absolute path to the image buffer service
        number : int
            The number of frames to get. Must be less than the image buffer service's
            current buffer size
        staleness_limit : float, optional
            Max value of how many seconds old the oldest image is. If the oldest image
            grabbed is older than this value, a RuntimeError is thrown.
            
            If None, staleness is ignored.
        Returns
        -------
        List of nump.ndarray objects, each one an image
        Images are in reverse chronological order (newest first)
        """
        
        rospy.wait_for_service(stream_buffer, timeout = self.timeout)
        ros_image_buffer = rospy.ServiceProxy(stream_buffer, ImageBuffer)
        ret = ros_image_buffer(number, 1)
        if not staleness_limit == None:
            if ret.timestamps[-1] > staleness_limit:
                raise RuntimeError("Got data {0} seconds old, more than allowed {1} seconds"
                                   .format(ret.timestamps[-1], staleness_limit))
            
        data = ret.data.reshape(ret.data_dim1, ret.data_dim2, ret.data_dim3).astype(ret.dtype)
        
        # Special handling for 1 element, since dstack's behavior is different
        if number == 1:
            return [data]
        return np.dsplit(data, number) 
Example #13
Source File: test_quantity_non_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dsplit(self):
        self.check(np.dsplit, [1]) 
Example #14
Source File: test_base_execute.py    From mars with Apache License 2.0 4 votes vote down vote up
def testSplitExecution(self):
        x = arange(48, chunk_size=3).reshape(2, 3, 8)
        ss = split(x, 4, axis=2)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.split(np.arange(48).reshape(2, 3, 8), 4, axis=2)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r, e) for r, e in zip(res, expected)]

        ss = split(x, [3, 5, 6, 10], axis=2)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.split(np.arange(48).reshape(2, 3, 8), [3, 5, 6, 10], axis=2)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r, e) for r, e in zip(res, expected)]

        # hsplit
        x = arange(120, chunk_size=3).reshape(2, 12, 5)
        ss = hsplit(x, 4)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.hsplit(np.arange(120).reshape(2, 12, 5), 4)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r, e) for r, e in zip(res, expected)]

        # vsplit
        x = arange(48, chunk_size=3).reshape(8, 3, 2)
        ss = vsplit(x, 4)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.vsplit(np.arange(48).reshape(8, 3, 2), 4)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r, e) for r, e in zip(res, expected)]

        # dsplit
        x = arange(48, chunk_size=3).reshape(2, 3, 8)
        ss = dsplit(x, 4)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.dsplit(np.arange(48).reshape(2, 3, 8), 4)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r, e) for r, e in zip(res, expected)]

        x_data = sps.random(12, 8, density=.1)
        x = tensor(x_data, chunk_size=3)
        ss = split(x, 4, axis=0)

        res = [self.executor.execute_tensor(i, concat=True)[0] for i in ss]
        expected = np.split(x_data.toarray(), 4, axis=0)
        self.assertEqual(len(res), len(expected))
        [np.testing.assert_equal(r.toarray(), e) for r, e in zip(res, expected)]