Python scipy.signal.convolve2d() Examples

The following are 30 code examples of scipy.signal.convolve2d(). 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 scipy.signal , or try the search function .
Example #1
Source File: test_signaltools.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_fillvalue_deprecations(self):
        # Deprecated 2017-07, scipy version 1.0.0
        with suppress_warnings() as sup:
            sup.filter(np.ComplexWarning, "Casting complex values to real")
            r = sup.record(DeprecationWarning, "could not cast `fillvalue`")
            convolve2d([[1]], [[1, 2]], fillvalue=1j)
            assert_(len(r) == 1)
            warnings.filterwarnings(
                "error", message="could not cast `fillvalue`",
                category=DeprecationWarning)
            assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
                          fillvalue=1j)

        with suppress_warnings():
            warnings.filterwarnings(
                "always", message="`fillvalue` must be scalar or an array ",
                category=DeprecationWarning)
            assert_warns(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
                         fillvalue=[1, 2])
            warnings.filterwarnings(
                "error", message="`fillvalue` must be scalar or an array ",
                category=DeprecationWarning)
            assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]],
                          fillvalue=[1, 2]) 
Example #2
Source File: test_base.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_marginal_convolution():
    rng = np.random.RandomState(42)
    convolution_filters = rng.randn(6, 4, 5).astype(np.float32)
    images = np.arange(
        3 * 2 * 10 * 10).reshape(3, 2, 10, 10).astype(np.float32)

    for border_mode in ['full', 'valid']:
        conv = MarginalConvolution(convolution_filters,
                                   border_mode=border_mode,
                                   activation=None)
        conv_func = theano.function([conv.input_],
                                    conv.expression_)
        convolved = conv_func(images)
        convolutions = np.array([
                [[convolve2d(img, convolution_filter,
                             mode=border_mode)
                  for convolution_filter in convolution_filters]
                 for img in imgs]
                for imgs in images])
        convolutions = convolutions.reshape(images.shape[0], -1,
                                            convolutions.shape[-2],
                                            convolutions.shape[-1])
        assert_array_almost_equal(convolved, convolutions, decimal=3) 
Example #3
Source File: dsift.py    From Lyssandra with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def extract_sift_patches(self, image, grid_h, grid_w):
        """extracts the sift descriptor of patches
           in positions (grid_h, grid_w) in the image"""
        h, w = image.shape
        n_patches = grid_h.size
        feat_arr = np.zeros((n_patches, n_samples * n_angles))

        # calculate gradient
        gh, gw = gen_dgauss(self.sigma)
        ih = signal.convolve2d(image, gh, mode='same')
        iw = signal.convolve2d(image, gw, mode='same')
        i_mag = np.sqrt(ih ** 2 + iw ** 2)
        i_theta = np.arctan2(ih, iw)
        i_orient = np.zeros((n_angles, h, w))
        for i in range(n_angles):
            i_orient[i] = i_mag * np.maximum(np.cos(i_theta - angles[i]) ** alpha, 0)
        for i in range(n_patches):
            curr_feature = np.zeros((n_angles, n_samples))
            for j in range(n_angles):
                curr_feature[j] = np.dot(self.weights, i_orient[j, grid_h[i]:grid_h[i] + self.ps,
                                                      grid_w[i]:grid_w[i] + self.ps].flatten())
            feat_arr[i] = curr_feature.flatten()
        # feaArr contains each descriptor in a row
        feat_arr = self.normalize_sift(feat_arr)
        return feat_arr 
Example #4
Source File: make_diffraction_test_data.py    From pyxem with GNU General Public License v3.0 6 votes vote down vote up
def get_diffraction_test_image(self, dtype=np.float32):
        image_x, image_y = self.image_x, self.image_y
        cx, cy = image_x / 2, image_y / 2
        image = np.zeros((image_y, image_x), dtype=np.float32)
        iterator = zip(self._x_list, self._y_list, self._intensity_list)
        for x, y, i in iterator:
            if self.diff_intensity_reduction is not False:
                dr = np.hypot(x - cx, y - cy)
                i = self._get_diff_intensity_reduction(dr, i)
            image[y, x] = i
        disk = morphology.disk(self.disk_r, dtype=dtype)
        image = convolve2d(image, disk, mode="same")
        if self.rotation != 0:
            image = rotate(image, self.rotation, reshape=False)
        if self.blur != 0:
            image = gaussian_filter(image, self.blur)
        if self._background_lorentz_width is not False:
            image += self._get_background_lorentz()
        if self.intensity_noise is not False:
            noise = np.random.random((image_y, image_x)) * self.intensity_noise
            image += noise
        return image 
Example #5
Source File: target_detection.py    From passiveRadar with MIT License 6 votes vote down vote up
def CFAR_2D(X, fw, gw, thresh = None):
    '''constant false alarm rate target detection
    
    Parameters:
        fw: CFAR kernel width 
        gw: number of guard cells
        thresh: detection threshold
    
    Returns:
        X with CFAR filter applied'''

    Tfilt = np.ones((fw,fw))/(fw**2 - gw**2)
    e1 = (fw - gw)//2
    e2 = fw - e1 + 1
    Tfilt[e1:e2, e1:e2] = 0

    CR = normalize(X) / (signal.convolve2d(X, Tfilt, mode='same', boundary='wrap') + 1e-10)
    if thresh is None:
        return CR
    else:
        return CR > thresh 
Example #6
Source File: array.py    From seisflows with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gridsmooth(Z, span):
    """ Smooths values on 2D rectangular grid
    """
    import warnings
    warnings.filterwarnings('ignore')

    x = np.linspace(-2.*span, 2.*span, 2.*span + 1.)
    y = np.linspace(-2.*span, 2.*span, 2.*span + 1.)
    (X, Y) = np.meshgrid(x, y)
    mu = np.array([0., 0.])
    sigma = np.diag([span, span])**2.
    F = gauss2(X, Y, mu, sigma)
    F = F/np.sum(F)
    W = np.ones(Z.shape)
    Z = _signal.convolve2d(Z, F, 'same')
    W = _signal.convolve2d(W, F, 'same')
    Z = Z/W
    return Z 
Example #7
Source File: test_conv_cuda_ndarray.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def py_conv_scipy(img, kern, mode, subsample):
    assert img.shape[1] == kern.shape[1]
    if mode == 'valid':
        outshp = (img.shape[0], kern.shape[0],
                img.shape[2] - kern.shape[2] + 1,
                img.shape[3] - kern.shape[3] + 1)
    else:
        outshp = (img.shape[0], kern.shape[0],
                img.shape[2] + kern.shape[2] - 1,
                img.shape[3] + kern.shape[3] - 1)
    out = numpy.zeros(outshp, dtype='float32')
    for b in xrange(out.shape[0]):
        for k in xrange(out.shape[1]):
            for s in xrange(img.shape[1]):
                #convolve2d or correlate
                out[b, k, :, :] += convolve2d(img[b, s, :, :],
                                  kern[k, s, :, :],
                                  mode)
    return out[:, :, ::subsample[0], ::subsample[1]] 
Example #8
Source File: test_conv_cuda_ndarray.py    From D-VAE with MIT License 6 votes vote down vote up
def py_conv_scipy(img, kern, mode, subsample):
    assert img.shape[1] == kern.shape[1]
    if mode == 'valid':
        outshp = (img.shape[0], kern.shape[0],
                img.shape[2] - kern.shape[2] + 1,
                img.shape[3] - kern.shape[3] + 1)
    else:
        outshp = (img.shape[0], kern.shape[0],
                img.shape[2] + kern.shape[2] - 1,
                img.shape[3] + kern.shape[3] - 1)
    out = numpy.zeros(outshp, dtype='float32')
    for b in xrange(out.shape[0]):
        for k in xrange(out.shape[1]):
            for s in xrange(img.shape[1]):
                #convolve2d or correlate
                out[b, k, :, :] += convolve2d(img[b, s, :, :],
                                  kern[k, s, :, :],
                                  mode)
    return out[:, :, ::subsample[0], ::subsample[1]] 
Example #9
Source File: prepare_pairwise_distribution.py    From joint-cnn-mrf with MIT License 6 votes vote down vote up
def compute_pairwise_distribution(joint, cond_j):
    """
    This computes a single histogram for a pair of (joint, cond_joint), and applies gaussian smoothing
    :param joint: e.g. 'lsho'
    :param cond_j: e.g. 'nose'
    :return: 120 x 180 pairwise distribution
    """
    hp_height = y_train.shape[1]
    hp_width = y_train.shape[2]
    pd = np.zeros([hp_height * 2, hp_width * 2])  # the pairwise distribution is twice the size of the heat map
    # print(pd.shape)
    for i in range(y_train.shape[0]):  # for every single image, we note the distance between the joint and cond_j
        img_j = y_train[i, :, :, joint_ids.index(joint)]
        img_cj = y_train[i, :, :, joint_ids.index(cond_j)]
        xj, yj = np.where(img_j == np.max(img_j))
        xcj, ycj = np.where(img_cj == np.max(img_cj))
        pd[hp_height + (xj - xcj), hp_width + (yj - ycj)] += 1  # count for the histgram
    pd = pd / np.float32(np.sum(pd))
    pd = signal.convolve2d(pd, kernel, mode='same', boundary='fill', fillvalue=0)
    return pd 
Example #10
Source File: test_signaltools.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_valid_mode2(self):
        # See gh-5897
        e = [[1, 2, 3], [3, 4, 5]]
        f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]]
        expected = [[62, 80, 98, 116, 134]]

        out = convolve2d(e, f, 'valid')
        assert_array_equal(out, expected)

        out = convolve2d(f, e, 'valid')
        assert_array_equal(out, expected)

        e = [[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]]
        f = [[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]]
        expected = [[27 - 1j, 46. + 2j]]

        out = convolve2d(e, f, 'valid')
        assert_array_equal(out, expected)

        # See gh-5897
        out = convolve2d(f, e, 'valid')
        assert_array_equal(out, expected) 
Example #11
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #12
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #13
Source File: unguided_network.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def navg_layer(self, kernel_size, init_stdev=0.5, in_channels=1, out_channels=1, initalizer='x', pos=False, groups=1):
        
        navg = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, 
                         padding=(kernel_size[0]//2, kernel_size[1]//2), bias=False, groups=groups)
        
        weights = navg.weight            
        
        if initalizer == 'x': # Xavier            
            torch.nn.init.xavier_uniform(weights)
        elif initalizer == 'k':    
            torch.nn.init.kaiming_uniform(weights)
        elif initalizer == 'p':    
            mu=kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.FloatTensor(w).cuda()
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(out_channels, 1, 1, 1)
            w = w.repeat(1, in_channels, 1, 1)
            weights.data = w + torch.rand(w.shape).cuda()
         
        return navg 
Example #14
Source File: nconv.py    From nconv with GNU General Public License v3.0 6 votes vote down vote up
def init_parameters(self):
        # Init weights
        if self.init_method == 'x': # Xavier            
            torch.nn.init.xavier_uniform_(self.weight)
        elif self.init_method == 'k': # Kaiming
            torch.nn.init.kaiming_uniform_(self.weight)
        elif self.init_method == 'p': # Poisson
            mu=self.kernel_size[0]/2 
            dist = poisson(mu)
            x = np.arange(0, self.kernel_size[0])
            y = np.expand_dims(dist.pmf(x),1)
            w = signal.convolve2d(y, y.transpose(), 'full')
            w = torch.Tensor(w).type_as(self.weight)
            w = torch.unsqueeze(w,0)
            w = torch.unsqueeze(w,1)
            w = w.repeat(self.out_channels, 1, 1, 1)
            w = w.repeat(1, self.in_channels, 1, 1)
            self.weight.data = w + torch.rand(w.shape)
            
        # Init bias
        self.bias = torch.nn.Parameter(torch.zeros(self.out_channels)+0.01)
        
        
# Non-negativity enforcement class 
Example #15
Source File: rule_30_and_game_of_life.py    From rule-30-and-game-of-life with MIT License 6 votes vote down vote up
def update_rows_and_gol_state(self):
    # Update `rows` (the state of the 2D cellular automaton).
    rule_index = signal.convolve2d(self.row[None, :],
                                   self.row_neighbors[None, :],
                                   mode='same', boundary='wrap')
    self.row = self.rule_kernel[rule_index[0]]
    transfer_row = self.rows[:1]
    self.rows = np.concatenate((
        self.rows[1:],
        self.row[None, self.row_padding:-self.row_padding]
    ))

    # Update `gol_state` (the state of the 3D cellular automaton).
    num_neighbors = signal.convolve2d(self.gol_state, self.gol_neighbors,
                                      mode='same', boundary='wrap')
    self.gol_state = np.logical_or(num_neighbors == 3,
                                   np.logical_and(num_neighbors == 2,
                                                  self.gol_state)
                                   ).astype(np.uint8)

    self.gol_state = np.concatenate((
        np.zeros((1, self.gol_state_width), np.uint8),
        self.gol_state[1:-1],
        transfer_row
    )) 
Example #16
Source File: metrics.py    From suite2p with GNU General Public License v3.0 5 votes vote down vote up
def filt_worker(inputs):
    X, filt = inputs
    for n in range(X.shape[0]):
        X[n,:,:] = convolve2d(X[n,:,:], filt, 'same')
    return X 
Example #17
Source File: featExt.py    From TextDetector with GNU General Public License v3.0 5 votes vote down vote up
def conv2d(im, co):
	''' conv2d(im, co)

	convolve an image with a codebook patch 
	im: 2D_numpy_array contains target image, with shape m by n
	co: 2D_numpy_array codebook patch with shape 8 by 8 
	Return 2D_numpy_array with shape same as <im> '''
	return convolve2d(im, co, mode = 'same') 
Example #18
Source File: numpy_impl.py    From twitter-sent-dnn with MIT License 5 votes vote down vote up
def conv2d(input_feature_map, filters, mode = "full"):
    """
    Convolution operation that functions as same as `theano.tensor.nnet.conv.conv2d`
    
    Refer to: [the theano documentation](http://deeplearning.net/software/theano/library/tensor/nnet/conv.html#theano.tensor.nnet.conv.conv2d)
    
    """
    assert len(input_feature_map.shape) == 4
    assert len(filters.shape) == 4
    batch_size, input_feature_n1, input_w, input_h = input_feature_map.shape
    output_feature_n, input_feature_n2, filter_w, filter_h = filters.shape

    assert input_feature_n1 == input_feature_n2, "%d != %d" %(input_feature_n1, input_feature_n2)

    output_feature_map = np.zeros((batch_size, 
                                   output_feature_n, 
                                   input_w + filter_w - 1, 
                                   input_h + filter_h - 1))

    for i in xrange(batch_size):
        # for the ith instance
        for k in xrange(output_feature_n):
            # for the kth feature map in the output
            for l in xrange(input_feature_n1):
                # for the lth feature map in the input
                output_feature_map[i, k] += convolve2d(input_feature_map[i, l], 
                                                       filters[k, l], 
                                                       mode = mode)

    return output_feature_map 
Example #19
Source File: metrics.py    From suite2p with GNU General Public License v3.0 5 votes vote down vote up
def local_corr(mov, batch_size, num_cores):
    """ computes correlation image on mov (nframes x pixels x pixels) """
    nframes, Ly, Lx = mov.shape

    filt = np.ones((3,3),np.float32)
    filt[1,1] = 0
    fnorm = ((filt**2).sum())**0.5
    filt /= fnorm
    ix=0
    k=0
    filtnorm = convolve2d(np.ones((Ly,Lx)),filt,'same')

    img_corr = np.zeros((Ly,Lx), np.float32)
    while ix < nframes:
        ifr = np.arange(ix, min(ix+batch_size, nframes), 1, int)

        X = mov[ifr,:,:]
        X = X.astype(np.float32)
        X -= X.mean(axis=0)
        Xstd = X.std(axis=0)
        Xstd[Xstd==0] = np.inf
        #X /= np.maximum(1, X.std(axis=0))
        X /= Xstd
        #for n in range(X.shape[0]):
        #    X[n,:,:] *= convolve2d(X[n,:,:], filt, 'same')
        X *= filt_parallel(X, filt, num_cores)
        img_corr += X.mean(axis=0)
        ix += batch_size
        k+=1
    img_corr /= filtnorm
    img_corr /= float(k)
    return img_corr 
Example #20
Source File: game_of_life.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def step(X):
    nbrs_count = convolve2d(X, np.ones((3, 3)), mode='same', boundary='wrap') - X
    return (nbrs_count == 3) | (X & (nbrs_count == 2)) 
Example #21
Source File: convolution_nodes.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _execute(self, x):
        is_2d = x.ndim==2
        output_shape, input_shape = self._output_shape, self._input_shape
        filters = self.filters
        nfilters = filters.shape[0]

        # XXX depends on convolution
        y = numx.empty((x.shape[0], nfilters,
                        output_shape[0], output_shape[1]), dtype=self.dtype)
        for n_im, im in enumerate(x):
            if is_2d:
                im = im.reshape(input_shape)
            for n_flt, flt in enumerate(filters):
                if self.approach == 'fft':
                    y[n_im,n_flt,:,:] = signal.fftconvolve(im, flt, mode=self.mode)
                elif self.approach == 'linear':
                    y[n_im,n_flt,:,:] = signal.convolve2d(im, flt,
                                                          mode=self.mode,
                                                          boundary=self.boundary,
                                                          fillvalue=self.fillvalue)

        # reshape if necessary
        if self.output_2d:
            y.resize((y.shape[0], self.output_dim))

        return y 
Example #22
Source File: testNNRegression.py    From kusanagi with MIT License 5 votes vote down vote up
def build_dataset(idims=9,odims=6,angi=[],f=test_func1,n_train=500,n_test=50, input_noise=0.01, output_noise=0.01,rand_seed=None):
    if rand_seed is not None:
        np.random.seed(rand_seed)
    #  ================== train dataset ==================
    # sample training points
    x_train = 15*(np.random.rand(n_train,idims) - 0.25)
    # generate the output at the training points
    y_train = np.empty((n_train,odims))
    for i in range(odims):
        y_train[:,i] =  (i+1)*f(x_train) + output_noise*(np.random.randn(n_train))
    x_train = utils.gTrig_np(x_train, angi)
    
    #  ================== test  dataset ==================
    # generate testing points
    #kk = input_noise*convolve2d(np.array([[1,2,3,2,1]]),np.array([[1,2,3,2,1]]).T)/9.0;
    #s_test = convolve2d(np.eye(idims),kk,'same')
    s_test = input_noise*np.eye(idims)
    s_test = np.tile(s_test,(n_test,1)).reshape(n_test,idims,idims)
    x_test = 120*(np.random.rand(n_test,idims) - 0.5)
    # generate the output at the test points
    y_test = np.empty((n_test,odims))
    for i in range(odims):
        y_test[:,i] =  (i+1)*f(x_test)
    if len(angi)>0:
        x_test,s_test = utils.gTrig2_np(x_test,s_test, angi, idims)

    return (x_train,y_train),(x_test,y_test,s_test) 
Example #23
Source File: testGPRegressor.py    From kusanagi with MIT License 5 votes vote down vote up
def build_dataset(idims=9, odims=6, angi=[], f=test_func1, n_train=500,
                  n_test=50, input_noise=0.01, output_noise=0.01, f_type=0,
                  rand_seed=None):
    if rand_seed is not None:
        np.random.seed(rand_seed)
    #  ================== train dataset ==================
    # sample training points
    x_train = 5*(np.random.rand(int(n_train/2), idims) - 1.25)
    x_train2 = 5*(np.random.rand(int(n_train/2), idims) + 1.25)
    x_train = np.concatenate([x_train, x_train2], axis=0)
    # generate the output at the training points
    y_train = np.empty((n_train, odims))
    for i in range(odims):
        y_train[:, i] = (i+1)*f(x_train, f_type)
        y_train[:, i] += output_noise*(np.random.randn(n_train))
    x_train = utils.gTrig_np(x_train, angi)

    #  ================== test  dataset ==================
    # generate testing points
    # kk = input_noise*convolve2d(
    #      np.array([[1,2,3,2,1]]),np.array([[1,2,3,2,1]]).T)/9.0;
    # s_test = convolve2d(np.eye(idims),kk,'same')
    s_test = input_noise*np.eye(idims)
    s_test = np.tile(s_test, (n_test, 1)).reshape(n_test, idims, idims)
    x_test = 75*(np.random.rand(n_test, idims) - 0.5)
    # generate the output at the test points
    y_test = np.empty((n_test, odims))
    for i in range(odims):
        y_test[:, i] = (i+1)*f(x_test, f_type)
    if len(angi) > 0:
        x_test, s_test = utils.gTrig2_np(x_test, s_test, angi, idims)

    return (x_train, y_train), (x_test, y_test, s_test) 
Example #24
Source File: measure_utils.py    From ambient-gan with MIT License 5 votes vote down vote up
def get_blur_func():
    def unmeasure_func(image, mask):
        gaussian_filter = get_gaussian_filter(radius=1, size=5)
        blurred = np.zeros_like(image)
        for c in range(image.shape[2]):
            image_c = image[:, :, c]
            mask_c = mask[:, :, c]
            if np.min(mask_c) > 0:
                # if mask is all ones, no need to blur
                blurred[:, :, c] = image_c
            else:
                blurred[:, :, c] = signal.convolve2d(image_c, gaussian_filter, mode='same')
        return blurred
    return unmeasure_func 
Example #25
Source File: amb_measure.py    From ambient-gan with MIT License 5 votes vote down vote up
def unmeasure_np(self, hparams, x_measured_val, theta_val):
        if hparams.unmeasure_type == 'medfilt':
            unmeasure_func = lambda image, mask: signal.medfilt(image)
        # elif hparams.unmeasure_type == 'inpaint-telea':
        #     inpaint_type = cv2.INPAINT_TELEA
        #     unmeasure_func = amb_measure_utils.get_inpaint_func_opencv(inpaint_type)
        # elif hparams.unmeasure_type == 'inpaint-ns':
        #     inpaint_type = cv2.INPAINT_NS
        #     unmeasure_func = amb_measure_utils.get_inpaint_func_opencv(inpaint_type)
        # elif hparams.unmeasure_type == 'inpaint-tv':
        #     assert hparams.dataset == 'mnist'  # Single channel support only
        #     unmeasure_func = amb_measure_utils.get_inpaint_func_tv()
        elif hparams.unmeasure_type == 'blur':
            # TODO(abora): Move radius and size to hparams
            gaussian_filter = amb_measure_utils.get_gaussian_filter(radius=1, size=5)
            def unmeasure_func(image, mask):
                blurred = np.zeros_like(image)
                for c in range(image.shape[2]):
                    blurred[:, :, c] = signal.convolve2d(image[:, :, c], gaussian_filter, mode='same')
                return blurred
        else:
            raise NotImplementedError

        x_unmeasured_val = np.zeros_like(x_measured_val)
        for i in range(x_measured_val.shape[0]):
            x_unmeasured_val[i] = unmeasure_func(x_measured_val[i], theta_val[i])
        return x_unmeasured_val 
Example #26
Source File: test_lin_ops.py    From ProxImaL with MIT License 5 votes vote down vote up
def test_conv_halide(self):
        """Test convolution lin op in halide.
        """
        if halide_installed():
            # Load image
            testimg_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                            'data', 'angela.jpg')
            # opens the file using Pillow - it's not an array yet
            img = Image.open(testimg_filename)
            np_img = np.asfortranarray(im2nparray(img))

            # Convert to gray
            np_img = np.mean(np_img, axis=2)

            # Test problem
            output = np.zeros_like(np_img)
            K = np.ones((11, 11), dtype=np.float32, order='FORTRAN')
            K /= np.prod(K.shape)

            #Convolve in halide
            Halide('A_conv.cpp').A_conv(np_img, K, output)

            #Convolve in scipy
            output_ref = signal.convolve2d(np_img, K, mode='same', boundary='wrap')

            # Transpose
            output_corr = np.zeros_like(np_img)
            Halide('At_conv.cpp').At_conv(np_img, K, output_corr)  # Call

            output_corr_ref = signal.convolve2d(np_img, np.flipud(np.fliplr(K)),
                                                mode='same', boundary='wrap')

            self.assertItemsAlmostEqual(output, output_ref)
            self.assertItemsAlmostEqual(output_corr, output_corr_ref) 
Example #27
Source File: utils.py    From ExposureFusion with MIT License 5 votes vote down vote up
def Expand1(image, a=0.6):
    kernel = get_kernel(a)
    shape = image.shape
    if len(shape) == 3:
        image_to_expand = np.zeros((2*shape[0], 2*shape[1], 3))
        image_expanded = np.zeros(image_to_expand.shape)
        for canal in range(3):
            image_to_expand[::2, ::2, canal] = image[:, :, canal]
            image_expanded[:, :, canal] = sig.convolve2d(image_to_expand[:, :, canal], 4*kernel, 'same')
    else:
        image_to_expand = np.zeros((2 * shape[0], 2 * shape[1]))
        image_to_expand[::2, ::2] = image
        image_expanded = sig.convolve2d(image_to_expand[:, :], 4*kernel, 'same')
    return image_expanded 
Example #28
Source File: utils.py    From ExposureFusion with MIT License 5 votes vote down vote up
def Reduce1(image, a=0.6):
    kernel = get_kernel(a)
    shape = image.shape
    if len(shape) == 3:
        image_reduced = np.zeros((shape[0]/2, shape[1]/2, 3))
        for canal in range(3):
            canal_reduced = sig.convolve2d(image[:, :, canal], kernel, 'same')
            image_reduced[:, :, canal] = canal_reduced[::2, ::2]
    else:
        image_reduced = sig.convolve2d(image, kernel, 'same')[::2, ::2]
    return image_reduced 
Example #29
Source File: test_signaltools.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_invalid_dims(self):
        assert_raises(ValueError, convolve2d, 3, 4)
        assert_raises(ValueError, convolve2d, [3], [4])
        assert_raises(ValueError, convolve2d, [[[3]]], [[[4]]]) 
Example #30
Source File: test_signaltools.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_same_mode(self):
        e = [[1, 2, 3], [3, 4, 5]]
        f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]]
        g = convolve2d(e, f, 'same')
        h = array([[22, 28, 34],
                   [80, 98, 116]])
        assert_array_equal(g, h)