Return to Computer Vision Notebooks

Basics [Cython]



Basic functions and operations using Cython and Python.

0. Installation


Installation command for anaconda and pip:

$ conda install -c anaconda cython

or

$ pip install Cython

1. Compilation


A Cython source file has the name of the module followed by the extension .pyx. For example, given the source file examples_cy.pyx with a simple function which returns a string.

def hello_cython():
    return 'Hello, Cython!'

The following step consist of creating the setup.py, which will be responsible for the compilation process.

from setuptools import setup
from Cython.Build import cythonize

setup(
    name="Examples Cython",
    ext_modules=cythonize("examples_cy.pyx")
)

Given that, the compilation step is done by running the command:

$ python setup.py build_ext --inplace

2. Performance


The following example, we will try to approximate the value $\large\pi$ with the idea of $\\tan^{-1}1=\frac{\pi}{4}$ using the power series of arctan, defined by:

$$\large 4 \sum_{n=0}^{N}\frac{(-1)^n}{2n+1} \approx \pi $$

where $N$ tends to the infinity.

In the same Cython source file examples_cy.pyx, lets include the function and adapt it to be compiled.

cdef double pi_cy(int N):
    cdef double pi = 0
    cdef int n
    for n in range(N):
        pi += (-1)**n/(2*n + 1)
    return 4*pi

p.s.: compile it again running the command:

$ python setup.py build_ext --inplace

3. Cython and Jupyter Notebook


To enable support for Cython compilation in Jupyter Notebooks, we have to run firstly the command:

It will allow the C functions declaration inside cells, using the magic function %%cython for multiple lines.

p.s.: the function call must be within the same cell