Python scipy.ndimage.median_filter() Examples

The following are 30 code examples of scipy.ndimage.median_filter(). 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 , or try the search function .
Example #1
Source File: filtering.py    From lidar with MIT License 6 votes vote down vote up
def MedianFilter(in_dem, kernel_size=3, out_file=None):

    print("Median filtering ...")
    start_time = time.time()
    dem = rd.LoadGDAL(in_dem)
    no_data = dem.no_data
    projection = dem.projection
    geotransform = dem.geotransform

    med = ndimage.median_filter(dem, size=kernel_size)
    med = np2rdarray(med, no_data, projection, geotransform)
    print("Run time: {:.4f} seconds".format(time.time() - start_time))

    if out_file is not None:
        print("Saving dem ...")
        rd.SaveGDAL(out_file, med)
        return out_file

    return med


# Gaussian filter 
Example #2
Source File: qps_rings.py    From qkit with GNU General Public License v2.0 6 votes vote down vote up
def find_jumps2(self,ds,threshold=30000):
        self._prepare_find_jumps()
        ds = self._hf[ds]
        offset=ds[0]
        # first we remove a bit of noise
        #flt = gaussian_filter1d(ds,10)
        flt = median_filter(ds,size=10)
        #flt = ds
        # the sobel filter finds the "jumps" 
        sb=sobel(flt)
        for i in sb:
            self.qps_jpn_hight.append(float(i))
            
        for i in flt: self.qps_jpn_spec.append(float(i))
        """    
        for i in xrange(flt.shape[0]-1):
            if(abs(sb[i])>threshold):
                offset -= sb[i]
                
                self.qps_jpn_spec.append(float(flt[i]-offset))
            else:
                self.qps_jpn_spec.append(float(flt[i]-offset))
        """       

        #for i in sb 
Example #3
Source File: dask_tools.py    From pyxem with GNU General Public License v3.0 6 votes vote down vote up
def _background_removal_single_frame_median(frame, footprint=19):
    """Background removal using median filter.

    Parameters
    ----------
    frame : NumPy 2D array
    footprint : float

    Returns
    -------
    background_removed : Numpy 2D array

    Examples
    --------
    >>> import pyxem.utils.dask_tools as dt
    >>> s = pxm.dummy_data.dummy_data.get_cbed_signal()
    >>> s_rem = dt._background_removal_single_frame_median(s.data[0, 0])

    """
    bg_subtracted = frame - ndi.median_filter(frame, size=footprint)
    return bg_subtracted 
Example #4
Source File: profile.py    From pylinac with MIT License 6 votes vote down vote up
def filter(self, size: NumberLike=0.05, kind: str='median'):
        """Filter the profile.

        Parameters
        ----------
        size : float, int
            Size of the median filter to apply.
            If a float, the size is the ratio of the length. Must be in the range 0-1.
            E.g. if size=0.1 for a 1000-element array, the filter will be 100 elements.
            If an int, the filter is the size passed.
        kind : {'median', 'gaussian'}
            The kind of filter to apply. If gaussian, `size` is the sigma value.
        """
        if isinstance(size, float):
            if 0 < size < 1:
                size = int(round(len(self.values)*size))
                size = max(size, 1)
            else:
                raise TypeError("Float was passed but was not between 0 and 1")

        if kind == 'median':
            self.values = ndimage.median_filter(self.values, size=size)
        elif kind == 'gaussian':
            self.values = ndimage.gaussian_filter(self.values, sigma=size) 
Example #5
Source File: image.py    From pylinac with MIT License 6 votes vote down vote up
def filter(self, size: Union[float, int]=0.05, kind: str='median'):
        """Filter the profile.

        Parameters
        ----------
        size : int, float
            Size of the median filter to apply.
            If a float, the size is the ratio of the length. Must be in the range 0-1.
            E.g. if size=0.1 for a 1000-element array, the filter will be 100 elements.
            If an int, the filter is the size passed.
        kind : {'median', 'gaussian'}
            The kind of filter to apply. If gaussian, *size* is the sigma value.
        """
        if isinstance(size, float):
            if 0 < size < 1:
                size *= len(self.array)
                size = max(size, 1)
            else:
                raise TypeError("Float was passed but was not between 0 and 1")

        if kind == 'median':
            self.array = ndimage.median_filter(self.array, size=size)
        elif kind == 'gaussian':
            self.array = ndimage.gaussian_filter(self.array, sigma=size) 
Example #6
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_rank12(self):
        expected = [[3, 3, 2, 4, 4],
                    [3, 5, 2, 5, 1],
                    [5, 5, 8, 3, 5]]
        footprint = [[1, 0, 1], [0, 1, 0]]
        for type_ in self.types:
            array = numpy.array([[3, 2, 5, 1, 4],
                                 [5, 8, 3, 7, 1],
                                 [5, 6, 9, 3, 5]], type_)
            output = ndimage.rank_filter(array, 1, footprint=footprint)
            assert_array_almost_equal(expected, output)
            output = ndimage.percentile_filter(array, 50.0,
                                               footprint=footprint)
            assert_array_almost_equal(expected, output)
            output = ndimage.median_filter(array, footprint=footprint)
            assert_array_almost_equal(expected, output) 
Example #7
Source File: dataloader_spacetime.py    From space_time_pde with MIT License 6 votes vote down vote up
def filter(self, signal):
        """Filter a given signal with a choice of filter type (self.lres_filter).
        """
        signal = signal.copy()
        filter_size = [1, self.downsamp_t*2-1, self.downsamp_xz*2-1, self.downsamp_xz*2-1]

        if self.lres_filter == 'none' or (not self.lres_filter):
            output = signal
        elif self.lres_filter == 'gaussian':
            sigma = [0, int(self.downsamp_t/2), int(self.downsamp_xz/2), int(self.downsamp_xz/2)]
            output = ndimage.gaussian_filter(signal, sigma=sigma)
        elif self.lres_filter == 'uniform':
            output = ndimage.uniform_filter(signal, size=filter_size)
        elif self.lres_filter == 'median':
            output = ndimage.median_filter(signal, size=filter_size)
        elif self.lres_filter == 'maximum':
            output = ndimage.maximum_filter(signal, size=filter_size)
        else:
            raise NotImplementedError(
                "lres_filter must be one of none/gaussian/uniform/median/maximum")
        return output 
Example #8
Source File: test_ndimage.py    From Computable with MIT License 6 votes vote down vote up
def test_rank12(self):
        expected = [[3, 3, 2, 4, 4],
                [3, 5, 2, 5, 1],
                [5, 5, 8, 3, 5]]
        footprint = [[1, 0, 1], [0, 1, 0]]
        for type in self.types:
            array = numpy.array([[3, 2, 5, 1, 4],
                                    [5, 8, 3, 7, 1],
                                    [5, 6, 9, 3, 5]], type)
            output = ndimage.rank_filter(array, 1,
                                                  footprint=footprint)
            assert_array_almost_equal(expected, output)
            output = ndimage.percentile_filter(array, 50.0,
                                                     footprint=footprint)
            assert_array_almost_equal(expected, output)
            output = ndimage.median_filter(array,
                                                    footprint=footprint)
            assert_array_almost_equal(expected, output) 
Example #9
Source File: neuro_dataset.py    From event-Python with MIT License 6 votes vote down vote up
def prepare_n_mnist(filename, is_filter, num_spikes, step_factor=1):
    """Creates images from the specified n mnist recording
    filename: path to the recording
    is_filter: True if median filtering should be applied to the constructed image
    num_spikes: number of unique spikes per image
    step_factor: proportional amount to shift before generating the next image
        1 would result in no overlapping events between images
        0.6 would result in the next image overlapping with 40% of the previous image
    returns: list of images, where each image is a 2d numpy array (height, width)
    """
    td = ev.read_dataset(filename)
    #td.show_td(100)
    td.data = stabilize(td)
    td.data = td.extract_roi([3, 3], [28, 28], True)
    images = make_td_images(td, num_spikes, step_factor)

    if is_filter:
        images = ndimage.median_filter(images, 3)

    #for image in images:
    #    cv2.imshow('img', image)
    #    cv2.waitKey(70)
    return images 
Example #10
Source File: neuro_dataset.py    From event-Python with MIT License 6 votes vote down vote up
def prepare_n_mnist_continuous(filename, is_filter, is_normalize=False):
    """Creates image with pixel values indicating probability of a spike
    filename: path to the recording
    is_filter: True if median filtering should be applied to the constructed image
    is_normalize: If True, the probabilities will be normalized to make the image more obvious
    returns: image (2d numpy array (height, width))
    """
    td = ev.read_dataset(filename)
    #td.show_td(100)
    td.data = stabilize(td)
    td.data = td.extract_roi([0, 0], [28, 28], True)
    #td.data = apply_tracking1(td)
    #td.data = apply_tracking2(td)
    #td.data = apply_tracking3(td)
    #td.data = td.extract_roi([3, 3], [28, 28], True)
    image = make_td_probability_image(td, 9, is_normalize)

    if is_filter:
        image = ndimage.median_filter(image, 3)

    #cv2.imshow('img', image)
    #cv2.waitKey(1)
    return image 
Example #11
Source File: helper.py    From sketchKeras with Apache License 2.0 5 votes vote down vote up
def show_active_img_and_save_denoise_filter2(name,img,path):
    mat = img.astype(np.float)
    mat[mat<0.1] = 0
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat=mat.astype(np.uint8)
    mat = ndimage.median_filter(mat, 1)
    cv2.imshow(name,mat)
    cv2.imwrite(path,mat)
    return 
Example #12
Source File: helper.py    From sketchKeras with Apache License 2.0 5 votes vote down vote up
def show_active_img_and_save_denoise_filter(name,img,path):
    mat = img.astype(np.float)
    mat[mat<0.18] = 0
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat=mat.astype(np.uint8)
    mat = ndimage.median_filter(mat, 1)
    cv2.imshow(name,mat)
    cv2.imwrite(path,mat)
    return 
Example #13
Source File: helper.py    From sketchKeras with Apache License 2.0 5 votes vote down vote up
def show_active_img_and_save_denoise(name,img,path):
    mat = img.astype(np.float)
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat=mat.astype(np.uint8)
    mat = ndimage.median_filter(mat, 1)
    cv2.imshow(name,mat)
    cv2.imwrite(path,mat)
    return 
Example #14
Source File: helper.py    From sketchKeras with Apache License 2.0 5 votes vote down vote up
def denoise_mat(img,i):
    return ndimage.median_filter(img, i) 
Example #15
Source File: line_seperate.py    From chamanti_ocr with Apache License 2.0 5 votes vote down vote up
def filter_noise(self, ):
        self.imgarr = nd.median_filter(self.imgarr, size=3) 
Example #16
Source File: grad_cam.py    From DeepDanbooru with MIT License 5 votes vote down vote up
def filter_grads(grads):
    return ndimage.median_filter(grads, 10) 
Example #17
Source File: sketch_keras_util.py    From Tag2Pix with MIT License 5 votes vote down vote up
def to_keras_enhanced(img):
    mat = img.astype(np.float)
    mat[mat<0.1] = 0
    mat = - mat + 1
    mat = mat * 255.0
    mat[mat < 0] = 0
    mat[mat > 255] = 255
    mat=mat.astype(np.uint8)
    mat = ndimage.median_filter(mat, 1)

    return mat 
Example #18
Source File: train.py    From fast-neural-style-keras with Apache License 2.0 5 votes vote down vote up
def display_img(i,x,style,is_val=False):
    # save current generated image
    img = x #deprocess_image(x)
    if is_val:
        #img = ndimage.median_filter(img, 3)

        fname = 'images/output/%s_%d_val.png' % (style,i)
    else:
        fname = 'images/output/%s_%d.png' % (style,i)
    imsave(fname, img)
    print('Image saved as', fname) 
Example #19
Source File: qps_rings.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def split_traces(self,ds,threshold=30000):
        self._prepare_find_jumps()
        ds = self._hf[ds]
        # first we remove a bit of noise, size is the number of averages
        #flt = gaussian_filter1d(ds,10)
        flt = median_filter(ds,size=3)
        #flt = ds
        # the sobel filter finds the "jumps" 
        sb=sobel(flt)
        for i in sb:
            self.qps_jpn_hight.append(float(i))
            
        #for i in flt: self.qps_jpn_spec.append(float(i))
        offset=ds[0]
        tr_num = 0
        tr_name = "qps_tr_"+str(tr_num)
        tr_obj =  self._hf.add_value_vector(tr_name, 
                                            folder = 'analysis', 
                                            x = self._x_co, 
                                            unit = 'Hz')
        keepout = 4
        for i,tr in enumerate(flt):
            keepout += 1
            if abs(sb[i])>threshold and keepout>3:
                keepout = 0
                # new trace
                tr_num +=1
                tr_name = "qps_tr_"+str(tr_num)
                tr_obj =  self._hf.add_value_vector(tr_name, 
                                                    folder = 'analysis', 
                                                    x =  self._x_co, 
                                                    unit = 'Hz')
                print tr , i
                #tr_obj.append(float(tr))
            else:
                if keepout>2:
                    tr_obj.append(float(tr-offset)) 
Example #20
Source File: defenses.py    From jpeg-defense with MIT License 5 votes vote down vote up
def median_filter(img_arr, size=3):
    return _median_filter(img_arr, size=size) 
Example #21
Source File: filters.py    From muDIC with MIT License 5 votes vote down vote up
def homomorphic_median(image, sigma=10):
    log_img = np.log(image)
    return np.exp(log_img - median_filter(log_img, int(sigma))) 
Example #22
Source File: test_filters.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_median_filter(self):
        d = np.random.randn(500, 500)
        os = np.empty([4] + list(d.shape))
        ot = np.empty_like(os)
        self.check_func_serial(4, sndi.median_filter, (d, 3), os)
        self.check_func_thread(4, sndi.median_filter, (d, 3), ot)
        assert_array_equal(os, ot) 
Example #23
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_rank08(self):
        array = numpy.array([[3, 2, 5, 1, 4],
                             [5, 8, 3, 7, 1],
                             [5, 6, 9, 3, 5]])
        expected = [[3, 3, 2, 4, 4],
                    [5, 5, 5, 4, 4],
                    [5, 6, 7, 5, 5]]
        output = ndimage.percentile_filter(array, 50.0, size=(2, 3))
        assert_array_almost_equal(expected, output)
        output = ndimage.rank_filter(array, 3, size=(2, 3))
        assert_array_almost_equal(expected, output)
        output = ndimage.median_filter(array, size=(2, 3))
        assert_array_almost_equal(expected, output) 
Example #24
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_rank04(self):
        array = numpy.array([3, 2, 5, 1, 4])
        expected = [3, 3, 2, 4, 4]
        output = ndimage.rank_filter(array, 1, size=3)
        assert_array_almost_equal(expected, output)
        output = ndimage.percentile_filter(array, 50, size=3)
        assert_array_almost_equal(expected, output)
        output = ndimage.median_filter(array, size=3)
        assert_array_almost_equal(expected, output) 
Example #25
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_rank02(self):
        array = numpy.array([1, 2, 3, 4, 5])
        output = ndimage.rank_filter(array, 1, size=[3])
        assert_array_almost_equal(array, output)
        output = ndimage.percentile_filter(array, 50, size=3)
        assert_array_almost_equal(array, output)
        output = ndimage.median_filter(array, (3,))
        assert_array_almost_equal(array, output) 
Example #26
Source File: test_ndimage.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_rank01(self):
        array = numpy.array([1, 2, 3, 4, 5])
        output = ndimage.rank_filter(array, 1, size=2)
        assert_array_almost_equal(array, output)
        output = ndimage.percentile_filter(array, 100, size=2)
        assert_array_almost_equal(array, output)
        output = ndimage.median_filter(array, 2)
        assert_array_almost_equal(array, output) 
Example #27
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_rank08(self):
        array = numpy.array([[3, 2, 5, 1, 4],
                                [5, 8, 3, 7, 1],
                                [5, 6, 9, 3, 5]])
        expected = [[3, 3, 2, 4, 4],
                [5, 5, 5, 4, 4],
                [5, 6, 7, 5, 5]]
        output = ndimage.percentile_filter(array, 50.0,
                                                    size=(2, 3))
        assert_array_almost_equal(expected, output)
        output = ndimage.rank_filter(array, 3, size=(2, 3))
        assert_array_almost_equal(expected, output)
        output = ndimage.median_filter(array, size=(2, 3))
        assert_array_almost_equal(expected, output) 
Example #28
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_rank04(self):
        array = numpy.array([3, 2, 5, 1, 4])
        expected = [3, 3, 2, 4, 4]
        output = ndimage.rank_filter(array, 1, size=3)
        assert_array_almost_equal(expected, output)
        output = ndimage.percentile_filter(array, 50, size=3)
        assert_array_almost_equal(expected, output)
        output = ndimage.median_filter(array, size=3)
        assert_array_almost_equal(expected, output) 
Example #29
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_rank02(self):
        array = numpy.array([1, 2, 3, 4, 5])
        output = ndimage.rank_filter(array, 1, size=[3])
        assert_array_almost_equal(array, output)
        output = ndimage.percentile_filter(array, 50, size=3)
        assert_array_almost_equal(array, output)
        output = ndimage.median_filter(array, (3,))
        assert_array_almost_equal(array, output) 
Example #30
Source File: test_ndimage.py    From Computable with MIT License 5 votes vote down vote up
def test_rank01(self):
        array = numpy.array([1, 2, 3, 4, 5])
        output = ndimage.rank_filter(array, 1, size=2)
        assert_array_almost_equal(array, output)
        output = ndimage.percentile_filter(array, 100, size=2)
        assert_array_almost_equal(array, output)
        output = ndimage.median_filter(array, 2)
        assert_array_almost_equal(array, output)