import numpy as np import math cimport numpy as np cimport cython cdef extern from "../morphology/_pnpoly.h": int pnpoly(int nr_verts, double *xp, double *yp, double x, double y) @cython.boundscheck(False) @cython.wraparound(False) def bresenham(int y, int x, int y2, int x2): """Generate line pixel coordinates. Parameters ---------- y, x : int Starting position (row, column). y2, x2 : int End position (row, column). Returns ------- rr, cc : (N,) ndarray of int Indices of pixels that belong to the line. May be used to directly index into an array, e.g. ``img[rr, cc] = 1``. """ cdef np.ndarray[np.int32_t, ndim=1, mode="c"] rr, cc cdef int steep = 0 cdef int dx = abs(x2 - x) cdef int dy = abs(y2 - y) cdef int sx, sy, d, i if (x2 - x) > 0: sx = 1 else: sx = -1 if (y2 - y) > 0: sy = 1 else: sy = -1 if dy > dx: steep = 1 x,y = y,x dx,dy = dy,dx sx,sy = sy,sx d = (2 * dy) - dx rr = np.zeros(int(dx) + 1, dtype=np.int32) cc = np.zeros(int(dx) + 1, dtype=np.int32) for i in range(dx): if steep: rr[i] = x cc[i] = y else: rr[i] = y cc[i] = x while d >= 0: y = y + sy d = d - (2 * dx) x = x + sx d = d + (2 * dy) rr[dx] = y2 cc[dx] = x2 return rr, cc @cython.boundscheck(False) @cython.wraparound(False) @cython.nonecheck(False) def polygon(verts, shape=None): """Generate coordinates of pixels within polygon. Parameters ---------- verts : Nx2 ndarray (row, col) coordinates shape : tuple, optional image shape which is used to determine maximum extents of output pixel coordinates. This is useful for polygons which exceed the image size. By default the full extents of the polygon are used. Returns ------- rr, cc : ndarray of int Pixel coordinates of polygon. May be used to directly index into an array, e.g. ``img[rr, cc] = 1``. """ cdef int nr_verts = verts.shape[0] cdef int minr = max(0, verts[:,0].min()) cdef int maxr = math.ceil(verts[:,0].max()) cdef int minc = max(0, verts[:,1].min()) cdef int maxc = math.ceil(verts[:,1].max()) # make sure output coordinates do not exceed image size if shape is not None: maxr = min(shape[0]-1, maxr) maxc = min(shape[1]-1, maxc) cdef int r, c #: make contigous arrays for r, c coordinates verts = verts.astype('double') cdef np.ndarray contiguous_rdata = verts[:,0].copy(order='C') cdef np.ndarray contiguous_cdata = verts[:,1].copy(order='C') cdef np.double_t* rptr = contiguous_rdata.data cdef np.double_t* cptr = contiguous_cdata.data #: output coordinate arrays rr = list() cc = list() for r in range(minr, maxr+1): for c in range(minc, maxc+1): if pnpoly(nr_verts, cptr, rptr, c, r): rr.append(r) cc.append(c) return np.array(rr), np.array(cc)