ENH: Whitespace cleanup.

This commit is contained in:
Stefan van der Walt
2011-11-30 10:55:57 -08:00
parent bea1b751d2
commit 053b27e623
2 changed files with 56 additions and 57 deletions
+32 -32
View File
@@ -1,11 +1,11 @@
#include <Python.h>
#include "numpy/arrayobject.h"
static char _find_contours_doc[] =
static char _find_contours_doc[] =
"This module defines C helper functions for find_contours";
static char iterate_and_store_doc[] =
static char iterate_and_store_doc[] =
"iterate_and_store(array, level, vertex_connect_high)\n\
\n\
Iterate across the given array in a marching-squares fashion, looking for\n\
@@ -51,32 +51,32 @@ face+vertex connected into objects; otherwise low-valued pixels are.";
return NULL; \
} \
char res = PyList_Append(arc_list, tuple); \
Py_DECREF(tuple); \
if (res < 0) { \
Py_DECREF(tuple); \
if (res < 0) { \
Py_DECREF(double_array); \
Py_DECREF(arc_list); \
return NULL; \
} \
return NULL; \
} \
}
#define ADD_SEGMENT(START, END) { \
double output0, output1; \
START \
ADD_TUPLE \
END \
ADD_TUPLE \
END \
ADD_TUPLE \
}
static PyObject*
iterate_and_store(PyObject *self, PyObject *args)
{
PyObject* array;
double level;
int vertex_connect_high;
if (!PyArg_ParseTuple(args, "Odi:iterate_and_store", &array, &level,
&vertex_connect_high)) {
return NULL;
}
PyObject* array;
double level;
int vertex_connect_high;
if (!PyArg_ParseTuple(args, "Odi:iterate_and_store", &array, &level,
&vertex_connect_high)) {
return NULL;
}
PyObject* double_array = PyArray_FromAny(array,
PyArray_DescrFromType(NPY_DOUBLE), 2, 2, NPY_CONTIGUOUS | NPY_ALIGNED,
@@ -84,14 +84,14 @@ iterate_and_store(PyObject *self, PyObject *args)
if (!double_array) {
return NULL;
}
npy_intp *dims = PyArray_DIMS(double_array);
if (dims[0] < 2 || dims[1] < 2) {
Py_DECREF(double_array);
PyErr_SetString(PyExc_ValueError, "Input array must be at least 2x2.");
return NULL;
}
}
// The plan is to iterate a 2x2 square across the input array. This means
// that the upper-left corner of the square needs to iterate across a
// sub-array that's one-less-large in each direction (so that the square
@@ -100,7 +100,7 @@ iterate_and_store(PyObject *self, PyObject *args)
// 2D coordinates for the position of the upper-left pointer. Note that we
// ensured that the array is of type 'double' and is C-contiguous (last
// index varies the fastest).
// Current coords start at 0,0.
npy_intp coords[2] = {0,0};
// Precompute the size of the array minus 2 in each direction, so we'll know
@@ -116,7 +116,7 @@ iterate_and_store(PyObject *self, PyObject *args)
double* ur_ptr = ul_ptr + 1;
double* ll_ptr = ul_ptr + dims[1];
double* lr_ptr = ll_ptr + 1;
// make a list to hold the returned coordinates
PyObject* arc_list = PyList_New(0);
if (!arc_list) {
@@ -139,22 +139,22 @@ iterate_and_store(PyObject *self, PyObject *args)
// -+ -+ -+ -+ ++ ++ ++ ++
//
// The position of the line segment that cuts through (or doesn't, in case
// 0 and 15) each square is clear, except in cases 6 and 9. In this case,
// 0 and 15) each square is clear, except in cases 6 and 9. In this case,
// where the segments are placed is determined by vertex_connect_high.
// If vertex_connect_high is false, then lines like \\ are drawn
// If vertex_connect_high is false, then lines like \\ are drawn
// through square 6, and lines like // are drawn through square 9.
// Otherwise, the situation is reversed.
// Finally, recall that we draw the lines so that (moving from tail to
// head) the lower-valued pixels are on the left of the line. So, for
// example, case 1 entails a line slanting from the middle of the top of
// the square to the middle of the left side of the square.
unsigned char square_case = 0;
if ((*ul_ptr) > level) square_case += 1;
if ((*ur_ptr) > level) square_case += 2;
if ((*ll_ptr) > level) square_case += 4;
if ((*lr_ptr) > level) square_case += 8;
switch(square_case)
{
case 0: // no line
@@ -210,7 +210,7 @@ iterate_and_store(PyObject *self, PyObject *args)
ADD_SEGMENT(TOP, LEFT);
// bottom to right
ADD_SEGMENT(BOTTOM, RIGHT);
}
}
break;
case 10: // bottom to top
ADD_SEGMENT(BOTTOM, TOP);
@@ -230,7 +230,7 @@ iterate_and_store(PyObject *self, PyObject *args)
case 15: // no line
break;
} // switch square_case
if (coords[1] < dims_m2[1]) {
coords[1]++;
} else {
@@ -242,21 +242,21 @@ iterate_and_store(PyObject *self, PyObject *args)
}
ul_ptr++; ur_ptr++; ll_ptr++; lr_ptr++;
} // iteration
// get rid of the double array reference that we own
Py_DECREF(double_array);
return arc_list;
return arc_list;
}
static PyMethodDef _find_contours_methods[] = {
{"iterate_and_store", iterate_and_store, METH_VARARGS, iterate_and_store_doc},
{NULL, NULL, 0, NULL}
{"iterate_and_store", iterate_and_store, METH_VARARGS, iterate_and_store_doc},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
init_find_contours(void)
{
Py_InitModule3("_find_contours", _find_contours_methods, _find_contours_doc);
import_array();
Py_InitModule3("_find_contours", _find_contours_methods, _find_contours_doc);
import_array();
}
+24 -25
View File
@@ -7,16 +7,16 @@ _param_options = ('high', 'low')
def find_contours(array, level, fully_connected='low', positive_orientation='low'):
'''Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute a the iso-valued contours of
the input 2D array for a particular level value. Array values are linearly
interpolated to provide better precision for the output contours.
Parameters
----------
----------
array : convertible to a 2D ndarray object
Input data in which to find isocontours.
level : float
level : float
Value along which to find contours in the array.
fully_connected : either 'low' or 'high'
Indicates whether array elements below the given level value are to
@@ -29,18 +29,18 @@ def find_contours(array, level, fully_connected='low', positive_orientation='low
elements below the iso-value. Alternately, this means that low-valued
elements are always on the left of the contour. (See below for
details.)
Returns
-------
-------
A list of contours, where each contour is an ndarray of shape (n, 2)
consisting of n (x,y) coordinates along the contour.
The marching squares algorithm is a special case of the marching cubes
algorithm (Lorensen, William and Harvey E. Cline. Marching Cubes: A High
Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH
87 Proceedings) 21(4) July 1987, p. 163-170). A simple explanation is
available here: http://www.essi.fr/~lingrand/MarchingCubes/algo.html
There is a single ambiguous case in the marching squares algorithm: when
a given 2x2-element square has two high-valued and two low-valued
elements, each pair diagonally adjacent. (Where high- and low-valued is
@@ -51,44 +51,44 @@ def find_contours(array, level, fully_connected='low', positive_orientation='low
connected' (also known as 'face+vertex-connected' or '8-connected'). Only
high-valued or low-valued elements can be fully-connected, the other set
will be considred as 'face-connected' or '4-connected'. By default,
low-valued elements are considered fully-connected; this can be altered
low-valued elements are considered fully-connected; this can be altered
with the 'fully_connected' parameter.
Output contours are not guaranteed to be closed: contours which intersect
the array edge will be left open. All other contours will be closed. (The
closed-ness of a contours can be tested by checking whether the beginning
point is the same as the end point.)
Contours are oriented. By default, array values lower than the contour
value are to the left of the contour and values greater than the contour
value are to the right. This means that contours will wind
counter-clockwise (i.e. in 'positive orientation') around islands of
low-valued pixels. This behavior can be altered with the
'positive_orientation' parameter.
The order of the contours in the output list is determined by the position
of the smallest x,y (in lexicographical order) coordinate in the contour.
This is a side-effect of how the input array is traversed, but can be
relied upon.
IMPORTANT NOTE ON COORDINATES AND VALUES:
Array coordinates/values are assumed to refer to the _center_ of the
array element. Take a simple example: [0, 1]. The interpolated position of
0.5 in this array is midway between the 0-element (at x=0) and the
1-element (at x=1), and thus would fall at x=0.5.
This means that to find reasonable contours, it is best to find contours
midway between the expected "light" and "dark" values. In particular,
given a binarized array, DO NOT choose to find contours at the low or high
value of the array. This will often yield degenerate contours, especially
around structures that are a single array element wide. Instead choose
a middle value, as above.'''
array = np.asarray(array)
if array.ndim != 2:
raise RuntimeError('Only 2D arrays are supported.')
level = float(level)
if (fully_connected not in _param_options or
if (fully_connected not in _param_options or
positive_orientation not in _param_options):
raise ValueError('Parameters "fully_connected" and'
' "positive_orientation" must be either "high" or "low".')
@@ -98,7 +98,7 @@ def find_contours(array, level, fully_connected='low', positive_orientation='low
if positive_orientation == 'high':
contours = [c[::-1] for c in contours]
return contours
def _take_2(seq):
iterator = iter(seq)
while(True):
@@ -117,24 +117,24 @@ def _assemble_contours(points_iterator):
# exactly the contour level, and the rest are above or below.
# This degnerate vertex will be picked up later by neighboring squares.
if from_point == to_point: continue
tail_data = starts.get(to_point)
head_data = ends.get(from_point)
if tail_data is not None and head_data is not None:
tail, tail_num = tail_data
head, head_num = head_data
# We need to connect these two contours.
# We need to connect these two contours.
if tail is head:
# We need to closed a contour.
# Add the end point, and remove the contour from the
# Add the end point, and remove the contour from the
# 'starts' and 'ends' dicts.
head.append(to_point)
del starts[to_point]
del ends[from_point]
else: # tail is not head
# We need to join two distinct contours.
# We want to keep the first contour segment created, so that
# We want to keep the first contour segment created, so that
# the final contours are ordered left->right, top->bottom.
if tail_num > head_num:
# tail was created second. Append tail to head.
@@ -166,7 +166,7 @@ def _assemble_contours(points_iterator):
ends[to_point] = (new_contour, new_num)
elif tail_data is not None and head_data is None:
tail, tail_num = tail_data
# We've found a single contour to which the new segment should be
# We've found a single contour to which the new segment should be
# prepended.
tail.appendleft(from_point)
del starts[to_point]
@@ -179,6 +179,5 @@ def _assemble_contours(points_iterator):
del ends[from_point]
ends[to_point] = (head, head_num)
# end iteration over from_ and to_ points
return [np.array(contour) for (num, contour) in sorted(contours.items())]