Exemplo n.º 1
0
def _complex_dblquad(func, a, b, gfun, hfun, kwargs={}):
    """Integrate real and imaginary part of the given function."""
    if cython_imported and cython.compiled:
        # pure python formulation of: cdef void *f_ptr = <void*>func
        f_ptr = cython.declare(cython.p_void, cython.cast(cython.p_void, func))

        func_capsule = PyCapsule_New(f_ptr, cython.NULL, cython.NULL)

        current_module = sys.modules[__name__]

        ll_real_2d_func_c = LowLevelCallable.from_cython(current_module,
                                                         '_real_2d_func_c',
                                                         func_capsule)
        ll_imag_2d_func_c = LowLevelCallable.from_cython(current_module,
                                                         '_imag_2d_func_c',
                                                         func_capsule)
        real, real_tol = dblquad(ll_real_2d_func_c, a, b, gfun, hfun, **kwargs)
        imag, imag_tol = dblquad(ll_imag_2d_func_c, a, b, gfun, hfun, **kwargs)
    else:
        real, real_tol = dblquad(
            _real_2d_func, a, b, gfun, hfun, (func,), **kwargs)
        imag, imag_tol = dblquad(
            _imag_2d_func, a, b, gfun, hfun, (func,), **kwargs)

    return real + 1j*imag, real_tol, imag_tol
Exemplo n.º 2
0
def erosion_fast(image, footprint):
    out = ndimage.generic_filter(
            image,
            LowLevelCallable.from_cython(sys.modules['test9'], name='erosion_kernel'),
            footprint=footprint
    )
    return out   
Exemplo n.º 3
0
def __count_votes(im, out, size, invert):
    """
    Count the votes for each pixel in a size-by-size region around each one, saving the totals to
    out. If invert is supplied, every pixel less than the values for it, otherwise every pixel
    greater than it votes for it.

    REFERENCES
      1. Eramian M and Mould D, 2005, "Histogram Equalization using Neighborhood Metrics",
         Proceedings of the Second Canadian Conference on Computer and Robot Vision.
    """
    if is_on_gpu(im):
        voting = __get_count_votes_cupy_kernel(invert)

    else:
        # Try to use the Cython functions if possible - they are ~160x faster!
        try:
            from scipy import LowLevelCallable
            import hist.exact.__basic as cy
            voting = LowLevelCallable.from_cython(
                cy, 'vote_lesser' if invert else 'vote_greater')
        except ImportError:
            # Fallback
            from numpy import empty, greater, less
            compare = greater if invert else less
            tmp = empty(size**im.ndim, bool)
            mid = tmp.size // 2
            voting = lambda x: compare(x[mid], x, tmp).sum()

    # Once we get the appropriate voting function we can call generic filter
    get_ndimage_module(im).generic_filter(im, voting, size, output=out)
Exemplo n.º 4
0
def bilateral_filter(im, size=None, sigma_r=None, sigma_d=1, **kwargs):
    """
    Bilaterally filter an image. Uses Gaussian kernels for the spatial and intensity filters.

    im is the image to filter, must be grayscale but can be any dimension
    size is the kernel size, must be odd and >=3, defaults to int(max(5, 2*ceil(3*sigma_d)+1)).
    sigma_r is the range/intensity standard deviation, defaults to image standard deviation.
    sigma_d is the domain/spatial standard deviation, default to 1.
    other keyword arguments are passed to scipy.ndimage.generic_filter.

    This attempts to use a Cython optimized function if possible. Additionally in common cases many
    parts are computed to greatly speed up the function.

    REFERENCES
     1. Tomasi C and Manduchi R, 1998, "Bilateral filtering for gray and color images". Sixth
        International Conference on Computer Vision. pp. 839–846.
     2. R A and Wilscu M, 2008, "Enhancing Contrast in Color Images Using Bilateral Filter and
        Histogram Equalization Using Wavelet Coefficients", 2008 Second International Conference on
        Future Generation Communication and Networking Symposia.
    """
    from scipy.ndimage import generic_filter

    if sigma_r is None: sigma_r = im.std()
    if size is None:
        size = int(max(5, 2*ceil(3*sigma_d)+1))
    elif size < 3 or size%2 != 1:
        raise ValueError(size)

    # Calculate the kernels
    spatial, scale, inten_lut = __bilateral_kernels(im.dtype, im.ndim, size, sigma_r, sigma_d)

    try:
        # Try to import Cython optimized code - 20 to 75x faster
        from scipy import LowLevelCallable
        import hist.exact.__bilateral_cy as cy
        _bilateral_filter = LowLevelCallable.from_cython(
            cy, 'bilateral_filter' if inten_lut is None else 'bilateral_filter_inten_lut',
            cy.get_user_data(spatial, scale, inten_lut)) # pylint: disable=c-extension-no-member
    except ImportError:
        # Fallback to pure Python function
        # Note: it seems the pure Python function actually gets slower with the intensity LUT
        def _bilateral_filter(data):
            diff = data - data[data.size // 2]
            weight = exp(diff*diff*scale) * spatial
            return dot(data, weight) / weight.sum()

    return generic_filter(im, _bilateral_filter, size, **kwargs)
Exemplo n.º 5
0
import numpy as np
import pandas as pd
from scipy import LowLevelCallable
from scipy.integrate import quad
from toolz import memoize

import textnets as tn

from .corpus import TidyText
from .fca import FormalContext
from .viz import decorate_plot

try:
    from . import _ext  # type: ignore

    integrand = LowLevelCallable.from_cython(_ext, "df_integrand")
except ImportError:

    def integrand(x: float, degree: int) -> float:
        """Fallback version of integrand function for the disparity filter."""
        return (1 - x) ** (degree - 2)

    warn("Could not import compiled extension, backbone extraction will be slow.")


class TextnetBase:
    """
    Base class for `Textnet` and `ProjectedTextnet`.

    Attributes
    ----------
Exemplo n.º 6
0
def get_cy_callback(module_name):
    lib = import_module(module_name)
    return LowLevelCallable.from_cython(
        lib,
        'f')  # , signature='double (int, double *, void *)')  # , user_data)
Exemplo n.º 7
0
# Example from https://ilovesymposia.com/2017/03/12/scipys-new-lowlevelcallable-is-a-game-changer/

import contextlib
import time

from scipy import ndimage as ndi
import numpy as np

from scipy import LowLevelCallable
import callable

image = np.random.random((2048, 2048))
footprint = np.array([[0, 1, 0],
                      [1, 1, 1],
                      [0, 1, 0]], dtype=bool)

c = LowLevelCallable.from_cython(callable, "nbmin")
ndi.generic_filter(image, c, footprint=footprint)