Python scipy.ndimage.interpolation.shift() Examples

The following are 30 code examples of scipy.ndimage.interpolation.shift(). 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.ndimage.interpolation , or try the search function .
Example #1
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def _scale_mask(mask, scale_amount=0.025):
  """Damages a mask for a single object by randomly scaling it in numpy.

  Args:
    mask: Boolean numpy array of shape(height, width, 1).
    scale_amount: Float scalar, the maximum factor for random scaling.

  Returns:
    The scaled version of mask.
  """
  nzy, nzx, _ = mask.nonzero()
  cy = 0.5 * (nzy.max() - nzy.min())
  cx = 0.5 * (nzx.max() - nzx.min())
  scale_factor = np.random.uniform(1.0 - scale_amount, 1.0 + scale_amount)
  shift = transform.SimilarityTransform(translation=[-cx, -cy])
  inv_shift = transform.SimilarityTransform(translation=[cx, cy])
  s = transform.SimilarityTransform(scale=[scale_factor, scale_factor])
  m = (shift + (s + inv_shift)).inverse
  scaled_mask = transform.warp(mask, m) > 0.5
  return scaled_mask 
Example #2
Source File: test_kernel_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def test_deshift_subgrid():
    # test the de-shifting with a sharpened subgrid kernel
    kernel_size = 5
    subgrid = 3
    fwhm = 1
    kernel_subgrid_size = kernel_size * subgrid
    kernel_subgrid = np.zeros((kernel_subgrid_size, kernel_subgrid_size))
    kernel_subgrid[7, 7] = 2
    kernel_subgrid = kernel_util.kernel_gaussian(kernel_subgrid_size, 1./subgrid, fwhm=fwhm)

    kernel = util.averaging(kernel_subgrid, kernel_subgrid_size, kernel_size)

    shift_x = 0.18
    shift_y = 0.2
    shift_x_subgird = shift_x * subgrid
    shift_y_subgrid = shift_y * subgrid
    kernel_shifted_subgrid = interp.shift(kernel_subgrid, [-shift_y_subgrid, -shift_x_subgird], order=1)
    kernel_shifted = util.averaging(kernel_shifted_subgrid, kernel_subgrid_size, kernel_size)
    kernel_shifted_highres = kernel_util.subgrid_kernel(kernel_shifted, subgrid_res=subgrid, num_iter=1)
    #npt.assert_almost_equal(kernel_shifted_highres[7, 7], kernel_shifted_subgrid[7, 7], decimal=10) 
Example #3
Source File: test_kernel_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def test_shift_long_dist():
    """
    input is a shifted kernel by more than 1 pixel
    :return:
    """

    kernel_size = 9
    kernel = np.zeros((kernel_size, kernel_size))
    kernel[4, 4] = 2.
    shift_x = 2.
    shift_y = 1.
    input_kernel = interp.shift(kernel, [-shift_y, -shift_x], order=1)
    old_style_kernel = interp.shift(input_kernel, [shift_y, shift_x], order=1)
    shifted_new = kernel_util.de_shift_kernel(input_kernel, shift_x, shift_y)
    assert kernel[3, 2] == shifted_new[3, 2]
    assert np.max(old_style_kernel - shifted_new) < 0.01 
Example #4
Source File: test_kernel_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def test_cutout_source_border():
    kernel_size = 7
    image = np.zeros((10, 10))
    kernel = np.zeros((kernel_size, kernel_size))
    kernel[2, 2] = 1
    shift_x = +0.1
    shift_y = 0
    x_c, y_c = 2, 5
    x_pos = x_c + shift_x
    y_pos = y_c + shift_y
    #kernel_shifted = interp.shift(kernel, [shift_y, shift_x], order=1)
    image = image_util.add_layer2image(image, x_pos, y_pos, kernel, order=1)
    kernel_new = kernel_util.cutout_source(x_pos=x_pos, y_pos=y_pos, image=image, kernelsize=kernel_size)
    nx_new, ny_new = np.shape(kernel_new)
    print(kernel_new)
    assert nx_new == kernel_size
    assert ny_new == kernel_size
    npt.assert_almost_equal(kernel_new[2, 2], kernel[2, 2], decimal=2) 
Example #5
Source File: test_kernel_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def test_cutout_source():
    """
    test whether a shifted psf can be reproduced sufficiently well
    :return:
    """
    kernel_size = 5
    image = np.zeros((10, 10))
    kernel = np.zeros((kernel_size, kernel_size))
    kernel[2, 2] = 1
    shift_x = 0.5
    shift_y = 0
    x_c, y_c = 5, 5
    x_pos = x_c + shift_x
    y_pos = y_c + shift_y
    #kernel_shifted = interp.shift(kernel, [shift_y, shift_x], order=1)
    image = image_util.add_layer2image(image, x_pos, y_pos, kernel, order=1)
    print(image)
    kernel_new = kernel_util.cutout_source(x_pos=x_pos, y_pos=y_pos, image=image, kernelsize=kernel_size)
    npt.assert_almost_equal(kernel_new[2, 2], kernel[2, 2], decimal=2) 
Example #6
Source File: image_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def add_layer2image(grid2d, x_pos, y_pos, kernel, order=1):
    """
    adds a kernel on the grid2d image at position x_pos, y_pos with an interpolated subgrid pixel shift of order=order
    :param grid2d: 2d pixel grid (i.e. image)
    :param x_pos: x-position center (pixel coordinate) of the layer to be added
    :param y_pos: y-position center (pixel coordinate) of the layer to be added
    :param kernel: the layer to be added to the image
    :param order: interpolation order for sub-pixel shift of the kernel to be added
    :return: image with added layer, cut to original size
    """

    x_int = int(round(x_pos))
    y_int = int(round(y_pos))
    shift_x = x_int - x_pos
    shift_y = y_int - y_pos
    kernel_shifted = interp.shift(kernel, [-shift_y, -shift_x], order=order)
    return add_layer2image_int(grid2d, x_int, y_int, kernel_shifted) 
Example #7
Source File: kernel_util.py    From lenstronomy with MIT License 6 votes vote down vote up
def center_kernel(kernel, iterations=20):
    """
    given a kernel that might not be perfectly centered, this routine computes its light weighted center and then
    moves the center in an iterative process such that it is centered

    :param kernel: 2d array (odd numbers)
    :param iterations: int, number of iterations
    :return: centered kernel
    """
    kernel = kernel_norm(kernel)
    nx, ny = np.shape(kernel)
    if nx %2 == 0:
        raise ValueError("kernel needs odd number of pixels")
    # make coordinate grid of kernel
    x_grid, y_grid = util.make_grid(nx, deltapix=1, left_lower=False)
    # compute 1st moments to get light weighted center
    x_w = np.sum(kernel * util.array2image(x_grid))
    y_w = np.sum(kernel * util.array2image(y_grid))
    # de-shift kernel
    kernel_centered = de_shift_kernel(kernel, shift_x=-x_w, shift_y=-y_w, iterations=iterations)
    return kernel_norm(kernel_centered) 
Example #8
Source File: colorize3_poisson.py    From SynthText with Apache License 2.0 6 votes vote down vote up
def drop_shadow(self, alpha, theta, shift, size, op=0.80):
        """
        alpha : alpha layer whose shadow need to be cast
        theta : [0,2pi] -- the shadow direction
        shift : shift in pixels of the shadow
        size  : size of the GaussianBlur filter
        op    : opacity of the shadow (multiplying factor)

        @return : alpha of the shadow layer
                  (it is assumed that the color is black/white)
        """
        if size%2==0:
            size -= 1
            size = max(1,size)
        shadow = cv.GaussianBlur(alpha,(size,size),0)
        [dx,dy] = shift * np.array([-np.sin(theta), np.cos(theta)])
        shadow = op*sii.shift(shadow, shift=[dx,dy],mode='constant',cval=0)
        return shadow.astype('uint8') 
Example #9
Source File: caffe_jitterlayer.py    From nideep with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setup(self, bottom, top):
		'''
		bottom blob:
		[ratemap]:	Nx1xFxT
		[amsFeature]:	NxMxFxT
		1.check bottom/top blob vector size
		2.read in parameters
	    	shift in T,F(time,frequency) domain
		'''
		# check input
		if len(bottom) != 1:
			raise Exception("Need one input to apply jitter.")
		self.shift_f = 0 # shift over frequency domain
		self.shift_t = 0 # shift over time domain

#		self.forwardIter = 0

		params = eval(self.param_str)	# read in as dictionary
       		# set parameters according to the train_val.prototxt,
        	# use python built-in function for dictionary
    		self.min_shift_f = params.get('min_shift_f',0)
    		self.max_shift_f = params.get('max_shift_f',0)
		self.min_shift_t = params.get('min_shift_t',0)
		self.max_shift_t = params.get('max_shift_t',0) 
Example #10
Source File: example_simple_GUI.py    From PyAbel with MIT License 6 votes vote down vote up
def _getfilename():
    global IM, text
    fn = filedialog.askopenfilename()

    # update what is occurring text box
    text.delete(1.0, tk.END)
    text.insert(tk.END, "reading image file {:s}\n".format(fn))
    canvas.draw()

    # read image file
    if ".txt" in fn:
        IM = np.loadtxt(fn)
    else:
        IM = imread(fn)

    if IM.shape[0] % 2 == 0:
        text.insert(tk.END, "make image odd size")
        IM = shift(IM, (-0.5, -0.5))[:-1, :-1]

    # show the image
    _display() 
Example #11
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def damage_masks(labels, shift=True, scale=True, rotate=True, dilate=True):
  """Damages segmentation masks by random transformations.

  Args:
    labels: Int32 labels tensor of shape (height, width, 1).
    shift: Boolean, whether to damage the masks by shifting.
    scale: Boolean, whether to damage the masks by scaling.
    rotate: Boolean, whether to damage the masks by rotation.
    dilate: Boolean, whether to damage the masks by dilation.

  Returns:
    The damaged version of labels.
  """
  def _damage_masks_np(labels_):
    return damage_masks_np(labels_, shift, scale, rotate, dilate)
  damaged_masks = tf.py_func(_damage_masks_np, [labels], tf.int32,
                             name='damage_masks')
  damaged_masks.set_shape(labels.get_shape())
  return damaged_masks 
Example #12
Source File: bouncyhouse.py    From technical with GNU General Public License v3.0 6 votes vote down vote up
def bounce(dataframe: DataFrame, level):
    """

    :param dataframe:
    :param level:
    :return:
      1 if it bounces up
      0 if no bounce
     -1 if it bounces below
    """

    from scipy.ndimage.interpolation import shift
    open = dataframe['open']
    close = dataframe['close']
    touch = shift(touches(dataframe, level), 1, cval=np.NAN)

    return np.vectorize(_bounce)(open, close, level, touch) 
Example #13
Source File: transitionModels.py    From bayesloop with MIT License 6 votes vote down vote up
def computeBackwardPrior(self, posterior, t):
        # determine grid axis along which to shift the distribution
        axisToTransform = self.study.observationModel.parameterNames.index(self.selectedParameter)

        # compute offset to shift parameter grid
        params = {name: value for (name, value) in zip(self.hyperParameterNames, self.hyperParameterValues)}
        ftm1 = self.function(t - 1 - self.tOffset, **params)
        ft = self.function(t - self.tOffset, **params)
        d = ftm1 - ft

        # normalize offset with respect to lattice constant of parameter grid
        d /= self.latticeConstant[axisToTransform]

        # build list for all axes of parameter grid (setting only the selected axis to a non-zero value)
        dAll = [0] * len(self.latticeConstant)
        dAll[axisToTransform] = d

        # shift interpolated version of distribution
        newPrior = shift(posterior, dAll, order=3, mode='nearest')

        # transformation above may violate proper normalization; re-normalization needed
        newPrior /= np.sum(newPrior)

        return newPrior 
Example #14
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def damage_masks_np(labels, shift=True, scale=True, rotate=True, dilate=True):
  """Performs the actual mask damaging in numpy.

  Args:
    labels: Int32 numpy array of shape (height, width, 1).
    shift: Boolean, whether to damage the masks by shifting.
    scale: Boolean, whether to damage the masks by scaling.
    rotate: Boolean, whether to damage the masks by rotation.
    dilate: Boolean, whether to damage the masks by dilation.

  Returns:
    The damaged version of labels.
  """
  unique_labels = np.unique(labels)
  unique_labels = np.setdiff1d(unique_labels, [0])
  # Shuffle to get random depth ordering when combining together.
  np.random.shuffle(unique_labels)
  damaged_labels = np.zeros_like(labels)
  for l in unique_labels:
    obj_mask = (labels == l)
    damaged_obj_mask = _damage_single_object_mask(obj_mask, shift, scale,
                                                  rotate, dilate)
    damaged_labels[damaged_obj_mask] = l
  return damaged_labels 
Example #15
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def _damage_single_object_mask(mask, shift, scale, rotate, dilate):
  """Performs mask damaging in numpy for a single object.

  Args:
    mask: Boolean numpy array of shape(height, width, 1).
    shift: Boolean, whether to damage the masks by shifting.
    scale: Boolean, whether to damage the masks by scaling.
    rotate: Boolean, whether to damage the masks by rotation.
    dilate: Boolean, whether to damage the masks by dilation.

  Returns:
    The damaged version of mask.
  """
  # For now we just do shifting and scaling. Better would be Affine or thin
  # spline plate transformations.
  if shift:
    mask = _shift_mask(mask)
  if scale:
    mask = _scale_mask(mask)
  if rotate:
    mask = _rotate_mask(mask)
  if dilate:
    mask = _dilate_mask(mask)
  return mask 
Example #16
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def _shift_mask(mask, max_shift_factor=0.05):
  """Damages a mask for a single object by randomly shifting it in numpy.

  Args:
    mask: Boolean numpy array of shape(height, width, 1).
    max_shift_factor: Float scalar, the maximum factor for random shifting.

  Returns:
    The shifted version of mask.
  """
  nzy, nzx, _ = mask.nonzero()
  h = nzy.max() - nzy.min()
  w = nzx.max() - nzx.min()
  size = np.sqrt(h * w)
  offset = np.random.uniform(-size * max_shift_factor, size * max_shift_factor,
                             2)
  shifted_mask = interpolation.shift(np.squeeze(mask, axis=2),
                                     offset, order=0).astype('bool')[...,
                                                                     np.newaxis]
  return shifted_mask 
Example #17
Source File: signal_alignment.py    From Signal-Alignment with GNU General Public License v3.0 6 votes vote down vote up
def highres(y,kind='cubic',res=100):
    '''
    Interpolate data onto a higher resolution grid by a factor of *res*

    Args:
        y (1d array/list): signal to be interpolated
        kind (str): order of interpolation (see docs for scipy.interpolate.interp1d)
        res (int): factor to increase resolution of data via linear interpolation
    
    Returns:
        shift (float): offset between target and reference signal 
    '''
    y = np.array(y)
    x = np.arange(0, y.shape[0])
    f = interp1d(x, y,kind='cubic')
    xnew = np.linspace(0, x.shape[0]-1, x.shape[0]*res)
    ynew = f(xnew)
    return xnew,ynew 
Example #18
Source File: ABuNDAtr.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _calc_atr_from_pd(high, low, close, time_period=14):
    """
    通过atr公式手动计算atr
    :param high: 最高价格序列,pd.Series或者np.array
    :param low: 最低价格序列,pd.Series或者np.array
    :param close: 收盘价格序列,pd.Series或者np.array
    :param time_period: atr的N值默认值14,int
    :return: atr值序列,np.array对象
    """
    if isinstance(close, pd.Series):
        # shift(1)构成昨天收盘价格序列
        pre_close = close.shift(1).values
    else:
        from scipy.ndimage.interpolation import shift
        # 也可以暂时转换为pd.Series进行shift
        pre_close = shift(close, 1)
    pre_close[0] = pre_close[1]

    if isinstance(high, pd.Series):
        high = high.values
    if isinstance(low, pd.Series):
        low = low.values

    # ∣最高价 - 最低价∣
    tr_hl = np.abs(high - low)
    # ∣最高价 - 昨收∣
    tr_hc = np.abs(high - pre_close)
    # ∣昨收 - 最低价∣
    tr_cl = np.abs(pre_close - low)
    # TR =∣最高价 - 最低价∣,∣最高价 - 昨收∣,∣昨收 - 最低价∣中的最大值
    tr = np.maximum(np.maximum(tr_hl, tr_hc), tr_cl)
    # (ATR)= MA(TR, N)(TR的N日简单移动平均), 这里没有完全按照标准公式使用简单移动平均,使用了pd_ewm_mean,即加权移动平均
    atr = pd_ewm_mean(pd.Series(tr), span=time_period, min_periods=1)
    # 返回atr值序列,np.array对象
    return atr.values 
Example #19
Source File: dftreg.py    From sima with GNU General Public License v2.0 5 votes vote down vote up
def _register_frame(frame, mean_img, upsample_factor=1,
                    max_displacement=None,
                    return_registered=False):
    """
    Called by _make_mean_img and _register_all_frames
    """
    # compute the offsets
    dy, dx = _register_translation(mean_img, frame,
                                   upsample_factor=upsample_factor)

    if max_displacement is not None:
        if dy > max_displacement[0]:
            dy = max_displacement[0]
            # dy = 0
        if dx > max_displacement[1]:
            dx = max_displacement[1]
            # dx = 0

    if return_registered:
        registered_frame = shift(frame,
                                 [dy, dx],
                                 order=3,
                                 mode='constant',
                                 cval=0,
                                 output=frame.dtype)

        return dy, dx, registered_frame
    else:
        return dy, dx 
Example #20
Source File: test_time_zero.py    From scikit-ued with MIT License 5 votes vote down vote up
def test_shift_with_noise(self):
        """ Test measuring the time-shift between traces shifted from one another, with added 6% gaussian noise """
        trace1 = np.sin(2 * np.pi * np.linspace(0, 10, 64))
        trace2 = scipy_shift(trace1, 5)

        trace1 = trace1[6:-6]
        trace2 = trace2[6:-6]

        trace1 += 0.03 * np.random.random(size=trace1.shape)
        trace2 += 0.03 * np.random.random(size=trace2.shape)
        shift = register_time_shift(trace1, trace2)
        self.assertEqual(shift, -5) 
Example #21
Source File: pandas_utils.py    From scikit-lego with MIT License 5 votes vote down vote up
def _add_lagged_pandas_columns(df, cols, lags, drop_na):
    """
    Append a lag columns.

    :param df: the input ``pd.DataFrame``.
    :param cols: column name(s).
    :param drop_na: remove rows that contain NA values.
    :returns: ``pd.DataFrame`` with the concatenated lagged cols.
    """

    cols = as_list(cols)

    # Indexes are not supported as pandas column names may be
    # integers themselves, introducing unexpected behaviour
    if not all([col in df.columns.values for col in cols]):
        raise KeyError("The column does not exist")

    combos = (
        df[col].shift(-lag).rename(col + str(lag)) for col in cols for lag in lags
    )

    answer = pd.concat([df, *combos], axis=1)

    # Remove rows that contain NA values when drop_na is truthy
    if drop_na:
        answer = answer.dropna()

    return answer 
Example #22
Source File: pandas_utils.py    From scikit-lego with MIT License 5 votes vote down vote up
def _add_lagged_numpy_columns(X, cols, lags, drop_na):
    """
    Append a lag columns.

    :param df: the input ``np.ndarray``.
    :param cols: column index / indices.
    :param drop_na: remove rows that contain NA values.
    :returns: ``np.ndarray`` with the concatenated lagged cols.
    """

    cols = as_list(cols)

    if not all([isinstance(col, int) for col in cols]):
        raise ValueError("Matrix columns are indexed by integers")

    if not all([col < X.shape[1] for col in cols]):
        raise KeyError("The column does not exist")

    combos = (shift(X[:, col], -lag, cval=np.NaN) for col in cols for lag in lags)

    # In integer-based ndarrays, NaN values are represented as
    # -9223372036854775808, so we convert back and forth from
    # original to float and back to original dtype
    original_type = X.dtype
    X = np.asarray(X, dtype=float)
    answer = np.column_stack((X, *combos))

    # Remove rows that contain NA values when drop_na is truthy
    if drop_na:
        answer = answer[~np.isnan(answer).any(axis=1)]

    # Change dtype back to its original
    answer = np.asarray(answer, dtype=original_type)
    return answer 
Example #23
Source File: colorize.py    From SRNet-Datagen with Apache License 2.0 5 votes vote down vote up
def drop_shadow(self, alpha, theta, shift, size, op=0.80):
        
        if size % 2 == 0:
            size -= 1
            size = max(1, size)
        shadow = cv2.GaussianBlur(alpha, (size,size), 0)
        [dx, dy] = shift * np.array([-np.sin(theta), np.cos(theta)])
        shadow = op * sii.shift(shadow, shift = [dx,dy], mode = 'constant', cval = 0)
        return shadow.astype(np.uint8) 
Example #24
Source File: discrete_bayes.py    From filterpy with MIT License 5 votes vote down vote up
def predict(pdf, offset, kernel, mode='wrap', cval=0.):
    """ Performs the discrete Bayes filter prediction step, generating
    the prior.

    `pdf` is a discrete probability distribution expressing our initial
    belief.

    `offset` is an integer specifying how much we want to move to the right
    (negative values means move to the left)

    We assume there is some noise in that offset, which we express in `kernel`.
    For example, if offset=3 and kernel=[.1, .7., .2], that means we think
    there is a 70% chance of moving right by 3, a 10% chance of moving 2
    spaces, and a 20% chance of moving by 4.

    It returns the resulting distribution.

    If `mode='wrap'`, then the probability distribution is wrapped around
    the array.

    If `mode='constant'`, or any other value the pdf is shifted, with `cval`
    used to fill in missing elements.

    Examples
    --------
    .. code-block:: Python

        belief = [.05, .05, .05, .05, .55, .05, .05, .05, .05, .05]
        prior = predict(belief, offset=2, kernel=[.1, .8, .1])
    """

    if mode == 'wrap':
        return convolve(np.roll(pdf, offset), kernel, mode='wrap')

    return convolve(shift(pdf, offset, cval=cval), kernel,
                    cval=cval, mode='constant') 
Example #25
Source File: psf_fitting.py    From lenstronomy with MIT License 5 votes vote down vote up
def cutout_psf_single(self, x, y, image, mask, kernelsize, kernel_init):
        """

        :param x: x-coordinate of point soure
        :param y: y-coordinate of point source
        :param image: image (i.e. data - all models subtracted, except a single point source)
        :param mask: mask of pixels in the image not to be considered in the PSF estimate (being replaced by kernel_init)
        :param kernelsize: width in pixel of the kernel
        :param kernel_init: initial guess of kernel (pixels that are masked are replaced by those values)
        :return: estimate of the PSF based on the image and position of the point source
        """
        # cutout the star
        x_int = int(round(x))
        y_int = int(round(y))
        star_cutout = kernel_util.cutout_source(x_int, y_int, image, kernelsize + 2, shift=False)
        # cutout the mask
        mask_cutout = kernel_util.cutout_source(x_int, y_int, mask, kernelsize + 2, shift=False)
        # enlarge the initial PSF kernel to the new cutout size
        kernel_enlarged = np.zeros((kernelsize+2, kernelsize+2))
        kernel_enlarged[1:-1, 1:-1] = kernel_init
        # shift the initial kernel to the shift of the star
        shift_x = x_int - x
        shift_y = y_int - y
        kernel_shifted = interp.shift(kernel_enlarged, [-shift_y, -shift_x], order=1)
        # compute normalization of masked and unmasked region of the shifted kernel
        # norm_masked = np.sum(kernel_shifted[mask_i == 0])
        norm_unmasked = np.sum(kernel_shifted[mask_cutout == 1])
        # normalize star within the unmasked region to the norm of the initial kernel of the same region
        star_cutout /= np.sum(star_cutout[mask_cutout == 1]) * norm_unmasked
        # replace mask with shifted initial kernel (+2 size)
        star_cutout[mask_cutout == 0] = kernel_shifted[mask_cutout == 0]
        star_cutout[star_cutout < 0] = 0
        # de-shift kernel
        kernel_deshifted = kernel_util.de_shift_kernel(star_cutout, shift_x, shift_y)
        # re-size kernel
        kernel_deshifted = image_util.cut_edges(kernel_deshifted, kernelsize)
        # re-normalize kernel again
        kernel_deshifted = kernel_util.kernel_norm(kernel_deshifted)
        return kernel_deshifted 
Example #26
Source File: test_kernel_util.py    From lenstronomy with MIT License 5 votes vote down vote up
def test_de_shift():
    kernel_size = 5
    kernel = np.zeros((kernel_size, kernel_size))
    kernel[2, 2] = 2
    shift_x = 0.48
    shift_y = 0.2
    kernel_shifted = interp.shift(kernel, [-shift_y, -shift_x], order=1)
    kernel_de_shifted = kernel_util.de_shift_kernel(kernel_shifted, shift_x, shift_y, iterations=50)
    delta_max = np.max(kernel- kernel_de_shifted)
    assert delta_max < 0.01
    npt.assert_almost_equal(kernel_de_shifted[2, 2], kernel[2, 2], decimal=2)

    kernel_size = 5
    kernel = np.zeros((kernel_size, kernel_size))
    kernel[2, 2] = 2
    shift_x = 1.48
    shift_y = 0.2
    kernel_shifted = interp.shift(kernel, [-shift_y, -shift_x], order=1)
    kernel_de_shifted = kernel_util.de_shift_kernel(kernel_shifted, shift_x, shift_y, iterations=50)
    delta_max = np.max(kernel - kernel_de_shifted)
    assert delta_max < 0.01
    npt.assert_almost_equal(kernel_de_shifted[2, 2], kernel[2, 2], decimal=2)

    kernel_size_x = 5
    kernel_size_y = 4
    kernel = np.zeros((kernel_size_x, kernel_size_y))
    kernel[2, 2] = 2
    shift_x = 1.48
    shift_y = 0.2
    kernel_shifted = interp.shift(kernel, [-shift_y, -shift_x], order=1)
    kernel_de_shifted = kernel_util.de_shift_kernel(kernel_shifted, shift_x, shift_y, iterations=50)
    delta_max = np.max(kernel - kernel_de_shifted)
    assert delta_max < 0.01
    npt.assert_almost_equal(kernel_de_shifted[2, 2], kernel[2, 2], decimal=2) 
Example #27
Source File: kernel_util.py    From lenstronomy with MIT License 5 votes vote down vote up
def cutout_source(x_pos, y_pos, image, kernelsize, shift=True):
    """
    cuts out point source (e.g. PSF estimate) out of image and shift it to the center of a pixel
    :param x_pos:
    :param y_pos:
    :param image:
    :param kernelsize:
    :return:
    """
    if kernelsize % 2 == 0:
        raise ValueError("even pixel number kernel size not supported!")
    x_int = int(round(x_pos))
    y_int = int(round(y_pos))
    n = len(image)
    d = (kernelsize - 1)/2
    x_max = int(np.minimum(x_int + d + 1, n))
    x_min = int(np.maximum(x_int - d, 0))
    y_max = int(np.minimum(y_int + d + 1, n))
    y_min = int(np.maximum(y_int - d, 0))
    image_cut = copy.deepcopy(image[y_min:y_max, x_min:x_max])
    shift_x = x_int - x_pos
    shift_y = y_int - y_pos
    if shift is True:
        kernel_shift = de_shift_kernel(image_cut, shift_x, shift_y, iterations=50)
    else:
        kernel_shift = image_cut
    kernel_final = np.zeros((kernelsize, kernelsize))

    k_l2_x = int((kernelsize - 1) / 2)
    k_l2_y = int((kernelsize - 1) / 2)

    xk_min = np.maximum(0, -x_int + k_l2_x)
    yk_min = np.maximum(0, -y_int + k_l2_y)
    xk_max = np.minimum(kernelsize, -x_int + k_l2_x + n)
    yk_max = np.minimum(kernelsize, -y_int + k_l2_y + n)

    kernel_final[yk_min:yk_max, xk_min:xk_max] = kernel_shift
    return kernel_final 
Example #28
Source File: kernel_util.py    From lenstronomy with MIT License 5 votes vote down vote up
def de_shift_kernel(kernel, shift_x, shift_y, iterations=20):
    """
    de-shifts a shifted kernel to the center of a pixel. This is performed iteratively.

    The input kernel is the solution of a linear interpolated shift of a sharper kernel centered in the middle of the
     pixel. To find the de-shifted kernel, we perform an iterative correction of proposed de-shifted kernels and compare
     its shifted version with the input kernel.

    :param kernel: (shifted) kernel, e.g. a star in an image that is not centered in the pixel grid
    :param shift_x: x-offset relative to the center of the pixel (sub-pixel shift)
    :param shift_y: y-offset relative to the center of the pixel (sub-pixel shift)
    :return: de-shifted kernel such that the interpolated shift boy (shift_x, shift_y) results in the input kernel
    """
    nx, ny = np.shape(kernel)
    kernel_new = np.zeros((nx+2, ny+2)) + (kernel[0, 0] + kernel[0, -1] + kernel[-1, 0] + kernel[-1, -1]) / 4.
    kernel_new[1:-1, 1:-1] = kernel
    int_shift_x = int(round(shift_x))
    frac_x_shift = shift_x - int_shift_x
    int_shift_y = int(round(shift_y))
    frac_y_shift = shift_y - int_shift_y
    kernel_init = copy.deepcopy(kernel_new)
    kernel_init_shifted = copy.deepcopy(interp.shift(kernel_init, [int_shift_y, int_shift_x], order=1))
    kernel_new = interp.shift(kernel_new, [int_shift_y, int_shift_x], order=1)
    norm = np.sum(kernel_init_shifted)
    for i in range(iterations):
        kernel_shifted_inv = interp.shift(kernel_new, [-frac_y_shift, -frac_x_shift], order=1)
        delta = kernel_init_shifted - kernel_norm(kernel_shifted_inv) * norm
        kernel_new += delta * 1.
        kernel_new = kernel_norm(kernel_new) * norm
    return kernel_new[1:-1, 1:-1] 
Example #29
Source File: input_modifiers.py    From keras-vis with MIT License 5 votes vote down vote up
def pre(self, img):
        if not self._processed:
            image_dims = utils.get_img_shape(img)[2:]
            self._process_jitter_values(image_dims)

        dim_offsets = [np.random.randint(-value, value + 1) for value in self.jitter]
        if K.image_data_format() == 'channels_first':
            shift_vector = np.array([0, 0] + dim_offsets)
        else:
            shift_vector = np.array([0] + dim_offsets + [0])

        return shift(img, shift_vector, mode='wrap', order=0) 
Example #30
Source File: analytic.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def _dSIR_compact_effective_degree_(X, t, N, tau, gamma):
    Skappa = X[:-2]
    R, SI = X[-2:]
    I = N- R- Skappa.sum()
    kappas = np.arange(len(Skappa))
    effectiveI = float(SI) /Skappa.dot(kappas)
    dSkappa = effectiveI*(-(tau+gamma)*kappas*Skappa \
                + gamma*shift(kappas*Skappa,-1))
    dSI = -(tau+gamma)*SI \
            + tau*(effectiveI-2*effectiveI**2)*sum(kappas*(kappas-1)*Skappa)

    dR = gamma*I
    dX = np.concatenate((dSkappa, [dR, dSI]), axis=0) 
    return dX