How to use the scipy.ndimage function in scipy

To help you get started, we’ve selected a few scipy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Zulko / moviepy / moviepy / video / tools / segmenting.py View on Github external
the screen.
        
    rem_thr : all objects found with size < rem_Thr will be
         considered false positives and will be removed
    
    """
    
    image = clip.get_frame(0)
    if clip.mask is None:
        clip = clip.add_mask()
        
    mask = clip.mask.get_frame(0)
    labelled, num_features = ndi.measurements.label(image[:,:,0])
    
    #find the objects
    slices = ndi.find_objects(labelled)
    # cool trick to remove letter holes (in o,e,a, etc.)
    slices = [e for e in slices if  mask[e[0],e[1]].mean() >0.2]
    # remove very small slices
    slices = [e for e in slices if  image[e[0],e[1]].size > rem_thr]
    # Sort the slices from left to right
    islices = sorted(enumerate(slices), key = lambda s : s[1][1].start)
    
    letters = []
    for i,(ind,(sy,sx)) in enumerate(islices):
        """ crop each letter separately """
        sy = slice(sy.start-1,sy.stop+1)
        sx = slice(sx.start-1,sx.stop+1)
        letter = image[sy,sx]
        labletter = labelled[sy,sx]
        maskletter = (labletter==(ind+1))*mask[sy,sx]
        letter = ImageClip(image[sy,sx])
github SimLeek / pySILEnT / slam_recognition / zoom_tensor / from_image.py View on Github external
for d in center_dimensions:
        assert d > 0, "Each dimension must be larger than zero."

    image_dimensions = image.shape[:-1]  # take out colors from n-dimensional image
    center_dimensions = list(reversed(center_dimensions))  # because OpenCV likes doing things backwards
    num_scales = int(
        m.ceil(max([m.log(x_i / x_c, scale) for x_i, x_c in zip(image_dimensions, center_dimensions)])))
    pyramid_tensor = np.empty([num_scales] + center_dimensions + [num_colors])
    for s in range(num_scales):
        slice_dimensions = [c * (scale ** s) for c in center_dimensions]
        image_slicers = [slice(int(max((i - c) / 2, 0)), int((i + c) / 2)) for i, c in
                         zip(image_dimensions, slice_dimensions)]
        image_slice = image[image_slicers]
        scaled_image_slice = np.empty(center_dimensions + [num_colors])
        for c in range(num_colors):
            zoomed_image = ndimage.zoom(np.squeeze(image_slice[[slice(None)] * len(image_dimensions) + [slice(c, c + 1)]]),
                             1.0 / (scale ** s), prefilter=False, order=5)[
                    [slice(None)] * len(center_dimensions) + [np.newaxis]]
            x_max = min(scaled_image_slice.shape[0], zoomed_image.shape[0])
            y_max = min(scaled_image_slice.shape[1], zoomed_image.shape[1])
            scaled_image_slice[[slice(None)] * len(center_dimensions) + [slice(c, c + 1)]][0:x_max, 0:y_max] = zoomed_image[0:x_max, 0:y_max]

        pyramid_tensor_slicers = [slice(None) for _ in image_dimensions] + [slice(None)]
        pyramid_tensor[[slice(s, s + 1)] + pyramid_tensor_slicers] = scaled_image_slice[[np.newaxis] +
                                                                                        pyramid_tensor_slicers]
    return pyramid_tensor
github rflamary / POT / examples / da / plot_otda_mapping_colors_images.py View on Github external
def mat2im(X, shape):
    """Converts back a matrix to an image"""
    return X.reshape(shape)


def minmax(I):
    return np.clip(I, 0, 1)


##############################################################################
# Generate data
##############################################################################

# Loading images
I1 = ndimage.imread('../../data/ocean_day.jpg').astype(np.float64) / 256
I2 = ndimage.imread('../../data/ocean_sunset.jpg').astype(np.float64) / 256


X1 = im2mat(I1)
X2 = im2mat(I2)

# training samples
nb = 1000
idx1 = np.random.randint(X1.shape[0], size=(nb,))
idx2 = np.random.randint(X2.shape[0], size=(nb,))

Xs = X1[idx1, :]
Xt = X2[idx2, :]


##############################################################################
github pyimreg / python-register / imreg / features / detector.py View on Github external
avgRows = haarData.shape[0] / 2 ** levels
    avgCols = haarData.shape[1] / 2 ** levels
    
    SalientPoints = {}
    
    siloH = np.zeros([haarData.shape[0]/2, haarData.shape[1]/2, levels])
    siloD = np.zeros([haarData.shape[0]/2, haarData.shape[1]/2, levels])
    siloV = np.zeros([haarData.shape[0]/2, haarData.shape[1]/2, levels])
    
    # Build the saliency silos
    for i in range(levels):
        level = i + 1
        halfRows = haarData.shape[0] / 2 ** level
        halfCols = haarData.shape[1] / 2 ** level
        siloH[:,:,i] = nd.zoom(haarData[:halfRows, halfCols:halfCols*2], 2**(level-1)) 
        siloD[:,:,i] = nd.zoom(haarData[halfRows:halfRows*2, halfCols:halfCols*2], 2**(level-1)) 
        siloV[:,:,i] = nd.zoom(haarData[halfRows:halfRows*2, :halfCols], 2**(level-1)) 
    
    # Calculate saliency heat-map
    saliencyMap = np.max(np.array([
                                np.sum(np.abs(siloH), axis=2), 
                                np.sum(np.abs(siloD), axis=2),
                                np.sum(np.abs(siloV), axis=2)
                                ]), axis=0)
                               
    # Determine global maximum and saliency threshold
    maximum = np.max(saliencyMap)
    sthreshold = threshold * maximum
    
    # Extract features by finding local maxima
    rows = haarData.shape[0] / 2
github eclipse / deeplearning4j-examples / tf-import-examples / src / main / resources / Mnist / mnist_jumpy.py View on Github external
# SPDX-License-Identifier: Apache-2.0
################################################################################

from scipy import ndimage
import jumpy as jp
import numpy as np
import os


path = os.path.dirname(os.path.abspath(__file__))

# load tensorflow model
tf_model = jp.TFModel(path + '/mnist.pb')

# load jpg to numpy array
image = ndimage.imread(path + '/img_1.jpg').reshape((1, 28, 28))

image = np.cast[float](image)

image /= 255.

# inference - uses nd4j
prediction = tf_model(image)  # prediction is a jumpy array

# get label from predction using argmax
label = jp.argmax(prediction.reshape((10,)))

print(label)
github puke3615 / SceneClassify / generator.py View on Github external
x: 2D numpy array, single image.
        transform_matrix: Numpy array specifying the geometric transformation.
        channel_axis: Index of axis for channels in the input tensor.
        fill_mode: Points outside the boundaries of the input
            are filled according to the given mode
            (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
        cval: Value used for points outside the boundaries
            of the input if `mode='constant'`.

    # Returns
        The transformed version of the input.
    """
    x = np.rollaxis(x, channel_axis, 0)
    final_affine_matrix = transform_matrix[:2, :2]
    final_offset = transform_matrix[:2, 2]
    channel_images = [ndi.interpolation.affine_transform(
        x_channel,
        final_affine_matrix,
        final_offset,
        order=0,
        mode=fill_mode,
        cval=cval) for x_channel in x]
    x = np.stack(channel_images, axis=0)
    x = np.rollaxis(x, 0, channel_axis + 1)
    return x
github PMEAL / OpenPNM / OpenPNM / Geometry / models / pore_seed.py View on Github external
network = geometry._net
    # The following will only work on Cubic networks
    x = network._shape[0]
    y = network._shape[1]
    z = network._shape[2]
    im = _sp.rand(x, y, z)
    if strel is None:  # Then generate a strel
        if sum(weights) == 0:
            # If weights of 0 are sent, then skip everything and return rands.
            return im.flatten()
        w = _sp.array(weights)
        strel = _sp.zeros(w*2+1)
        strel[:, w[1], w[2]] = 1
        strel[w[0], :, w[2]] = 1
        strel[w[0], w[1], :] = 1
    im = spim.convolve(im, strel)
    # Convolution is no longer randomly distributed, so fit a gaussian
    # and find it's seeds
    im = (im - _sp.mean(im))/_sp.std(im)
    im = 1/2*_sp.special.erfc(-im/_sp.sqrt(2))
    values = im.flatten()
    values = values[geometry.map_pores(target=network, pores=geometry.Ps)]
    return values
github CellProfiler / CellProfiler / cellprofiler / modules / measurecolocalization.py View on Github external
"Min Correlation coeff",
                        "%.3f" % numpy.min(corr),
                    ],
                    [
                        first_image_name,
                        second_image_name,
                        object_name,
                        "Max Correlation coeff",
                        "%.3f" % numpy.max(corr),
                    ],
                ]

            if any((self.do_manders, self.do_rwc, self.do_overlap)):
                # Threshold as percentage of maximum intensity of objects in each channel
                tff = (self.thr.value / 100) * fix(
                    scipy.ndimage.maximum(first_pixels, labels, lrange)
                )
                tss = (self.thr.value / 100) * fix(
                    scipy.ndimage.maximum(second_pixels, labels, lrange)
                )

                combined_thresh = (first_pixels >= tff[labels - 1]) & (
                    second_pixels >= tss[labels - 1]
                )
                fi_thresh = first_pixels[combined_thresh]
                si_thresh = second_pixels[combined_thresh]
                tot_fi_thr = scipy.ndimage.sum(
                    first_pixels[first_pixels >= tff[labels - 1]],
                    labels[first_pixels >= tff[labels - 1]],
                    lrange,
                )
                tot_si_thr = scipy.ndimage.sum(
github ejeschke / ginga / ginga / util / iqcalc.py View on Github external
def centroid(self, data, xc, yc, radius):
        if not have_scipy:
            raise IQCalcError("Please install the 'scipy' module "
                              "to use this function")
        xc, yc = int(xc), int(yc)
        x0, y0, arr = self.cut_region(xc, yc, int(radius), data)
        # See https://stackoverflow.com/questions/25369982/center-of-mass-for-roi-in-python
        cp_arr = np.asarray(arr)
        cy, cx = ndimage.center_of_mass(cp_arr)
        return (x0 + cx, y0 + cy)
github flatironinstitute / CaImAn / caiman / source_extraction / cnmf / initialization.py View on Github external
def ICA_PCA(Y_ds, nr, sigma_smooth=(.5, .5, .5), truncate=2, fun='logcosh',
            max_iter=1000, tol=1e-10, remove_baseline=True, perc_baseline=20, nb=1):
    """ Initialization using ICA and PCA. DOES NOT WORK WELL WORK IN PROGRESS"

    Parameters:
    -----------

    Returns:
    --------


    """
    print("not a function to use in the moment ICA PCA \n")
    m = scipy.ndimage.gaussian_filter(np.transpose(
        Y_ds, [2, 0, 1]), sigma=sigma_smooth, mode='nearest', truncate=truncate)
    if remove_baseline:
        bl = np.percentile(m, perc_baseline, axis=0)
        m1 = np.maximum(0, m - bl)
    else:
        bl = np.zeros(m.shape[1:])
        m1 = m
    pca_comp = nr

    T, d1, d2 = np.shape(m1)
    d = d1 * d2
    yr = np.reshape(m1, [T, d], order='F')

    [U, S, V] = scipy.sparse.linalg.svds(yr, pca_comp)
    S = np.diag(S)
    whiteningMatrix = np.dot(scipy.linalg.inv(S), U.T)