Move the sources to trunk
[opencv] / interfaces / swig / python / pyhelpers.cpp
1 #include "pyhelpers.h"
2 #include <iostream>
3 #include <sstream>
4
5 int PySwigObject_Check(PyObject *op);
6
7 /* Py_ssize_t for old Pythons */
8 #if PY_VERSION_HEX < 0x02050000
9 typedef int Py_ssize_t;
10 #endif
11
12 PyObject * PyTuple_FromIntArray(int * arr, int len){
13         PyObject * obj = PyTuple_New(len);
14         for(int i=0; i<len; i++){
15                 PyTuple_SetItem(obj, i, PyLong_FromLong( arr[i] ) );
16         }
17         return obj;
18 }
19
20 PyObject * SWIG_SetResult(PyObject * result, PyObject * obj){
21         if(result){
22                 Py_DECREF(result);
23         }
24         result = PyTuple_New(1);
25         PyTuple_SetItem(result, 0, obj);
26         return result;
27 }
28
29 PyObject * SWIG_AppendResult(PyObject * result, PyObject ** to_add, int num){
30         if ((!result) || (result == Py_None)) {
31                 /* no other results, so just add our values */
32
33                 /* if only one object, return that */
34                 if(num==1){
35                         return to_add[0];
36                 }
37                 
38                 /* create a new tuple to put in our new pointer python objects */
39                 result = PyTuple_New (num);
40
41                 /* put in our new pointer python objects */
42                 for(int i=0; i<num; i++){
43                         PyTuple_SetItem (result, i, to_add[i]);
44                 }       
45         }
46         else {
47                 /* we have other results, so add it to the end */
48
49                 if (!PyTuple_Check (result)) {
50                         /* previous result is not a tuple, so create one and put
51                            previous result and current pointer in it */
52
53                         /* first, save previous result */
54                         PyObject *obj_save = result;
55
56                         /* then, create the tuple */
57                         result = PyTuple_New (1);
58
59                         /* finaly, put the saved value in the tuple */
60                         PyTuple_SetItem (result, 0, obj_save);
61                 }
62
63                 /* create a new tuple to put in our new pointer python object */
64                 PyObject *my_obj = PyTuple_New (num);
65
66                 /* put in our new pointer python object */
67                 for( int i=0; i<num ; i++ ){
68                         PyTuple_SetItem (my_obj, i, to_add[i]);
69                 }
70
71                 /* save the previous result */
72                 PyObject *obj_save = result;
73
74                 /* concat previous and our new result */
75                 result = PySequence_Concat (obj_save, my_obj);
76
77                 /* decrement the usage of no more used objects */
78                 Py_DECREF (obj_save);
79                 Py_DECREF (my_obj);
80         }
81         return result;
82 }
83
84 template <typename T>
85 std::ostream & cv_arr_write(std::ostream & out, T * data, int rows, int nch, int step){
86         int i,j,k;
87         char * cdata = (char *) data;
88         std::string chdelim1="", chdelim2="";
89
90         // only output channel parens if > 1
91         if(nch>1){
92                 chdelim1="(";
93                 chdelim2=")";
94         }
95
96         out<<"[";
97         for(i=0; i<rows; i++){
98                 out<<"[";
99
100                 // first element
101                 out<<chdelim1;
102                 out<<((T*)(cdata+i*step))[0];
103                 for(k=1; k<nch; k++){
104                         out<<", "<<((T*)(cdata+i*step))[k];
105                 }
106                 out<<chdelim2;
107                 
108                 // remaining elements
109                 for(j=nch*sizeof(T); j<step; j+=(nch*sizeof(T))){
110                         out<<", "<<chdelim1;
111                         out<<((T*)(cdata+i*step+j))[0];
112                         for(k=1; k<nch; k++){
113                                 out<<", "<<((T*)(cdata+i*step+j))[k];
114                         }
115                         out<<chdelim2;
116                 }
117                 out<<"]\n";
118         }
119         out<<"]";
120         return out;
121 }
122
123 void cvArrPrint(CvArr * arr){
124     CV_FUNCNAME( "cvArrPrint" );
125             
126         __BEGIN__;
127         CvMat * mat;
128         CvMat stub;
129
130         mat = cvGetMat(arr, &stub);
131         
132         int cn = CV_MAT_CN(mat->type);
133         int depth = CV_MAT_DEPTH(mat->type);
134         int step = MAX(mat->step, cn*mat->cols*CV_ELEM_SIZE(depth));
135         std::ostringstream str;
136
137         switch(depth){
138                 case CV_8U:
139                         cv_arr_write(str, (uchar *)mat->data.ptr, mat->rows, cn, step);
140                         break;
141                 case CV_8S:
142                         cv_arr_write(str, (char *)mat->data.ptr, mat->rows, cn, step);
143                         break;
144                 case CV_16U:
145                         cv_arr_write(str, (ushort *)mat->data.ptr, mat->rows, cn, step);
146                         break;
147                 case CV_16S:
148                         cv_arr_write(str, (short *)mat->data.ptr, mat->rows, cn, step);
149                         break;
150                 case CV_32S:
151                         cv_arr_write(str, (int *)mat->data.ptr, mat->rows, cn, step);
152                         break;
153                 case CV_32F:
154                         cv_arr_write(str, (float *)mat->data.ptr, mat->rows, cn, step);
155                         break;
156                 case CV_64F:
157                         cv_arr_write(str, (double *)mat->data.ptr, mat->rows, cn, step);
158                         break;
159                 default:
160                         CV_ERROR( CV_StsError, "Unknown element type");
161                         break;
162         }
163         std::cout<<str.str()<<std::endl;
164
165         __END__;
166 }
167
168 // deal with negative array indices
169 int PyLong_AsIndex( PyObject * idx_object, int len ){
170         int idx = PyLong_AsLong( idx_object );
171         if(idx<0) return len+idx;
172         return idx;
173 }
174
175 CvRect PySlice_to_CvRect(CvArr * src, PyObject * idx_object){
176         CvSize sz = cvGetSize(src);
177         //printf("Size %dx%d\n", sz.height, sz.width);
178         int lower[2], upper[2];
179         Py_ssize_t len, start, stop, step, slicelength;
180
181         if(PyInt_Check(idx_object) || PyLong_Check(idx_object)){
182                 // if array is a row vector, assume index into columns
183                 if(sz.height>1){
184                         lower[0] = PyLong_AsIndex( idx_object, sz.height );
185                         upper[0] = lower[0] + 1;
186                         lower[1] = 0;
187                         upper[1] = sz.width;
188                 }
189                 else{
190                         lower[0] = 0;
191                         upper[0] = sz.height;
192                         lower[1] = PyLong_AsIndex( idx_object, sz.width );
193                         upper[1] = lower[1]+1;
194                 }
195         }
196
197         // 1. Slice
198         else if(PySlice_Check(idx_object)){
199                 len = sz.height;
200                 if(PySlice_GetIndicesEx( (PySliceObject*)idx_object, len, &start, &stop, &step, &slicelength )!=0){
201                         printf("Error in PySlice_GetIndicesEx: returning NULL");
202                         PyErr_SetString(PyExc_Exception, "Error");
203                         return cvRect(0,0,0,0);
204                 }
205                 // if array is a row vector, assume index bounds are into columns
206                 if(sz.height>1){
207                         lower[0] = (int) start; // use c convention of start index = 0
208                         upper[0] = (int) stop;    // use c convention
209                         lower[1] = 0;
210                         upper[1] = sz.width;
211                 }
212                 else{
213                         lower[1] = (int) start; // use c convention of start index = 0
214                         upper[1] = (int) stop;    // use c convention
215                         lower[0] = 0;
216                         upper[0] = sz.height;
217                 }
218         }
219
220         // 2. Tuple
221         else if(PyTuple_Check(idx_object)){
222                 //printf("PyTuple{\n");
223                 if(PyObject_Length(idx_object)!=2){
224                         //printf("Expected a sequence of length 2: returning NULL");
225                         PyErr_SetString(PyExc_ValueError, "Expected a sequence with 2 elements");
226                         return cvRect(0,0,0,0);
227                 }
228                 for(int i=0; i<2; i++){
229                         PyObject *o = PyTuple_GetItem(idx_object, i);
230
231                         // 2a. Slice -- same as above
232                         if(PySlice_Check(o)){
233                                 //printf("PySlice\n");
234                                 len = (i==0 ? sz.height : sz.width);
235                                 if(PySlice_GetIndicesEx( (PySliceObject*)o, len, &start, &stop, &step, &slicelength )!=0){
236                                         PyErr_SetString(PyExc_Exception, "Error");
237                                         printf("Error in PySlice_GetIndicesEx: returning NULL");
238                                         return cvRect(0,0,0,0);
239                                 }
240                                 //printf("PySlice_GetIndecesEx(%d, %d, %d, %d, %d)\n", len, start, stop, step, slicelength);
241                                 lower[i] = start;
242                                 upper[i] = stop;
243
244                         }
245
246                         // 2b. Integer
247                         else if(PyInt_Check(o) || PyLong_Check(o)){
248                                 //printf("PyInt\n");
249                                 lower[i] = PyLong_AsIndex(o, i==0 ? sz.height : sz.width);
250                                 upper[i] = lower[i]+1;
251                         }
252
253                         else {
254                                 PyErr_SetString(PyExc_TypeError, "Expected a sequence of slices or integers");
255                                 printf("Expected a slice or int as sequence item: returning NULL");
256                                 return cvRect(0,0,0,0);
257                         }
258                 }
259         }
260
261         else {
262                 PyErr_SetString( PyExc_TypeError, "Expected a slice or sequence");
263                 printf("Expected a slice or sequence: returning NULL");
264                 return cvRect(0,0,0,0);
265         }
266
267         //lower[0] = MAX(0, lower[0]);
268         //lower[1] = MAX(0, lower[1]);
269         //upper[0] = MIN(sz.height, upper[0]);
270         //upper[1] = MIN(sz.width, upper[1]);
271         //printf("Slice=%d %d %d %d\n", lower[0], upper[0], lower[1], upper[1]);
272         return cvRect(lower[1],lower[0], upper[1]-lower[1], upper[0]-lower[0]);
273 }
274
275 double PyObject_AsDouble(PyObject * obj){
276         if(PyNumber_Check(obj)){
277                 if(PyFloat_Check(obj)){
278                         return PyFloat_AsDouble(obj);
279                 }
280                 else if(PyInt_Check(obj) || PyLong_Check(obj)){
281                         return (double) PyLong_AsLong(obj);
282                 }
283         }
284         PyErr_SetString( PyExc_TypeError, "Could not convert python object to Double");
285         return -1;
286 }
287
288 long PyObject_AsLong(PyObject * obj){
289     if(PyNumber_Check(obj)){
290         if(PyFloat_Check(obj)){
291             return (long) PyFloat_AsDouble(obj);
292         }
293         else if(PyInt_Check(obj) || PyLong_Check(obj)){
294             return PyLong_AsLong(obj);
295         }
296     }
297         PyErr_SetString( PyExc_TypeError, "Could not convert python object to Long");
298         return -1;
299 }
300