[Numpy-discussion] C++ Example

David Cournapeau cournape@gmail....
Sat Mar 3 18:38:53 CST 2012


On Sat, Mar 3, 2012 at 8:07 AM, Luis Pedro Coelho <lpc@cmu.edu> wrote:
> Hi,
>
> I sort of missed the big C++ discussion, but I'd like to give some examples of
> how writing code can become much simpler if you are based on C++. This is from
> my mahotas package, which has a thin C++ wrapper around numpy's C API
>
> https://github.com/luispedro/mahotas/blob/master/mahotas/_morph.cpp
>
> and it implements multi-type greyscale erosion.
>
>
> // numpy::aligned_array wraps PyArrayObject*
> template<typename T>
> void erode(numpy::aligned_array<T> res,
>                                numpy::aligned_array<T> array,
>                                numpy::aligned_array<T> Bc) {
>
>
>        // Release the GIL using RAII
>    gil_release nogil;
>    const int N = res.size();
>    typename numpy::aligned_array<T>::iterator iter = array.begin();
>    // this is adapted from scipy.ndimage.
>    // it implements the convolution-like filtering.
>    filter_iterator<T> filter(res.raw_array(),
>                                                                                Bc.raw_array(),
>                                                                                EXTEND_NEAREST,
>                                                                                is_bool(T()));
>    const int N2 = filter.size();
>    T* rpos = res.data();
>
>    for (int i = 0; i != N; ++i, ++rpos, filter.iterate_both(iter)) {
>        T value = std::numeric_limits<T>::max();
>        for (int j = 0; j != N2; ++j) {
>            T arr_val = T();
>            filter.retrieve(iter, j, arr_val);
>            value = std::min<T>(value, erode_sub(arr_val, filter[j]));
>        }
>        *rpos = value;
>    }
> }
>
> If you compare this with the equivalent scipy.ndimage function, which is very
> good C code (but mostly write-only—in fact, ndimage has not been maintainable
> because it is so hard [at least for me, I've tried]):

The fact that this is good C is matter of opinon :)

I don't think the code is comparable either - some of the stuff done
in the C code is done in the C++ code your are calling. The C code
could be significantly improved. Even more important here: almost none
of this code should be written anymore anyway, C++ or not. This is
really the kind of code that should be done in cython, as it is mostly
about wrapping C code into the python C API.

cheers,

David


More information about the NumPy-Discussion mailing list