Repository navigation
Expand file tree
/
Copy pathmrgingham_pywrap.c
More file actions
489 lines (425 loc) · 16.5 KB
/
Copy pathmrgingham_pywrap.c
File metadata and controls
489 lines (425 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#include <stdbool.h>
#include <Python.h>
#include <structmember.h>
#include <numpy/arrayobject.h>
#include <signal.h>
#include "ChESS.h"
#include "mrgingham_pywrap_cplusplus_bridge.h"
// Python is silly. There's some nuance about signal handling where it sets a
// SIGINT (ctrl-c) handler to just set a flag, and the python layer then reads
// this flag and does the thing. Here I'm running C code, so SIGINT would set a
// flag, but not quit, so I can't interrupt the solver. Thus I reset the SIGINT
// handler to the default, and put it back to the python-specific version when
// I'm done
#define SET_SIGINT() struct sigaction sigaction_old; \
do { \
if( 0 != sigaction(SIGINT, \
&(struct sigaction){ .sa_handler = SIG_DFL }, \
&sigaction_old) ) \
{ \
PyErr_SetString(PyExc_RuntimeError, "sigaction() failed"); \
goto done; \
} \
} while(0)
#define RESET_SIGINT() do { \
if( 0 != sigaction(SIGINT, \
&sigaction_old, NULL )) \
PyErr_SetString(PyExc_RuntimeError, "sigaction-restore failed"); \
} while(0)
#define PYMETHODDEF_ENTRY(name, c_function_name, args) {#name, \
(PyCFunction)c_function_name, \
args, \
name ## _docstring}
static void capsule_free(PyObject* capsule)
{
void* ptr = PyCapsule_GetPointer(capsule, NULL);
free(ptr);
}
static
void loop_dim(int idim,
PyArrayObject* response,
PyArrayObject* image,
const npy_intp* dims,
const npy_intp* strides,
const int ndims,
npy_intp* islice)
{
if(idim < 0)
{
int16_t* data_response = (int16_t*)PyArray_GetPtr(response, islice);
uint8_t* data_image = (uint8_t*)PyArray_GetPtr(image, islice);
mrgingham_ChESS_response_5( data_response, data_image,
dims[ndims-1], dims[ndims-2],
strides[ndims-2]);
}
else
for(islice[idim]=0; islice[idim] < dims[idim]; islice[idim]++)
loop_dim(idim-1,
response,
image,
dims,
strides,
ndims,
islice);
}
static PyObject* py_ChESS_response_5(PyObject* NPY_UNUSED(self),
PyObject* args)
{
PyObject* result = NULL;
SET_SIGINT();
PyArrayObject* image = NULL;
if(!PyArg_ParseTuple( args, "O&", PyArray_Converter, &image ))
goto done;
npy_intp* dims = PyArray_DIMS (image);
npy_intp* strides = PyArray_STRIDES(image);
int ndims = PyArray_NDIM (image);
if( ndims < 2 )
{
PyErr_Format(PyExc_RuntimeError, "The input image array must have at least 2 dims (extra ones will be broadcasted); got %d",
PyArray_NDIM(image));
goto done;
}
if( PyArray_TYPE(image) != NPY_UINT8 )
{
PyErr_SetString(PyExc_RuntimeError, "The input image array must contain 8-bit unsigned data");
goto done;
}
if( strides[ndims-1] != 1 )
{
PyErr_SetString(PyExc_RuntimeError, "Image rows must live in contiguous memory");
goto done;
}
PyArrayObject* response =
(PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_INT16);
if(response == NULL)
{
PyErr_SetString(PyExc_RuntimeError, "Couldn't allocate response");
goto done;
}
// broadcast through all the slices
{ // need a block to pacify the compiler
npy_intp islice[ndims];
islice[ndims - 1] = 0;
islice[ndims - 2] = 0;
// The last 2 dimensions index each slice (x,y inside each image). The
// dimensions before that are for broadcasting
loop_dim(ndims-3,
response,
image,
dims,
strides,
ndims,
islice);
}
result = (PyObject*)response;
done:
Py_XDECREF(image);
RESET_SIGINT();
return result;
}
static
bool add_points__find_points(int* xy, int N, double scale, void* cookie)
{
PyObject** result = (PyObject**)cookie;
*result = PyArray_SimpleNew(2,
((npy_intp[]){N, 2}),
NPY_DOUBLE);
if(*result == NULL) return false;
double* out_data = (double*)PyArray_BYTES((PyArrayObject*)*result);
for(int i=0; i<2*N; i++)
out_data[i] = scale * (double)xy[i];
return true;
}
static PyObject* find_points(PyObject* NPY_UNUSED(self),
PyObject* args,
PyObject* kwargs)
{
PyArrayObject* image = NULL;
PyObject* result = NULL;
int image_pyramid_level = 0;
int blobs = 0;
int debug = 0;
SET_SIGINT();
char* keywords[] = { "image", "image_pyramid_level", "blobs",
"debug",
NULL };
if(!PyArg_ParseTupleAndKeywords( args, kwargs,
"O&|ipp",
keywords,
PyArray_Converter, &image,
&image_pyramid_level,
&blobs,
&debug,
NULL))
goto done;
if(blobs && image_pyramid_level != 0)
{
PyErr_Format(PyExc_RuntimeError, "blob detector requires that image_pyramid_level == 0");
goto done;
}
npy_intp* dims = PyArray_DIMS (image);
npy_intp* strides = PyArray_STRIDES(image);
int ndims = PyArray_NDIM (image);
if( ndims != 2 )
{
PyErr_Format(PyExc_RuntimeError, "The input image array must have exactly 2 dims (broadcasting not supported here); got %d",
PyArray_NDIM(image));
goto done;
}
if( PyArray_TYPE(image) != NPY_UINT8 )
{
PyErr_SetString(PyExc_RuntimeError, "The input image array must contain 8-bit unsigned data");
goto done;
}
if( strides[ndims-1] != 1 )
{
PyErr_SetString(PyExc_RuntimeError, "Image rows must live in contiguous memory");
goto done;
}
if(! find_chessboard_corners_from_image_array_C(PyArray_DIMS(image)[0],
PyArray_DIMS(image)[1],
PyArray_STRIDES(image)[0],
PyArray_BYTES(image),
image_pyramid_level,
blobs,
debug,
&add_points__find_points, &result) )
{
if(result == NULL)
{
// Detector didn't find anything. I don't flag an error,
// but simply return a no-data array
result = PyArray_SimpleNew(2,
((npy_intp[]){0, 2}),
NPY_DOUBLE);
}
else
{
// an actual error occured. I complain
Py_DECREF(result);
result = NULL;
PyErr_SetString(PyExc_RuntimeError, "find_chessboard_corners_from_image_array_C() failed");
goto done;
}
}
done:
Py_XDECREF(image);
RESET_SIGINT();
return result;
}
static
bool add_points__find_board(double* xy, int N, void* cookie)
{
PyObject** result = (PyObject**)cookie;
*result = PyArray_SimpleNew(2,
((npy_intp[]){N, 2}),
NPY_DOUBLE);
if(*result == NULL) return false;
double* out_data = (double*)PyArray_BYTES((PyArrayObject*)*result);
memcpy(out_data, xy, 2*N*sizeof(double));
return true;
}
static PyObject* find_board(PyObject* NPY_UNUSED(self),
PyObject* args,
PyObject* kwargs)
{
PyArrayObject* image = NULL;
PyObject* result = NULL;
int image_pyramid_level = -1;
int gridn = 10;
int blobs = 0;
int debug = 0;
const char* debug_sequence_string = NULL;
int debug_sequence_x = -1;
int debug_sequence_y = -1;
int report_refinement_level = 0;
PyObject* py_points = NULL;
signed char* refinement_level = NULL;
PyObject* py_refinement_level = NULL;
PyObject* py_refinement_level_capsule = NULL;
SET_SIGINT();
char* keywords[] = { "image", "image_pyramid_level", "gridn", "blobs",
"debug", "debug_sequence",
"report_refinement_level",
NULL };
if(!PyArg_ParseTupleAndKeywords( args, kwargs,
"O&|iippsp",
keywords,
PyArray_Converter, &image,
&image_pyramid_level, &gridn,
&blobs,
&debug,
&debug_sequence_string,
&report_refinement_level,
NULL))
goto done;
if(blobs && image_pyramid_level != 0)
{
PyErr_Format(PyExc_RuntimeError, "blob detector requires that image_pyramid_level == 0");
goto done;
}
if(debug_sequence_string != NULL)
{
// parse string into INTEGER,INTEGER
int nbytesread;
int res = sscanf(debug_sequence_string,
"%d,%d%n",
&debug_sequence_x,
&debug_sequence_x,
&nbytesread);
if(!(res == 2 && debug_sequence_string[nbytesread] == '\0'))
{
PyErr_Format(PyExc_RuntimeError, "Couldn't parse debug_sequence as an 'INTEGER,INTEGER' string");
goto done;
}
}
npy_intp* dims = PyArray_DIMS (image);
npy_intp* strides = PyArray_STRIDES(image);
int ndims = PyArray_NDIM (image);
if( ndims != 2 )
{
PyErr_Format(PyExc_RuntimeError, "The input image array must have exactly 2 dims (broadcasting not supported here); got %d",
PyArray_NDIM(image));
goto done;
}
if( PyArray_TYPE(image) != NPY_UINT8 )
{
PyErr_SetString(PyExc_RuntimeError, "The input image array must contain 8-bit unsigned data");
goto done;
}
if( strides[ndims-1] != 1 )
{
PyErr_SetString(PyExc_RuntimeError, "Image rows must live in contiguous memory");
goto done;
}
if(gridn < 2)
{
PyErr_SetString(PyExc_RuntimeError, "gridn value must be >= 2");
goto done;
}
if(! find_chessboard_from_image_array_C(PyArray_DIMS(image)[0],
PyArray_DIMS(image)[1],
PyArray_STRIDES(image)[0],
PyArray_BYTES(image),
gridn,
image_pyramid_level,
blobs,
debug,
debug_sequence_x,
debug_sequence_y,
&refinement_level,
&add_points__find_board, &py_points) )
{
// This is allowed to fail. We possibly found no chessboard. This is
// sloppy since it ignore other potential errors, but there shouldn't be
// any in this path
Py_XDECREF(py_points);
if( py_points == NULL )
{
py_points = Py_None;
Py_INCREF(py_points);
}
}
if(!report_refinement_level)
{
// Not reporting the refinement_level
result = py_points;
py_points = NULL;
}
else
{
if(py_points == Py_None || refinement_level == NULL)
{
// Reporting the refinement_level, but there were no detections or no refinement_level.
// return (py_points,None). py_points may be None too
py_refinement_level = Py_None;
Py_INCREF(py_refinement_level);
result = Py_BuildValue("(OO)",
py_points,
py_refinement_level);
}
else
{
// Reporting the refinement_level, and there are detections: return
// (points,refinement_level)
py_refinement_level =
PyArray_SimpleNewFromData(1, (npy_intp[]){PyArray_DIMS((PyArrayObject*)py_points)[0]},
NPY_INT8,
(void *)refinement_level);
if (py_refinement_level == NULL)
goto done;
py_refinement_level_capsule = PyCapsule_New((void *)refinement_level, NULL, capsule_free);
if (py_refinement_level_capsule == NULL)
goto done;
// The capsule now owns the C pointer. I do not free() it myself
refinement_level = NULL;
// Tell numpy this capsule is what owns the memory. We make sure we free(refinement_level) when done
if (PyArray_SetBaseObject((PyArrayObject *)py_refinement_level, py_refinement_level_capsule) < 0)
goto done;
// PyArray_SetBaseObject() succeeded, and stole the reference to the
// capsule. I make sure we don't try to free it
py_refinement_level_capsule = NULL;
result = Py_BuildValue("(OO)",
py_points,
py_refinement_level);
}
}
done:
Py_XDECREF(image);
free(refinement_level);
Py_XDECREF(py_points);
Py_XDECREF(py_refinement_level);
Py_XDECREF(py_refinement_level_capsule);
RESET_SIGINT();
return result;
}
static const char ChESS_response_5_docstring[] =
#include "ChESS_response_5.docstring.h"
;
static const char find_points_docstring[] =
#include "find_points.docstring.h"
;
static const char find_board_docstring[] =
#include "find_board.docstring.h"
;
static const char find_chessboard_corners_docstring[] =
#include "find_chessboard_corners.docstring.h"
;
static const char find_chessboard_docstring[] =
#include "find_chessboard.docstring.h"
;
static PyMethodDef methods[] =
{
PYMETHODDEF_ENTRY(ChESS_response_5, py_ChESS_response_5, METH_VARARGS),
PYMETHODDEF_ENTRY(find_points, find_points, METH_VARARGS | METH_KEYWORDS),
PYMETHODDEF_ENTRY(find_board, find_board, METH_VARARGS | METH_KEYWORDS),
// These are compatibility functions. Same implementation as the above, but
// different names. Meant to keep old code running
PYMETHODDEF_ENTRY(find_chessboard_corners, find_points, METH_VARARGS | METH_KEYWORDS),
PYMETHODDEF_ENTRY(find_chessboard, find_board, METH_VARARGS | METH_KEYWORDS),
{}
};
#if PY_MAJOR_VERSION == 2
__attribute__((visibility("default")))
PyMODINIT_FUNC initmrgingham(void)
{
Py_InitModule3("mrgingham", methods,
"Chessboard-detection routines");
import_array();
}
#else
static struct PyModuleDef module_def =
{
PyModuleDef_HEAD_INIT,
"mrgingham",
"Chessboard-detection routines",
-1,
methods
};
PyMODINIT_FUNC PyInit_mrgingham(void)
{
import_array();
return PyModule_Create(&module_def);
}
#endif