Beispiel #1
0
def resize_flow(flow, shape):
    """Rescale the values of the vector field (u, v) to the desired shape.

    The values of the output vector field are scaled to the new
    resolution.

    Parameters
    ----------
    flow : ndarray
        The motion field to be processed.
    shape : iterable
        Couple of integers representing the output shape.

    Returns
    -------
    rflow : ndarray
        The resized and rescaled motion field.

    """

    scale = [n / o for n, o in zip(shape, flow.shape[1:])]
    scale_factor = cp.asarray(scale, dtype=flow.dtype)

    for _ in shape:
        scale_factor = scale_factor[..., cp.newaxis]

    rflow = scale_factor * ndi.zoom(flow, [1] + scale, order=0,
                                    mode='nearest', prefilter=False)

    return rflow
Beispiel #2
0
def preview_datastore(stream, method, size):
    # lookup size
    size = {
        "4K": (2160, 3840),
        "QHD": (1440, 2560),
        "FHD": (1080, 1920),
        "HD": (720, 1280),
    }[size]

    if method == "zstack":
        for data in stream:
            data = cp.asarray(data)

            factor = shape_to_zoom_factor(data.shape, size)
            data = zoom(data, factor, order=1, output=data.dtype)

            data = data.astype(cp.uint16)
            data = auto_contrast(data)
            data = (data - data.min()) / (data.max() - data.min()) * 255
            data = data.astype(cp.uint8)

            # frame
            yield data

    elif method == "mip":
        result = None
        for data in stream:
            data = cp.asarray(data)
            try:
                np.maximum(result, data, out=result)
            except TypeError:
                result = data.copy()
        yield result
Beispiel #3
0
def mark_boundaries(image, label_img, color=(1, 1, 0),
                    outline_color=None, mode='outer', background_label=0,
                    *, order=3):
    """Return image with boundaries between labeled regions highlighted.

    Parameters
    ----------
    image : (M, N[, 3]) array
        Grayscale or RGB image.
    label_img : (M, N) array of int
        Label array where regions are marked by different integer values.
    color : length-3 sequence, optional
        RGB color of boundaries in the output image.
    outline_color : length-3 sequence, optional
        RGB color surrounding boundaries in the output image. If None, no
        outline is drawn.
    mode : string in {'thick', 'inner', 'outer', 'subpixel'}, optional
        The mode for finding boundaries.
    background_label : int, optional
        Which label to consider background (this is only useful for
        modes ``inner`` and ``outer``).

    Additional Parameters
    ---------------------
    order : int
       The spline interpolation order to use when ``mode="subpixel"``.
       Unused by other modes.

    Returns
    -------
    marked : (M, N, 3) array of float
        An image in which the boundaries between labels are
        superimposed on the original image.

    See Also
    --------
    find_boundaries
    """
    marked = img_as_float(image, force_copy=True)
    if marked.ndim == 2:
        marked = gray2rgb(marked)
    if mode == 'subpixel':
        # Here, we want to interpose an extra line of pixels between
        # each original line - except for the last axis which holds
        # the RGB information. ``ndi.zoom`` then performs the (cubic)
        # interpolation, filling in the values of the interposed pixels
        marked = ndi.zoom(marked, [2 - 1 / s for s in marked.shape[:-1]] + [1],
                          mode='mirror', order=order)
    boundaries = find_boundaries(label_img, mode=mode,
                                 background=background_label)
    if outline_color is not None:
        outlines = dilation(boundaries, square(3))
        marked[outlines] = outline_color
    marked[boundaries] = color
    return marked
Beispiel #4
0
def Data_anchor_sample(image, face_boxes, face_keys=None):
    # 增加小人脸的比例
    maxSize = 12000
    infDistance = 9999999

    height, width, _ = image.shape
    random_counter = 0
    box_area = face_boxes[:, 2] * face_boxes[:, 3]
    rand_idx = random.randint(0, len(box_area) - 1)  # 随机选择一个人脸
    rand_Side = box_area[rand_idx]**0.5  # 等效正方形边长

    if rand_Side <= 0:  # 有的人脸大小被标记为0,可以跳过这些数据
        return image, face_boxes, face_keys

    anchors = [16, 32, 48, 64, 96, 128, 256, 512]
    distance = infDistance
    anchor_idx = 5
    for i, anchor in enumerate(anchors):
        if abs(anchor - rand_Side) < distance:
            distance = abs(anchor - rand_Side)  # 选择最接近的anchors
            anchor_idx = i

    target_anchor = random.choice(anchors[0:min(anchor_idx +
                                                1, 5)])  # 随机选择一个相对较小的anchor,向下
    ratio = float(target_anchor) / rand_Side  # 缩放的尺度
    ratio = ratio * (2**random.uniform(-1, 1))  # [ratio/2, 2ratio]的均匀分布

    if height * ratio * width * ratio > maxSize * maxSize:
        ratio = (maxSize * maxSize / (height * width))**0.5

    image = ndimage.zoom(image,
                         zoom=(ratio, ratio, 1.0),
                         order=1,
                         mode='opencv')

    face_boxes = face_boxes * ratio
    if face_keys is not None:
        face_keys[:, :, 0:2] *= ratio
    return image, face_boxes, face_keys
Beispiel #5
0
def resize(image,
           output_shape,
           order=None,
           mode='reflect',
           cval=0,
           clip=True,
           preserve_range=False,
           anti_aliasing=None,
           anti_aliasing_sigma=None):
    """Resize image to match a certain size.

    Performs interpolation to up-size or down-size N-dimensional images. Note
    that anti-aliasing should be enabled when down-sizing images to avoid
    aliasing artifacts. For down-sampling with an integer factor also see
    `skimage.transform.downscale_local_mean`.

    Parameters
    ----------
    image : ndarray
        Input image.
    output_shape : tuple or ndarray
        Size of the generated output image `(rows, cols[, ...][, dim])`. If
        `dim` is not provided, the number of channels is preserved. In case the
        number of input channels does not equal the number of output channels a
        n-dimensional interpolation is applied.

    Returns
    -------
    resized : ndarray
        Resized version of the input.

    Other parameters
    ----------------
    order : int, optional
        The order of the spline interpolation, default is 0 if
        image.dtype is bool and 1 otherwise. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
    anti_aliasing : bool, optional
        Whether to apply a Gaussian filter to smooth the image prior
        to down-scaling. It is crucial to filter when down-sampling
        the image to avoid aliasing artifacts. If input image data
        type is bool, no anti-aliasing is applied.
    anti_aliasing_sigma : {float, tuple of floats}, optional
        Standard deviation for Gaussian filtering to avoid aliasing artifacts.
        By default, this value is chosen as (s - 1) / 2 where s is the
        down-scaling factor, where s > 1. For the up-size case, s < 1, no
        anti-aliasing is performed prior to rescaling.

    Notes
    -----
    Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
    pixels are duplicated during the reflection.  As an example, if an array
    has values [0, 1, 2] and was padded to the right by four values using
    symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
    would be [0, 1, 2, 1, 0, 1, 2].

    Examples
    --------
    >>> from skimage import data
    >>> from cucim.skimage.transform import resize
    >>> image = cp.array(data.camera())
    >>> resize(image, (100, 100)).shape
    (100, 100)

    """
    output_shape = tuple(output_shape)
    output_ndim = len(output_shape)
    input_shape = image.shape
    if output_ndim > image.ndim:
        # append dimensions to input_shape
        input_shape = input_shape + (1, ) * (output_ndim - image.ndim)
        image = cp.reshape(image, input_shape)
    elif output_ndim == image.ndim - 1:
        # multichannel case: append shape of last axis
        output_shape = output_shape + (image.shape[-1], )
    elif output_ndim < image.ndim - 1:
        raise ValueError("len(output_shape) cannot be smaller than the image "
                         "dimensions")

    if anti_aliasing is None:
        anti_aliasing = not image.dtype == bool

    if image.dtype == bool and anti_aliasing:
        warn(
            "Input image dtype is bool. Gaussian convolution is not defined "
            "with bool data type. Please set anti_aliasing to False or "
            "explicitely cast input image to another data type. Starting "
            "from version 0.19 a ValueError will be raised instead of this "
            "warning.",
            FutureWarning,
            stacklevel=2)

    factors = tuple(si / so for si, so in zip(input_shape, output_shape))

    if anti_aliasing and any(f > 1 for f in factors):
        if anti_aliasing_sigma is None:
            anti_aliasing_sigma = tuple([max(0, (f - 1) / 2) for f in factors])
        else:
            if np.isscalar(anti_aliasing_sigma):
                anti_aliasing_sigma = (anti_aliasing_sigma, ) * len(factors)
            elif len(anti_aliasing_sigma) != len(factors):
                raise ValueError("invalid anti_aliasing_sigma length")
            if any(sigma < 0 for sigma in anti_aliasing_sigma):
                raise ValueError("Anti-aliasing standard deviation must be "
                                 "greater than or equal to zero")
            elif any(((sigma > 0) & (factor <= 1))
                     for factor, sigma in zip(factors, anti_aliasing_sigma)):
                warn("Anti-aliasing standard deviation greater than zero but "
                     "not down-sampling along all axes")

        # Translate modes used by np.pad to those used by ndi.gaussian_filter
        np_pad_to_ndimage = {
            'constant': 'constant',
            'edge': 'nearest',
            'symmetric': 'reflect',
            'reflect': 'mirror',
            'wrap': 'wrap'
        }
        try:
            ndi_mode = np_pad_to_ndimage[mode]
        except KeyError:
            raise ValueError("Unknown mode, or cannot translate mode. The "
                             "mode should be one of 'constant', 'edge', "
                             "'symmetric', 'reflect', or 'wrap'. See the "
                             "documentation of numpy.pad for more info.")

        image = ndi.gaussian_filter(image,
                                    anti_aliasing_sigma,
                                    cval=cval,
                                    mode=ndi_mode)

    order = _validate_interpolation_order(image.dtype, order)
    ndi_mode = _to_ndimage_mode(mode)
    # TODO: move the following conversion into _to_ndimage_mode
    if ndi_mode == 'constant':
        ndi_mode = 'grid-constant'
    elif ndi_mode == 'wrap':
        ndi_mode = 'grid-wrap'
    zoom_factors = [1 / f for f in factors]
    image = convert_to_float(image, preserve_range)
    out = ndi.zoom(image,
                   zoom_factors,
                   order=order,
                   mode=ndi_mode,
                   cval=cval,
                   grid_mode=True)
    _clip_warp_output(image, out, order, mode, cval, clip)
    return out
Beispiel #6
0
def upsample(x):
    return zoom(x, (float(UPSAMPLE_X), float(UPSAMPLE_Y), 1), order=1)
Beispiel #7
0
def dataAugmentation(sample):

    rotation = random.randint(0, 23)

    if rotation == 1:
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 2:
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 3:
        sample = cp.rot90(sample, 1, (2, 1))
    elif rotation == 4:
        sample = cp.rot90(sample, 1, (0, 1))
    elif rotation == 5:
        sample = cp.rot90(sample, 1, (0, 1))
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 6:
        sample = cp.rot90(sample, 1, (0, 1))
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 7:
        sample = cp.rot90(sample, 1, (0, 1))
        sample = cp.rot90(sample, 1, (2, 1))
    elif rotation == 8:
        sample = cp.rot90(sample, 1, (1, 0))
    elif rotation == 9:
        sample = cp.rot90(sample, 1, (1, 0))
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 10:
        sample = cp.rot90(sample, 1, (1, 0))
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 11:
        sample = cp.rot90(sample, 1, (1, 0))
        sample = cp.rot90(sample, 1, (2, 1))
    elif rotation == 12:
        sample = cp.rot90(sample, 2, (1, 0))
    elif rotation == 13:
        sample = cp.rot90(sample, 2, (1, 0))
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 14:
        sample = cp.rot90(sample, 2, (1, 0))
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 15:
        sample = cp.rot90(sample, 2, (1, 0))
        sample = cp.rot90(sample, 1, (2, 1))
    elif rotation == 16:
        sample = cp.rot90(sample, 1, (0, 2))
    elif rotation == 17:
        sample = cp.rot90(sample, 1, (0, 2))
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 18:
        sample = cp.rot90(sample, 1, (0, 2))
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 19:
        sample = cp.rot90(sample, 1, (0, 2))
        sample = cp.rot90(sample, 1, (2, 1))
    elif rotation == 20:
        sample = cp.rot90(sample, 1, (2, 0))
    elif rotation == 21:
        sample = cp.rot90(sample, 1, (2, 0))
        sample = cp.rot90(sample, 1, (1, 2))
    elif rotation == 22:
        sample = cp.rot90(sample, 1, (2, 0))
        sample = cp.rot90(sample, 2, (1, 2))
    elif rotation == 23:
        sample = cp.rot90(sample, 1, (2, 0))
        sample = cp.rot90(sample, 1, (2, 1))

    resolution = int(sample.shape[0])

    strategy = random.randint(0, 9)

    if strategy == 0:
        factor = random.uniform(1.0625, 1.25)
        sample = ndimage.zoom(sample, factor, order=0)
        startx = random.randint(0, sample.shape[0] - resolution)
        starty = random.randint(0, sample.shape[1] - resolution)
        startz = random.randint(0, sample.shape[2] - resolution)
        sample = sample[startx:startx + resolution, starty:starty + resolution,
                        startz:startz + resolution]
    elif strategy == 1:
        factor = random.uniform(0.9375, 0.75)
        sample = ndimage.zoom(sample, factor, order=0)
        padxwl = random.randint(0, resolution - sample.shape[0])
        padxwr = resolution - padxwl - sample.shape[0]
        padywl = random.randint(0, resolution - sample.shape[1])
        padywr = resolution - padywl - sample.shape[1]
        padzwl = random.randint(0, resolution - sample.shape[2])
        padzwr = resolution - padzwl - sample.shape[2]
        sample = np.pad(sample,
                        ((padxwl, padxwr), (padywl, padywr), (padzwl, padzwr)),
                        mode='edge')
    elif strategy == 2:
        padr = int(resolution / 8)
        loc = 2 * padr
        startx = random.randint(0, loc)
        starty = padr
        startz = padr
        sample = np.pad(sample, ((padr, padr), (padr, padr), (padr, padr)),
                        mode='edge')
        sample = sample[startx:startx + resolution, starty:starty + resolution,
                        startz:startz + resolution]
    elif strategy == 3:
        padr = int(resolution / 8)
        loc = 2 * padr
        startx = padr
        starty = random.randint(0, loc)
        startz = padr
        sample = np.pad(sample, ((padr, padr), (padr, padr), (padr, padr)),
                        mode='edge')
        sample = sample[startx:startx + resolution, starty:starty + resolution,
                        startz:startz + resolution]
    elif strategy == 4:
        padr = int(resolution / 8)
        loc = 2 * padr
        startx = padr
        starty = padr
        startz = random.randint(0, loc)
        sample = np.pad(sample, ((padr, padr), (padr, padr), (padr, padr)),
                        mode='edge')
        sample = sample[startx:startx + resolution, starty:starty + resolution,
                        startz:startz + resolution]

    return sample