Python numpy.ogrid() Examples

The following are 30 code examples of numpy.ogrid(). 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: test_backend_pgf.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bbox_inches():
    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(range(5))
    ax2 = fig.add_subplot(122)
    ax2.plot(range(5))
    plt.tight_layout()

    bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox},
                   tol=0) 
Example #2
Source File: core.py    From mars with Apache License 2.0 6 votes vote down vote up
def execute_combine(cls, ctx, op):
        axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
        (vals, arg), device_id, xp = as_same_device(
            ctx[op.inputs[0].key], device=op.device, ret_extra=True)

        func_name = getattr(cls, '_func_name')
        arg_func = getattr(xp, func_name)
        with device(device_id):
            if axis is None:
                local_args = arg_func(vals, axis=axis).reshape(op.outputs[0].shape)
                vals = vals.ravel()[local_args]
                arg = arg.ravel()[local_args]
            else:
                local_args = arg_func(vals, axis=axis)
                inds = np.ogrid[tuple(map(slice, local_args.shape))]
                if xp != np:
                    inds = [xp.asarray(it) for it in inds]
                inds.insert(axis, local_args)
                inds_tuple = tuple(inds)
                vals = vals[inds_tuple].reshape(op.outputs[0].shape)
                arg = arg[inds_tuple].reshape(op.outputs[0].shape)
            ctx[op.outputs[0].key] = (vals, arg) 
Example #3
Source File: core.py    From mars with Apache License 2.0 6 votes vote down vote up
def execute_agg(cls, ctx, op):
        axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
        (vals, arg), device_id, xp = as_same_device(
            ctx[op.inputs[0].key], device=op.device, ret_extra=True)

        func_name = getattr(cls, '_func_name')
        arg_func = getattr(xp, func_name)

        with device(device_id):
            if xp.any(xp.isnan(vals)) and 'nan' in func_name:
                raise ValueError("All NaN slice encountered")
            if axis is None:
                local_args = arg_func(vals, axis=axis)
                arg = arg.ravel()[local_args]
            else:
                local_args = arg_func(vals, axis=axis)
                inds = np.ogrid[tuple(map(slice, local_args.shape))]
                if xp != np:
                    inds = [xp.asarray(it) for it in inds]
                inds.insert(axis, local_args)
                arg = arg[tuple(inds)]
            ctx[op.outputs[0].key] = arg 
Example #4
Source File: image.py    From keras-utility-layer-collection with MIT License 6 votes vote down vote up
def _bilinear_upsampling_weights(weight_shape):
        # weight_shape must be (width, height, n_channels, n_channels)

        if weight_shape[-1] != weight_shape[-2]:
            raise ValueError("Number of input channels must be the same as the number of input channels.")

        weight = np.zeros(weight_shape, dtype=np.float32)

        # create single upsampling kernel for one channel
        # according to http://warmspringwinds.github.io/tensorflow/tf-slim/2016/11/22/upsampling-and-image-segmentation-with-tensorflow-and-tf-slim/

        grid = np.ogrid[:weight_shape[0], :weight_shape[1]]
        factors = [(s+1)//2 for s in weight_shape[:2]]
        centers = [(s+1)//2 - 0.5*(s%2 + 1) for s in weight_shape[:2]]

        upsampling_kernel = (1-abs(grid[0] - centers[0]) / factors[0]) * (1-abs(grid[1] - centers[1]) / factors[1])

        for i in range(weight_shape[-1]):
            weight[:, :, i, i] = upsampling_kernel

        return weight 
Example #5
Source File: functions.py    From Semantic-Segmentation-using-Adversarial-Networks with MIT License 6 votes vote down vote up
def bilinear_interpolation_kernel(in_channels, out_channels, ksize):
    """calculate a bilinear interpolation kernel

    Args:
        in_channels (int): Number of channels of input arrays. If ``None``,
            parameter initialization will be deferred until the first forward
            data pass at which time the size will be determined.
        out_channels (int): Number of channels of output arrays.
        ksize (int): Size of filters (a.k.a. kernels).
    """

    factor = (ksize + 1) / 2
    if ksize % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:ksize, :ksize]
    k = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
                                                                                
    W = np.zeros((in_channels, out_channels, ksize, ksize)).astype(np.float32)
    W[range(in_channels), range(out_channels), :, :] = k
    return W 
Example #6
Source File: models.py    From hed-pytorch with MIT License 6 votes vote down vote up
def make_bilinear_weights(size, num_channels):
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
    # print(filt)
    filt = torch.from_numpy(filt)
    w = torch.zeros(num_channels, num_channels, size, size)
    w.requires_grad = False
    for i in range(num_channels):
        for j in range(num_channels):
            if i == j:
                w[i, j] = filt
    return w 
Example #7
Source File: target_generator.py    From gluon-cv with Apache License 2.0 6 votes vote down vote up
def _gaussian_2d(shape, sigma=1):
    """Generate 2d gaussian.

    Parameters
    ----------
    shape : tuple of int
        The shape of the gaussian.
    sigma : float
        Sigma for gaussian.

    Returns
    -------
    float
        2D gaussian kernel.

    """
    m, n = [(ss - 1.) / 2. for ss in shape]
    y, x = np.ogrid[-m:m+1, -n:n+1]

    h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
    h[h < np.finfo(h.dtype).eps * h.max()] = 0
    return h 
Example #8
Source File: kaleidoscope.py    From pywonderland with MIT License 6 votes vote down vote up
def main(imgsize):
    y, x = np.ogrid[6: -6: imgsize*2j, -6: 6: imgsize*2j]
    z = x + y*1j
    z = RiemannSphere(Klein(Mobius(Klein(z))))

    # define colors in hsv space
    H = np.sin(z[0]*np.pi)**2
    S = np.cos(z[1]*np.pi)**2
    V = abs(np.sin(z[2]*np.pi) * np.cos(z[2]*np.pi))**0.2
    HSV = np.stack((H, S, V), axis=2)

    # transform to rgb space
    img = hsv_to_rgb(HSV)
    fig = plt.figure(figsize=(imgsize/100.0, imgsize/100.0), dpi=100)
    ax = fig.add_axes([0, 0, 1, 1], aspect=1)
    ax.axis('off')
    ax.imshow(img)
    fig.savefig('kaleidoscope.png') 
Example #9
Source File: scene_processing.py    From kite with GNU General Public License v3.0 6 votes vote down vote up
def apply(self):
        sc = self.scene
        org = self.original
        factor = self.factor

        sx, sy = sc.displacement.shape
        gx, gy = num.ogrid[0:sx, 0:sy]
        regions = sy/factor * (gx/factor) + gy/factor
        indices = num.arange(regions.max() + 1)

        def block_downsample(arr):
            res = ndimage.mean(
                arr,
                labels=regions,
                index=indices)
            res.shape = (sx/factor, sy/factor)
            return res

        sc.displacement = block_downsample(sc.displacement)
        sc.theta = block_downsample(sc.theta)
        sc.phi = block_downsample(sc.phi)
        sc.frame.dLat = org['frame.dLat'] * self.factor
        sc.frame.dLon = org['frame.dLat'] * self.factor 
Example #10
Source File: test_backend_pgf.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_bbox_inches():
    if not check_for('xelatex'):
        raise SkipTest('xelatex + pgf is required')

    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(range(5))
    ax2 = fig.add_subplot(122)
    ax2.plot(range(5))
    plt.tight_layout()

    bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox}) 
Example #11
Source File: mini_imagenet.py    From versa with MIT License 6 votes vote down vote up
def onehottify_2d_array(a):
    """
    https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy
    :param a: 2-dimensional array.
    :return: 3-dim array where last dim corresponds to one-hot encoded vectors.
    """

    # https://stackoverflow.com/a/46103129/ @Divakar
    def all_idx(idx, axis):
        grid = np.ogrid[tuple(map(slice, idx.shape))]
        grid.insert(axis, idx)
        return tuple(grid)

    num_columns = a.max() + 1
    out = np.zeros(a.shape + (num_columns,), dtype=int)
    out[all_idx(a, axis=2)] = 1
    return out 
Example #12
Source File: density_gen.py    From Counting-ICCV-DSSINet with MIT License 6 votes vote down vote up
def get(self, shape=(3, 3), sigma=0.5):
        if '%d_%d' % (int(shape[0]), int(sigma * 10)) not in self.kernel_set.keys():
            m, n = [(ss - 1.0) / 2.0 for ss in shape]
            y, x = np.ogrid[-m:m + 1, -n:n + 1]
            h = np.exp(-(x * x + y * y) / (2.0 * sigma * sigma))
            h[h < np.finfo(h.dtype).eps * h.max()] = 0
            # import pdb
            # pdb.set_trace()
            t = h[0][int(m)]
            h[h < t] = 0
            sumh = h.sum()
            if sumh != 0:
                h /= sumh
            self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))] = h
            return h
        else:
            return self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))] 
Example #13
Source File: utils.py    From dal with MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example #14
Source File: utils.py    From dal with MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example #15
Source File: utils.py    From dal with MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example #16
Source File: misc.py    From cross-season-segmentation with MIT License 6 votes vote down vote up
def get_upsampling_weight(in_channels, out_channels, kernel_size):
    factor = (kernel_size + 1) // 2
    if kernel_size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:kernel_size, :kernel_size]
    filt = (1 - abs(og[0] - center) / factor) * \
        (1 - abs(og[1] - center) / factor)
    weight = np.zeros(
        (in_channels,
         out_channels,
         kernel_size,
         kernel_size),
        dtype=np.float64)
    weight[list(range(in_channels)), list(range(out_channels)), :, :] = filt
    return torch.from_numpy(weight).float() 
Example #17
Source File: HumanPts.py    From CU-Net with Apache License 2.0 6 votes vote down vote up
def pts2resmap(pts, resmap_shape, radius):
    # generate multi-channel resmap, one map for each point
    pts_num = pts.shape[0]
    resmap = np.zeros((pts_num, resmap_shape[0], resmap_shape[1]))
    valid_pts = np.zeros((pts.shape))
    for i in range(0, pts_num):
        # if vis_arr[i] == -1:
        #     continue
        # note that here we can't use vis_arr to indicate whether to draw the annotation
        # because some pts are labeled visible but not within the effective crop area due to the
        # inaccurate person scale in the original annotation
        if pts[i][0] <= 0 or pts[i][1] <= 0 or \
                        pts[i][0] > resmap_shape[1] or pts[i][1] > resmap_shape[0]:
            continue
        y, x = np.ogrid[-pts[i][1]:resmap_shape[0] - pts[i][1], -pts[i][0]:resmap_shape[1] - pts[i][0]]
        mask = x * x + y * y <= radius * radius
        resmap[i][mask] = 1
        valid_pts[i] = pts[i]
        # print('channel %d sum is %.f' % (i, np.sum(resmap[i])))
    return resmap, valid_pts 
Example #18
Source File: util.py    From modred with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def Hankel(first_col, last_row=None):
    """
    Construct a Hankel array, whose skew diagonals are constant.

    Args:
        ``first_col``: 1D array corresponding to first column of Hankel array.

    Kwargs:
        ``last_row``: 1D array corresponding to the last row of Hankel array.
        First element will be ignored.  Default is an array of zeros of the same
        size as ``first_col``.

    Returns:
        Hankel: 2D array with dimensions ``[len(first_col), len(last_row)]``.
    """
    first_col = np.array(first_col).flatten()
    if last_row is None:
        last_row = np.zeros(first_col.shape)
    else:
        last_row = last_row.flatten()

    unique_vals = np.concatenate((first_col, last_row[1:]))
    a, b = np.ogrid[0:len(first_col), 0:len(last_row)]
    indices = a + b
    return unique_vals[indices] 
Example #19
Source File: tracker.py    From KCF-DSST-py with MIT License 6 votes vote down vote up
def createHanningMats(self):
        hann2t, hann1t = np.ogrid[0:self.size_patch[0], 0:self.size_patch[1]]
 
        hann1t = 0.5 * (1 - np.cos(2 * np.pi * hann1t / (self.size_patch[1] - 1)))
        hann2t = 0.5 * (1 - np.cos(2 * np.pi * hann2t / (self.size_patch[0] - 1)))
        hann2d = hann2t * hann1t
 
        if self._hogfeatures:
            hann1d = hann2d.reshape(self.size_patch[0] * self.size_patch[1])
            self.hann = np.zeros((self.size_patch[2], 1), np.float32) + hann1d
            #相当于把1D汉宁窗复制成多个通道
        else:
            self.hann = hann2d
        
        self.hann = self.hann.astype(np.float32)

    # 创建高斯峰函数,函数只在第一帧的时候执行(高斯响应) 
Example #20
Source File: tracker.py    From KCF-DSST-py with MIT License 5 votes vote down vote up
def createGaussianPeak(self, sizey, sizex):
        syh, sxh = sizey / 2, sizex / 2
        output_sigma = np.sqrt(sizex * sizey) / self.padding * self.output_sigma_factor
        mult = -0.5 / (output_sigma * output_sigma)
        y, x = np.ogrid[0:sizey, 0:sizex]
        y, x = (y - syh) ** 2, (x - sxh) ** 2
        res = np.exp(mult * (y + x))
        return fftd(res)

    # 使用带宽SIGMA计算高斯卷积核以用于所有图像X和Y之间的相对位移
    # 必须都是MxN大小。二者必须都是周期的(即,通过一个cos窗口进行预处理) 
Example #21
Source File: hot_words_generator.py    From LagouJob with Apache License 2.0 5 votes vote down vote up
def cal_and_show_job_impression_hot_words(self, interviewee_comments_dir='../spider/impression'):
        """
        calculate and show hot words of Job Impression
        :param interviewee_comments_dir:
        :return:
        """
        if not os.path.exists(interviewee_comments_dir) or len(os.listdir(interviewee_comments_dir)) == 0:
            print('Error! No valid content in {0}'.format(interviewee_comments_dir))
            sys.exit(0)
        else:
            job_and_dir = {_: os.path.join(interviewee_comments_dir, _) for _ in os.listdir(interviewee_comments_dir)}

            for k, v in job_and_dir.items():
                text = self.concat_all_text(v)
                jieba.analyse.set_stop_words(STOPWORDS_PATH)
                jieba.load_userdict(USER_CORPUS)
                hot_words_with_weights = jieba.analyse.extract_tags(text, topK=30, withWeight=True, allowPOS=())

                frequencies = {_[0]: _[1] for _ in hot_words_with_weights}

                print(frequencies)

                x, y = np.ogrid[:300, :300]
                mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2
                mask = 255 * mask.astype(int)

                wordcloud = WordCloud(font_path='./msyh.ttf', width=600, height=300, background_color="white",
                                      repeat=False,
                                      mask=mask)
                wordcloud.generate_from_frequencies(frequencies)

                import matplotlib.pyplot as plt
                plt.imshow(wordcloud, interpolation='bilinear')
                plt.axis("off")
                plt.show() 
Example #22
Source File: test_delaunay.py    From neural-network-animation with MIT License 5 votes vote down vote up
def plot(self, func, interp=True, plotter='imshow'):
        if interp:
            lpi = self.interpolator(func)
            z = lpi[self.yrange[0]:self.yrange[1]:complex(0,self.nrange),
                    self.xrange[0]:self.xrange[1]:complex(0,self.nrange)]
        else:
            y, x = np.mgrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange),
                            self.xrange[0]:self.xrange[1]:complex(0,self.nrange)]
            z = func(x, y)

        z = np.where(np.isinf(z), 0.0, z)

        extent = (self.xrange[0], self.xrange[1],
            self.yrange[0], self.yrange[1])
        fig = plt.figure()
        plt.hot() # Some like it hot
        if plotter == 'imshow':
            plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower')
        elif plotter == 'contour':
            Y, X = np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange),
                self.xrange[0]:self.xrange[1]:complex(0,self.nrange)]
            plt.contour(np.ravel(X), np.ravel(Y), z, 20)
        x = self.x
        y = self.y
        lc = mpl.collections.LineCollection(np.array([((x[i], y[i]), (x[j], y[j]))
            for i, j in self.tri.edge_db]), colors=[(0,0,0,0.2)])
        ax = plt.gca()
        ax.add_collection(lc)

        if interp:
            title = '%s Interpolant' % self.name
        else:
            title = 'Reference'
        if hasattr(func, 'title'):
            plt.title('%s: %s' % (func.title, title))
        else:
            plt.title(title) 
Example #23
Source File: sampling.py    From chainer with MIT License 5 votes vote down vote up
def _get_linear_filter(size, ndim, upsampling=True):
    """Make a 2D and 3D linear kernel suitable for up/downsampling"""
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1.
    else:
        center = factor - 0.5
    slices = (slice(size),) * ndim
    og = numpy.ogrid[slices]
    filt = 1.
    for og_i in og:
        filt = filt * (1. - abs(og_i - center) / factor)
    if not upsampling:
        filt /= filt.sum()
    return filt 
Example #24
Source File: weight.py    From fcn with MIT License 5 votes vote down vote up
def _get_upsampling_filter(size):
    """Make a 2D bilinear kernel suitable for upsampling"""
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    filter = (1 - abs(og[0] - center) / factor) * \
             (1 - abs(og[1] - center) / factor)
    return filter 
Example #25
Source File: surgery.py    From fcn with MIT License 5 votes vote down vote up
def upsample_filt(size):
    """
    Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
    """
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    return (1 - abs(og[0] - center) / factor) * \
           (1 - abs(og[1] - center) / factor) 
Example #26
Source File: create_label.py    From centernet_tensorflow_wilderface_voc with MIT License 5 votes vote down vote up
def creat_roiheatmap_circle(det_size_map):
    min_size=min(det_size_map)
    sigma = ((min_size - 1) * 0.5 - 1) * 0.3 + 0.8
    s_ = 2 * (sigma ** 2)
    h, w = [(hw - 1.) / 2. for hw in det_size_map]
    y, x = np.ogrid[-h:h + 1, -w:w + 1]
    heatmap = np.exp(-x**2 / s_ - y**2 / s_)
    return heatmap 
Example #27
Source File: bdcn.py    From BDCN with MIT License 5 votes vote down vote up
def get_upsampling_weight(in_channels, out_channels, kernel_size):
    """Make a 2D bilinear kernel suitable for upsampling"""
    factor = (kernel_size + 1) // 2
    if kernel_size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:kernel_size, :kernel_size]
    filt = (1 - abs(og[0] - center) / factor) * \
           (1 - abs(og[1] - center) / factor)
    weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size),
                      dtype=np.float64)
    weight[range(in_channels), range(out_channels), :, :] = filt
    return torch.from_numpy(weight).float() 
Example #28
Source File: ablation.py    From BDCN with MIT License 5 votes vote down vote up
def get_upsampling_weight(in_channels, out_channels, kernel_size):
    """Make a 2D bilinear kernel suitable for upsampling"""
    factor = (kernel_size + 1) // 2
    if kernel_size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:kernel_size, :kernel_size]
    filt = (1 - abs(og[0] - center) / factor) * \
           (1 - abs(og[1] - center) / factor)
    weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size),
                      dtype=np.float64)
    weight[range(in_channels), range(out_channels), :, :] = filt
    return torch.from_numpy(weight).float() 
Example #29
Source File: sorting.py    From MDT with GNU Lesser General Public License v3.0 5 votes vote down vote up
def sort_volumes_per_voxel(input_volumes, sort_matrix):
    """Sort the given volumes per voxel using the sort index in the given matrix.

    What this essentially does is to look per voxel from which map we should take the first value. Then we place that
    value in the first volume and we repeat for the next value and finally for the next voxel.

    If the length of the 4th dimension is > 1 we shift the 4th dimension to the 5th dimension and sort
    the array as if the 4th dimension values where a single value. This is useful for sorting (eigen)vector matrices.

    Args:
        input_volumes (:class:`list`): list of 4d ndarray
        sort_matrix (ndarray): 4d ndarray with for every voxel the sort index

    Returns:
        :class:`list`: the same input volumes but then with every voxel sorted according to the given sort index.
    """
    def load_maps(map_list):
        tmp = []
        for data in map_list:
            if isinstance(data, str):
                data = load_nifti(data).get_data()

            if len(data.shape) < 4:
                data = data[..., None]

            tmp.append(data)
        return tmp

    input_volumes = load_maps(input_volumes)

    if input_volumes[0].shape[3] > 1:
        volume = np.concatenate([np.reshape(m, m.shape[0:3] + (1,) + (m.shape[3],)) for m in input_volumes], axis=3)
        grid = np.ogrid[[slice(x) for x in volume.shape]]
        sorted_volume = volume[list(grid[:-2]) + [np.reshape(sort_matrix, sort_matrix.shape + (1,))] + list(grid[-1])]
        return [sorted_volume[..., ind, :] for ind in range(len(input_volumes))]
    else:
        volume = np.concatenate([m for m in input_volumes], axis=3)
        sorted_volume = volume[list(np.ogrid[[slice(x) for x in volume.shape]][:-1])+[sort_matrix]]
        return [np.reshape(sorted_volume[..., ind], sorted_volume.shape[0:3] + (1,))
                for ind in range(len(input_volumes))] 
Example #30
Source File: tracker.py    From KCF-DSST-py with MIT License 5 votes vote down vote up
def createHanningMatsForScale(self):
        _, hann_s = np.ogrid[0:0, 0:self.n_scales]
        hann_s = 0.5 * (1 - np.cos(2 * np.pi * hann_s / (self.n_scales - 1)))
        return hann_s

    # 初始化尺度估计器