Noob Saibot | 1 Jun 05:07 2014
Picon

Python C-API Metaclass + Cython = "Variable type `PyTypeObject` is Incomplete"

I'm tying to make cdef-metatyped classes for use in cython. Since cython 0.20 currently doesn't support them, i thought of building the metaclass from scratch using python's C-API, including it in cython, and proceeding as normal; but everytime i try to compile, it fails with many errors. I believe the principle culprit is a Variable type `PyTypeObject` is Incomplete error.

Attached is what i came up with (It's not long at all). What am i missing? ANY help would be greatly appreciated.

Machine: 64-Bit Windows
Python Version: 2.7
Cython Version: 0.20

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

C:\Python27\Lib\site-packages\kivy\uix>python setup.py build_ext --inplace
Compiling widget.pyx because it changed.
Cythonizing widget.pyx

Error compiling Cython file:
------------------------------------------------------------
...

cdef extern from "_metakivy.h":
    object initmetaclass(object type, object op, object subtype, object args, ob
ject kwargs, object factory)
    ctypedef extern struct KvTypeType:
        pass
    cdef extern PyTypeObject KvType_Type
                            ^
------------------------------------------------------------

widget.pxd:11:29: Variable type 'PyTypeObject' is incomplete

Error compiling Cython file:
------------------------------------------------------------
...
        pass
    cdef extern PyTypeObject KvType_Type

cdef object WidgetBase = initmetaclass(KvTypeType, KvType_Type, <PyTypeObject *>
EventDispatcher, NULL, NULL, Factory)

cdef class Widget(WidgetBase):
    ^
------------------------------------------------------------

widget.pxd:15:5: 'WidgetBase' is not a type name

Error compiling Cython file:
------------------------------------------------------------
...
    object initmetaclass(object type, object op, object subtype, object args, ob
ject kwargs, object factory)
    ctypedef extern struct KvTypeType:
        pass
    cdef extern PyTypeObject KvType_Type

cdef object WidgetBase = initmetaclass(KvTypeType, KvType_Type, <PyTypeObject *>
EventDispatcher, NULL, NULL, Factory)
                                                ^
------------------------------------------------------------

widget.pxd:13:49: 'KvTypeType' is not a constant, variable or function identifie
r
Compiler crash in AnalyseExpressionsTransform

File 'Nodes.py', line 388, in analyse_expressions: StatListNode(widget.pxd:1:0)
File 'Nodes.py', line 4511, in analyse_expressions: SingleAssignmentNode(widget.
pxd:13:5)
File 'Nodes.py', line 4616, in analyse_types: SingleAssignmentNode(widget.pxd:13
:5)
File 'ExprNodes.py', line 4416, in analyse_types: SimpleCallNode(widget.pxd:13:3
8,
    analysed = True,
    result_is_used = True,
    use_managed_ref = True)
File 'ExprNodes.py', line 4522, in analyse_c_function_call: SimpleCallNode(widge
t.pxd:13:38,
    analysed = True,
    result_is_used = True,
    use_managed_ref = True)
File 'ExprNodes.py', line 1622, in coerce_to: NameNode(widget.pxd:13:62,
    cf_maybe_null = True,
    initialized_check = True,
    is_name = True,
    name = u'KvType_Type',
    result_is_used = True,
    use_managed_ref = True)
File 'ExprNodes.py', line 755, in coerce_to: NameNode(widget.pxd:13:62,
    cf_maybe_null = True,
    initialized_check = True,
    is_name = True,
    name = u'KvType_Type',
    result_is_used = True,
    use_managed_ref = True)
File 'ExprNodes.py', line 10681, in __init__: CoerceToPyTypeNode(is_temp = 1,
    result_is_used = True,
    use_managed_ref = True)

Compiler crash traceback from this point on:
  File "C:\Python27\lib\site-packages\Cython\Compiler\ExprNodes.py", line 10681,
 in __init__
    if not arg.type.create_to_py_utility_code(env):
  File "C:\Python27\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 2881,
 in create_to_py_utility_code
    for member in self.scope.var_entries:
AttributeError: 'NoneType' object has no attribute 'var_entries'

Error compiling Cython file:
------------------------------------------------------------
...
cdef class Widget(WidgetBase):
    ^
------------------------------------------------------------

widget.pyx:1:5: 'WidgetBase' is not a type name
Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    ext_modules = cythonize('widget.pyx'),)
  File "C:\Python27\lib\site-packages\Cython\Build\Dependencies.py", line 785, i
n cythonize
    cythonize_one(*args[1:])
  File "C:\Python27\lib\site-packages\Cython\Build\Dependencies.py", line 902, i
n cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: widget.pyx

C:\Python27\Lib\site-packages\kivy\uix>
Attachment (_metakivy.c): text/x-csrc, 2658 bytes
Attachment (_metakivy.h): text/x-chdr, 355 bytes
Attachment (widget.pxd): application/octet-stream, 561 bytes
Attachment (widget.pyx): application/octet-stream, 40 bytes
刘振海 | 30 May 15:32 2014
Picon

directives like wraparound, boundscheck etc is not supported in pure python model

here is the code:
test.py
def f(arr):
  return arr[0]

test.pxd
import cython
 <at> cython.wraparound(False)
 <at> cython.boundscheck(False)
cdef f(double[:,::1] arr) 

I try to fix this, but I get no cule.
this can be solved by using cmd options like cython -X wraparound=False to overcome.

--

-- 

--- 
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Robert Bradshaw | 30 May 03:06 2014
Picon

Cython 0.20.2 beta

I've pushed a beta for the 0.20.2 can be found at
http://cython.org/release/Cython-0.20rc1.tar.gz . This is a
bugfix-only release, more development is going on for 0.21 which will
also be released soon. Note, however, that the 0.20.x branch is the
last to support older versions of Python (pre 2.6 or 3.2).

Please try it out and report back.

- Robert

Features added

Some optimisations for set/frozenset instantiation.
Support for C++ unordered_set and unordered_map.

Bugs fixed

Access to attributes of optimised builtin methods (e.g.
[].append.__name__) could fail to compile.
Memory leak when extension subtypes add a memory view as attribute to
those of the parent type without having Python object attributes or a
user provided dealloc method.
Compiler crash on readonly properties in "binding" mode.
Auto-encoding with c_string_encoding=ascii failed in Py3.3.
Crash when subtyping freelist enabled Cython extension types with
Python classes that use __slots__.
Freelist usage is restricted to CPython to avoid problems with other
Python implementations.
Memory leak in memory views when copying overlapping, contiguous slices.
Format checking when requesting non-contiguous buffers from
cython.array objects was disabled in Py3.
C++ destructor calls in extension types could fail to compile in clang.
Buffer format validation failed for sequences of strings in structs.
Docstrings on extension type attributes in .pxd files were rejected.

--

-- 

--- 
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Yuxiang Wang | 29 May 18:45 2014
Picon

Use Cython with OpenMP in Windows

Dear all,

I have a question: how do I use Cython with OpenMP in Windows?

According to this link https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows   I would be better off using MSVC. However, with VC++ 2010 Express Edition, OpenMP support is not included. I also tried to install Windows SDK, but the same error (no omp.h) pops up again.

I don't think I am the first one who ran into this... Could anyone give me a hint?

Thank you!

Shawn

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jacky Wang | 29 May 09:51 2014
Picon

0.20.2 in PyPI?

Hi there,

I noticed that Cython on PyPI is pretty old (3.5 months, 0.20.1) and on github's 0.20.x branch 0.20.2 is already tagged.  Is there anyone knows when it will be released to PyPI?

Thanks,
Jacky

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Julien Delafontaine | 28 May 14:16 2014
Picon

"Call with wrong number of arguments" after compilation

Hi again,

I am trying to import a Cython function into a Python script using a "cpdef" declaration.
In a script B.pyx, I have defined:

cpdef count(object a, object b, int c, int d):
    <do stuff>

I compile B.pyx to obtain B.c and B.so.
In A.py (which does not have another "count()" function), I do:

from B import count
==> ERROR: "Assignment to non-lvalue 'count'".

Ok. With a star maybe:

from B import *    # works now
def otherfunction():
    ...
    count(obj1, obj2, 3, 4)
==> ERROR: "Call with wrong number of arguments (expected 5, got 4)".

B.c shows things like:

static PyObject *__pyx_f_11B_count(PyObject *, PyObject *, int, int, int __pyx_skip_dispatch); /*proto*/

It has a 5th argument "int __pyx_skip_dispatch".
So I tried to add a "0" as 5th argument (well, better to try everything), then:

count(obj1, obj2, 3, 4, 0)
==> ERROR: "count() takes exactly 4 positional arguments (5 given)".

A bit contradictory... How do I get out of it?
Is it because the call is inside a function? A "self" missing somewhere?

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Julien Delafontaine | 28 May 11:34 2014
Picon

Re: pure Python mode: .pxd and <at> locals

I think this is a place where "newbies" can help a lot -- you know better than the core developers what initial explanation is needed. Perhaps you could write up a tutorial following your process in "cythonizing" your code in pure-python mode.

Of course, it would require review by the "experts", but I find we're  a lot more likley to get helpful comments and review than getting one of them to write the whole thing from scratch!

I actually wanted to do so anyway, because I will report my work on a bioinformatics blog (in french), as I often do.
At the moment though, I can't go really far following the official doc. What I would write already looks like that, and maybe it is half wrong:

* From A.py, how to create the setupA.py, compile and see how you gain 20% speed.
--[No idea why there is a "cythonize" function but other examples with "Extension", doing the same while "cythonize" is more limited]--
* Then two methods:

a) Create A.pxd, that is not meant for it but can be used nonetheless to override python methods by cython ones. It has limitations - to be listed - over method b).
Do not rename to A.pyx because it would ignore A.pxd at compilation time.
To override functions, one must use "cpdef inline".
To override classes, one must use
cdef class <name>:
    cpdef <type> <future attribute>

For instance, the python class

class C(object):
    def __init__(self, a=0, b=0):
        self.a = a
        self.b = b

can be overriden by specifying the following in the .pxd:

cdef class C:
    cpdef int a,b

so that it is in the end equivalent to the folowing Cython code:

cdef class C(object):
    cdef int a,b
    def  __init__(self, int a=0, int b=0):
        self.a = a
        self.b = b

--[Btw. no idea if it is necessary to specify the type at "cdef int a,b" as well as in the __init__ arguments, in the Cython code]--

b) [Not really full Python but useful if some parts are not subject to changes]
Write B.pyx. Move some functions that need optimization from A.py to B.pyx. Rewrite functions in B.pyx using Cython's syntax. Also, "to make them accessible from Python code, you need to declare them as "public" or "readonly" (source) [uh? I think "cpdef" does that]. Compile B.pyx with a separate setupB.py. Then in A.py import (not cimport because it is only when there is a .pxd) functions and classes from B. Finally, compile A.py with setupA.py.

* How to debug (still trying).


To my opinion the doc lacks an example of a full class with __init__, __cinit__, arguments to __init__ and their default values.

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Daniel DeSousa | 27 May 20:05 2014
Picon

Bug Inquiry: Iterator Override

When I attempt to iterate over a collection like std::map in cython, cython will generate compiled code which copies the collection (even if accessed by reference) which may silently work but fails the visual studio iterator debug assertions.

Wrapped:

cdef extern from "object_set.h" namespace "::":
    cppclass obj_set:
        const map_t & objects() nogil except +
        const obj & get_object(int index) nogil except +


Wrapper:

    cpdef dict objects(self):
        cdef dict d = dict()
        cdef map[int, c_obj].iterator it = self.thisptr.objects().begin()
        while it != self.thisptr.objects().end():
             pass
        return d

Generated Code (output.cpp:1145):

__pyx_t_12c_object_set_map_t __pyx_t_3;
...
  /* "object_set.pyx":26
 *     cpdef dict objects(self):
 *         cdef dict d = dict()
 *         cdef map[int, c_obj].iterator it = self.thisptr.objects().begin()             # <<<<<<<<<<<<<<
 *         while it != self.thisptr.objects().end():
 *              pass
 */
  try {
    __pyx_t_3 = __pyx_v_self->thisptr->objects();
  } catch(...) {
    __Pyx_CppExn2PyErr();
    {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  }
  __pyx_v_it = __pyx_t_3.begin();

  /* "object_set.pyx":27
 *         cdef dict d = dict()
 *         cdef map[int, c_obj].iterator it = self.thisptr.objects().begin()
 *         while it != self.thisptr.objects().end():             # <<<<<<<<<<<<<<
 *              pass
 *         return d
 */
  while (1) {
    try {
      __pyx_t_3 = __pyx_v_self->thisptr->objects();
    } catch(...) {
      __Pyx_CppExn2PyErr();
      {__pyx_filename = __pyx_f[0]; __pyx_lineno = 27; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
    }
    __pyx_t_4 = ((__pyx_v_it != __pyx_t_3.end()) != 0);
    if (!__pyx_t_4) break;
  }


Notice that it overrides the map (copying it desspite being pass by reference). This might work when built because it copies over to the same memory location, but it contradicts what appears to be the case in cython and fails visual studio debug iterator assertions (building under debug and calling the method throws the assertion).

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Attachment (c_object_set.pxd): application/octet-stream, 420 bytes
Attachment (object_set.h): text/x-chdr, 532 bytes
Attachment (object_set.pyx): application/octet-stream, 835 bytes
Attachment (object_set.pxd): application/octet-stream, 314 bytes
Attachment (output.cpp): text/x-c++src, 104 KiB
Daniel DeSousa | 27 May 19:51 2014
Picon

Bug Inquiry: Pass by Reference Method Assumes Default Constructor

Inquiry as to whether this seems to be a bug. When I wrap a function which returns a reference to a wrapped object, cython compiled c code assumes the presence of a default constructor:

Wrapped (c_object_set.pyd):

cdef extern from "object_set.h" namespace "::":
    cppclass obj_set:
        const obj & get_object(int index) nogil except +

Wrapper Implementation (object_set.pyx):

cpdef obj get_object(self, int index):
    return obj(self.thisptr.get_object(index).value())

Produces the following code (output.cpp:1122):

::::obj __pyx_t_4;

All the files are attached. Built with:

cython -Werror -Wextra -2 --cplus object_set.pyx -I . -o output.cpp -X boundscheck=False,wraparound=False,cdivision=True,always_allow_keywords=False,embedsignature=True

 It seems like it should not assume the presence of a default constructor if I pass by reference. Maybe one of the contributors could comment.

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Attachment (object_set.pyx): application/octet-stream, 586 bytes
Attachment (c_object_set.pxd): application/octet-stream, 315 bytes
Attachment (object_set.h): text/x-chdr, 532 bytes
Attachment (output.cpp): text/x-c++src, 105 KiB
Attachment (object_set.pxd): application/octet-stream, 284 bytes
mdboom | 27 May 17:06 2014
Picon

Possible bug compiling with a Unicode path

Over at the astropy project we have discovered a possible bug when compiling Cython modules that are part of a package where the source path contains non-ascii characters.

https://github.com/astropy/astropy/issues/2564


To reproduce, set up a package with the following structure:

. ├── helloworld │ ├── helloworld.pyx │ └── __init__.py ├── setup.py

setup.py contains:

from distutils.core import setup, Extension from Cython.Distutils import build_ext setup( cmdclass = { 'build_ext': build_ext }, ext_modules = [Extension("helloworld.helloworld", sources=["helloworld/helloworld.pyx"])] )

helloworld.pyx contains:

cimport numpy as np print "Hello World"

__init__.py is empty.

(All of this is also attached in a tarball).

It crashes with the following:

Error compiling Cython file: ------------------------------------------------------------ ... import numpy as np cimport numpy as np ^ ------------------------------------------------------------ helloworld/helloworld.pyx:2:8: Compiler crash in AnalyseDeclarationsTransform File 'ModuleNode.py', line 101, in analyse_declarations: ModuleNode(helloworld.pyx:1:0, full_module_name = 'helloworld.helloworld') File 'Nodes.py', line 382, in analyse_declarations: StatListNode(helloworld.pyx:1:0) File 'Nodes.py', line 382, in analyse_declarations: StatListNode(helloworld.pyx:2:8) File 'Nodes.py', line 6608, in analyse_declarations: CImportStatNode(helloworld.pyx:2:8, as_name = u'np', module_name = u'numpy') Compiler crash traceback from this point on: File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Compiler/Nodes.py", line 6608, in analyse_declarations module_scope = env.find_module(self.module_name, self.pos) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Compiler/Symtab.py", line 1101, in find_module module_name, relative_to = self.parent_module, pos = pos) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Compiler/Main.py", line 132, in find_module pxd_pathname = self.find_pxd_file(qualified_name, pos) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Compiler/Main.py", line 184, in find_pxd_file pxd = self.search_include_directories(qualified_name, ".pxd", pos, sys_path=True) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Compiler/Main.py", line 225, in search_include_directories tuple(self.include_directories), qualified_name, suffix, pos, include, sys_path) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Utils.py", line 16, in wrapper res = cache[args] = f(*args) File "/home/mdboom/python/lib/python2.7/site-packages/Cython/Utils.py", line 103, in search_include_directories path = os.path.join(dir, dotted_filename) File "/home/mdboom/python/lib64/python2.7/posixpath.py", line 80, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 36: ordinal not in range(128) building 'helloworld.helloworld' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/helloworld gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.7 -c helloworld/helloworld.c -o build/temp.linux-x86_64-2.7/helloworld/helloworld.o helloworld/helloworld.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation. #error Do not use this file, it is the result of a failed Cython compilation. ^ error: command 'gcc' failed with exit status 1

Is this a bonafide bug?

Mike

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Attachment (cython-unicode-crash.tgz): application/x-gtar, 555 bytes
Roberto Medeiros de Souza | 26 May 21:50 2014
Picon

Help optimizing cython code

Hi,

I know how to programm Python/NumPy and I am trying to learn to program Cython in order to make my code run faster. Does anyone have any tips on how I can optimize the code below?

Thanks in advance!
Roberto

import numpy as np
cimport cython
cimport numpy as np


<at> cython.boundscheck(False)
<at> cython.wraparound(False)


cdef inline int int_min(int a, int b): return a if a <= b else b


cdef int anc(Py_ssize_t x, Py_ssize_t h, np.ndarray[np.int_t, ndim=1, negative_indices=False] par, np.ndarray[np.int_t, ndim=1, negative_indices=False] f):
  cdef int par_x = par[x]
  while par_x != x and h <= f[par_x]:
    x  = levelRoot(par_x, par, f)
    par_x = par[x]
  return x
   
cdef int levelRoot(Py_ssize_t x, np.ndarray[np.int_t, ndim=1] par, np.ndarray[np.int_t, ndim=1] f):
  cdef int par_x = par[x]
  if par_x == x or f[x] != f[par_x]:
    return x
  else:
    par[x] = levelRoot(par_x,par,f)  
    return par[x]
   
cdef merge(Py_ssize_t x, Py_ssize_t y,  np.ndarray[np.int_t, ndim=1, negative_indices=False] par, np.ndarray[np.int_t, ndim=1] f, np.ndarray[np.int_t, ndim=1, negative_indices=False] area):
  cdef Py_ssize_t s = int_min(f[x],f[y])
  x = anc(x,s,par,f)
  y = anc(y,s,par,f)
  cdef Py_ssize_t z    
  if f[x] < f[y]: x,y = y,x
  while x != y and par[x]!= x:
    z = par[x]
    par[x] = y
    if f[x] == f[y]:
      area[y] += area[x]
      area[x] = 0
    x = anc(y, f[z], par,f)
    y = anc(z,f[z],par,f)
  if x != y:
    par[x] = y
    if f[x] == f[y]:
      area[y] += area[x]
      area[x] = 0
  return  


cdef Nlut(int H,int W, np.ndarray[np.int_t, ndim=2, negative_indices=False] off):
  """
  Neighbors LUT
  Receives the image shape and an array of offsets
  Returns an array of neighbors neighbors
  neighbors[p] are the neighbors of pixel p
  """
  cdef int n = H*W
  cdef np.ndarray  hi = np.arange(H, dtype = np.int).reshape(-1,1)
  cdef np.ndarray wi = np.arange(W, dtype = np.int).reshape(1,-1)
  hoff = off[:,0]
  woff = off[:,1]
 
  h = hi + off[:,0].reshape(-1,1,1)
  w = wi + woff.reshape(-1,1,1)
  h[(h<0) | (h>=H)] = n
  w[(w<0) | (w>=W)] = n
  cdef np.ndarray[np.int_t, ndim=2, negative_indices=False] neighbors = np.clip(h * W + w,0,n).reshape(off.shape[0],-1).transpose()
  return neighbors

   
cdef se2off(np.ndarray Bc):
  """
  Converts structuring element to list of neighbors offsets in graph image
  """
  cdef int h = Bc.shape[0]
  cdef int w = Bc.shape[1]
  cdef int hc = h/2
  cdef int wc = w/2
 
  cdef np.ndarray B = Bc.copy()
  B[hc,wc] = 0  # remove origin
  cdef np.ndarray off = np.transpose(B.nonzero()) - np.array([hc,wc])
  i = off[:,0] * w + off[:,1]
  return off[i<0,:]  # 2 columns x n. of neighbors rows
  #return off


def mtuf(np.ndarray[np.int_t, ndim=2, negative_indices=False] I, np.ndarray[np.int_t, ndim=2, negative_indices=False] Bc):
 
  s = I.shape
  cdef Py_ssize_t p
  cdef Py_ssize_t i
  cdef Py_ssize_t j
  cdef Py_ssize_t nb
  cdef Py_ssize_t nneighbors
  # Armazena o shape e o tipo da imagem
  cdef  int fsize = I.size
  fd = I.dtype
  cdef np.ndarray[np.int_t, ndim=1] f = I.ravel()
 
 
  # Aumenta a imagem para que na posicao dos vizinhos invalidos tenha valor -1
  #f = f.ravel()
 
  # Inicializa o array que aramazena as areas e os parents
  cdef np.ndarray[np.int_t, ndim=1, negative_indices=False] par
  cdef np.ndarray[np.int_t, ndim=1, negative_indices=False] area
  par = np.arange(fsize, dtype = np.int)
  area    = np.ones(fsize,dtype = np.int)
 
  # Calcula os vizinhos
  cdef np.ndarray[np.int_t, ndim=2, negative_indices=False] neighbors
  neighbors = Nlut(s[0],s[1],se2off(Bc) )
  # Ordenacao lexografica dos pixels, primeiro pelo nivel de cinza, seguido pela posicao do
  # pixel no array
  cdef np.ndarray[np.int_t, ndim=1, negative_indices=False] ordered_pixels
  ordered_pixels = np.lexsort((-par,f))[::-1]
  nneighbors = neighbors.shape[1]
  for i in xrange(fsize):
    p = ordered_pixels[i]
    for j in xrange(nneighbors):
      nb = neighbors[p,j]
      if nb != fsize: merge(p,nb,par,f,area)
  return par,area

 

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gmane