Drop old python interface

This commit is contained in:
Andrey Kamaev 2013-04-12 17:05:23 +04:00
parent 909d6fcf51
commit b2ba8b9969
10 changed files with 48 additions and 6988 deletions

View File

@ -827,8 +827,8 @@ if(BUILD_opencv_python)
else()
status(" Libraries:" HAVE_opencv_python THEN ${PYTHON_LIBRARIES} ELSE NO)
endif()
status(" numpy:" PYTHON_USE_NUMPY THEN "${PYTHON_NUMPY_INCLUDE_DIR} (ver ${PYTHON_NUMPY_VERSION})" ELSE "NO (Python wrappers can not be generated)")
status(" packages path:" PYTHON_EXECUTABLE THEN "${PYTHON_PACKAGES_PATH}" ELSE "-")
status(" numpy:" PYTHON_NUMPY_INCLUDE_DIR THEN "${PYTHON_NUMPY_INCLUDE_DIR} (ver ${PYTHON_NUMPY_VERSION})" ELSE "NO (Python wrappers can not be generated)")
status(" packages path:" PYTHON_EXECUTABLE THEN "${PYTHON_PACKAGES_PATH}" ELSE "-")
endif()
# ========================== java ==========================

View File

@ -14,7 +14,6 @@ if(WIN32 AND NOT PYTHON_EXECUTABLE)
endif()
find_host_package(PythonInterp 2.0)
unset(PYTHON_USE_NUMPY CACHE)
unset(HAVE_SPHINX CACHE)
if(PYTHON_EXECUTABLE)
if(PYTHON_VERSION_STRING)
@ -93,7 +92,6 @@ if(PYTHON_EXECUTABLE)
endif()
if(PYTHON_NUMPY_INCLUDE_DIR)
set(PYTHON_USE_NUMPY TRUE)
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import numpy; print numpy.version.version"
RESULT_VARIABLE PYTHON_NUMPY_PROCESS
OUTPUT_VARIABLE PYTHON_NUMPY_VERSION

View File

@ -717,8 +717,8 @@ public:
template<typename _Tp> MatConstIterator_<_Tp> begin() const;
template<typename _Tp> MatConstIterator_<_Tp> end() const;
enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG };
enum { MAGIC_MASK=0xFFFF0000, TYPE_MASK=0x00000FFF, DEPTH_MASK=7 };
enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
/*! includes several bit-fields:
- the magic signature

View File

@ -5,23 +5,20 @@
if(WIN32 AND CMAKE_BUILD_TYPE STREQUAL "Debug")
ocv_module_disable(python)
endif()
if(ANDROID OR IOS OR NOT PYTHONLIBS_FOUND OR NOT PYTHON_USE_NUMPY)
if(ANDROID OR IOS OR NOT PYTHONLIBS_FOUND OR NOT PYTHON_NUMPY_INCLUDE_DIR)
ocv_module_disable(python)
endif()
set(the_description "The python bindings")
ocv_add_module(python BINDINGS opencv_core opencv_flann opencv_imgproc opencv_video opencv_ml opencv_features2d opencv_highgui opencv_calib3d opencv_photo opencv_objdetect opencv_contrib opencv_legacy opencv_softcascade OPTIONAL opencv_nonfree)
add_definitions(-DPYTHON_USE_NUMPY=1)
ocv_module_include_directories(
"${PYTHON_INCLUDE_PATH}"
"${PYTHON_NUMPY_INCLUDE_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/src2"
)
set(opencv_hdrs
"${OPENCV_MODULE_opencv_core_LOCATION}/include/opencv2/core.hpp"
"${OPENCV_MODULE_opencv_core_LOCATION}/include/opencv2/core/base.hpp"
@ -53,13 +50,6 @@ set(cv2_generated_hdrs
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_type_reg.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_const_reg.h")
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/generated0.i
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src2/gen.py" "${CMAKE_CURRENT_SOURCE_DIR}/src2"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/api
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/defs
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/gen.py)
add_custom_command(
OUTPUT ${cv2_generated_hdrs}
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src2/gen2.py" ${CMAKE_CURRENT_BINARY_DIR} ${opencv_hdrs}
@ -67,7 +57,7 @@ add_custom_command(
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/hdr_parser.py
DEPENDS ${opencv_hdrs})
add_library(${the_module} SHARED src2/cv2.cpp ${CMAKE_CURRENT_BINARY_DIR}/generated0.i ${cv2_generated_hdrs} src2/cv2.cv.hpp)
add_library(${the_module} SHARED src2/cv2.cpp ${cv2_generated_hdrs})
set_target_properties(${the_module} PROPERTIES COMPILE_DEFINITIONS OPENCV_NOSTL)
if(PYTHON_DEBUG_LIBRARIES AND NOT PYTHON_LIBRARIES MATCHES "optimized.*debug")

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
from cv2.cv import *

View File

@ -1,12 +1,7 @@
#include <Python.h>
#if !PYTHON_USE_NUMPY
#error "The module can only be built if NumPy is available"
#endif
#define MODULESTR "cv2"
#include "numpy/ndarrayobject.h"
#include <numpy/ndarrayobject.h>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
@ -14,7 +9,6 @@
#include "opencv2/flann/miniflann.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/ml.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/softcascade.hpp"
@ -22,13 +16,9 @@
#include "opencv2/photo.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/photo/photo_c.h"
#include "opencv2/video/tracking_c.h"
#include "opencv2/objdetect/objdetect_c.h"
#include "opencv2/ml.hpp"
#include "opencv2/opencv_modules.hpp"
#ifdef HAVE_OPENCV_NONFREE
# include "opencv2/nonfree.hpp"
#endif
@ -196,19 +186,14 @@ public:
depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT;
int i;
npy_intp _sizes[CV_MAX_DIM+1];
cv::AutoBuffer<npy_intp> _sizes(dims + 1);
for( i = 0; i < dims; i++ )
_sizes[i] = sizes[i];
if( cn > 1 )
{
/*if( _sizes[dims-1] == 1 )
_sizes[dims-1] = cn;
else*/
_sizes[dims++] = cn;
}
_sizes[dims++] = cn;
PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
if(!o)
CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
refcount = refcountFromPyObject(o);
npy_intp* _strides = PyArray_STRIDES(o);
for( i = 0; i < dims - (cn > 1); i++ )
@ -306,6 +291,10 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow
}
}
#ifndef CV_MAX_DIM
const int CV_MAX_DIM = 32;
#endif
int ndims = PyArray_NDIM(o);
if(ndims >= CV_MAX_DIM)
{
@ -314,7 +303,8 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow
}
int size[CV_MAX_DIM+1];
size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
size_t step[CV_MAX_DIM+1];
size_t elemsize = CV_ELEM_SIZE1(type);
const npy_intp* _sizes = PyArray_DIMS(o);
const npy_intp* _strides = PyArray_STRIDES(o);
bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;
@ -617,24 +607,6 @@ static inline PyObject* pyopencv_from(const Range& r)
return Py_BuildValue("(ii)", r.start, r.end);
}
static inline bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name = "<unknown>")
{
(void)name;
if(!obj || obj == Py_None)
return true;
if(PyObject_Size(obj) == 0)
{
r = CV_WHOLE_SEQ;
return true;
}
return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
}
static inline PyObject* pyopencv_from(const CvSlice& r)
{
return Py_BuildValue("(ii)", r.start_index, r.end_index);
}
static inline bool pyopencv_to(PyObject* obj, Point& p, const char* name = "<unknown>")
{
(void)name;
@ -930,20 +902,6 @@ template<> struct pyopencvVecConverter<String>
}
};
static inline bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name="<unknown>")
{
(void)name;
if(!obj)
return true;
return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
}
static inline PyObject* pyopencv_from(const CvTermCriteria& src)
{
return Py_BuildValue("(iid)", src.type, src.max_iter, src.epsilon);
}
static inline bool pyopencv_to(PyObject *obj, TermCriteria& dst, const char *name="<unknown>")
{
(void)name;
@ -982,13 +940,6 @@ static inline PyObject* pyopencv_from(const Moments& m)
"nu30", m.nu30, "nu21", m.nu21, "nu12", m.nu12, "nu03", m.nu03);
}
static inline PyObject* pyopencv_from(const CvDTreeNode* node)
{
double value = node->value;
int ivalue = cvRound(value);
return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
}
static bool pyopencv_to(PyObject *o, cv::flann::IndexParams& p, const char *name="<unknown>")
{
(void)name;
@ -1053,6 +1004,31 @@ static bool pyopencv_to(PyObject *o, cvflann::flann_distance_t& dist, const char
return ok;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: REMOVE used only by ml wrapper
static bool pyopencv_to(PyObject *obj, CvTermCriteria& dst, const char *name="<unknown>")
{
(void)name;
if(!obj)
return true;
return PyArg_ParseTuple(obj, "iid", &dst.type, &dst.max_iter, &dst.epsilon) > 0;
}
static bool pyopencv_to(PyObject* obj, CvSlice& r, const char* name = "<unknown>")
{
(void)name;
if(!obj || obj == Py_None)
return true;
if(PyObject_Size(obj) == 0)
{
r = CV_WHOLE_SEQ;
return true;
}
return PyArg_ParseTuple(obj, "ii", &r.start_index, &r.end_index) > 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static void OnMouse(int event, int x, int y, int flags, void* param)
@ -1088,7 +1064,7 @@ static PyObject *pycvSetMouseCallback(PyObject*, PyObject *args, PyObject *kw)
if (param == NULL) {
param = Py_None;
}
ERRWRAP2(cvSetMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
ERRWRAP2(setMouseCallback(name, OnMouse, Py_BuildValue("OO", on_mouse, param)));
Py_RETURN_NONE;
}
@ -1120,7 +1096,7 @@ static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args)
PyErr_SetString(PyExc_TypeError, "on_change must be callable");
return NULL;
}
ERRWRAP2(cvCreateTrackbar2(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None)));
Py_RETURN_NONE;
}
@ -1155,8 +1131,6 @@ static int to_ok(PyTypeObject *to)
return (PyType_Ready(to) == 0);
}
#include "cv2.cv.hpp"
extern "C"
#if defined WIN32 || defined _WIN32
__declspec(dllexport)
@ -1165,13 +1139,9 @@ void initcv2();
void initcv2()
{
#if PYTHON_USE_NUMPY
import_array();
#endif
import_array();
#if PYTHON_USE_NUMPY
#include "pyopencv_generated_type_reg.h"
#endif
PyObject* m = Py_InitModule(MODULESTR, methods);
PyObject* d = PyModule_GetDict(m);
@ -1181,27 +1151,10 @@ void initcv2()
opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
PyDict_SetItemString(d, "error", opencv_error);
PyObject* cv_m = init_cv();
PyDict_SetItemString(d, "cv", cv_m);
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(I))
#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
//#define PUBLISHU(I) PyDict_SetItemString(d, #I, PyLong_FromUnsignedLong(I))
#define PUBLISH2(I, value) PyDict_SetItemString(d, #I, PyLong_FromLong(value))
PUBLISHU(IPL_DEPTH_8U);
PUBLISHU(IPL_DEPTH_8S);
PUBLISHU(IPL_DEPTH_16U);
PUBLISHU(IPL_DEPTH_16S);
PUBLISHU(IPL_DEPTH_32S);
PUBLISHU(IPL_DEPTH_32F);
PUBLISHU(IPL_DEPTH_64F);
PUBLISH(CV_LOAD_IMAGE_COLOR);
PUBLISH(CV_LOAD_IMAGE_GRAYSCALE);
PUBLISH(CV_LOAD_IMAGE_UNCHANGED);
PUBLISH(CV_HIST_ARRAY);
PUBLISH(CV_HIST_SPARSE);
PUBLISH(CV_8U);
PUBLISH(CV_8UC1);
PUBLISH(CV_8UC2);
@ -1237,37 +1190,7 @@ void initcv2()
PUBLISH(CV_64FC2);
PUBLISH(CV_64FC3);
PUBLISH(CV_64FC4);
PUBLISH(CV_NEXT_AROUND_ORG);
PUBLISH(CV_NEXT_AROUND_DST);
PUBLISH(CV_PREV_AROUND_ORG);
PUBLISH(CV_PREV_AROUND_DST);
PUBLISH(CV_NEXT_AROUND_LEFT);
PUBLISH(CV_NEXT_AROUND_RIGHT);
PUBLISH(CV_PREV_AROUND_LEFT);
PUBLISH(CV_PREV_AROUND_RIGHT);
PUBLISH(CV_WINDOW_AUTOSIZE);
PUBLISH(CV_PTLOC_INSIDE);
PUBLISH(CV_PTLOC_ON_EDGE);
PUBLISH(CV_PTLOC_VERTEX);
PUBLISH(CV_PTLOC_OUTSIDE_RECT);
PUBLISH(GC_BGD);
PUBLISH(GC_FGD);
PUBLISH(GC_PR_BGD);
PUBLISH(GC_PR_FGD);
PUBLISH(GC_INIT_WITH_RECT);
PUBLISH(GC_INIT_WITH_MASK);
PUBLISH(GC_EVAL);
PUBLISH(CV_ROW_SAMPLE);
PUBLISH(CV_VAR_NUMERICAL);
PUBLISH(CV_VAR_ORDERED);
PUBLISH(CV_VAR_CATEGORICAL);
PUBLISH(CV_AA);
#include "pyopencv_generated_const_reg.h"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,360 +0,0 @@
#define CV_BLUR_NO_SCALE 0
#define CV_BLUR 1
#define CV_GAUSSIAN 2
#define CV_MEDIAN 3
#define CV_BILATERAL 4
#define CV_INPAINT_NS 0
#define CV_INPAINT_TELEA 1
#define CV_SCHARR -1
#define CV_MAX_SOBEL_KSIZE 7
#define CV_BGR2BGRA 0
#define CV_RGB2RGBA CV_BGR2BGRA
#define CV_BGRA2BGR 1
#define CV_RGBA2RGB CV_BGRA2BGR
#define CV_BGR2RGBA 2
#define CV_RGB2BGRA CV_BGR2RGBA
#define CV_RGBA2BGR 3
#define CV_BGRA2RGB CV_RGBA2BGR
#define CV_BGR2RGB 4
#define CV_RGB2BGR CV_BGR2RGB
#define CV_BGRA2RGBA 5
#define CV_RGBA2BGRA CV_BGRA2RGBA
#define CV_BGR2GRAY 6
#define CV_RGB2GRAY 7
#define CV_GRAY2BGR 8
#define CV_GRAY2RGB CV_GRAY2BGR
#define CV_GRAY2BGRA 9
#define CV_GRAY2RGBA CV_GRAY2BGRA
#define CV_BGRA2GRAY 10
#define CV_RGBA2GRAY 11
#define CV_BGR2BGR565 12
#define CV_RGB2BGR565 13
#define CV_BGR5652BGR 14
#define CV_BGR5652RGB 15
#define CV_BGRA2BGR565 16
#define CV_RGBA2BGR565 17
#define CV_BGR5652BGRA 18
#define CV_BGR5652RGBA 19
#define CV_GRAY2BGR565 20
#define CV_BGR5652GRAY 21
#define CV_BGR2BGR555 22
#define CV_RGB2BGR555 23
#define CV_BGR5552BGR 24
#define CV_BGR5552RGB 25
#define CV_BGRA2BGR555 26
#define CV_RGBA2BGR555 27
#define CV_BGR5552BGRA 28
#define CV_BGR5552RGBA 29
#define CV_GRAY2BGR555 30
#define CV_BGR5552GRAY 31
#define CV_BGR2XYZ 32
#define CV_RGB2XYZ 33
#define CV_XYZ2BGR 34
#define CV_XYZ2RGB 35
#define CV_BGR2YCrCb 36
#define CV_RGB2YCrCb 37
#define CV_YCrCb2BGR 38
#define CV_YCrCb2RGB 39
#define CV_BGR2HSV 40
#define CV_RGB2HSV 41
#define CV_BGR2Lab 44
#define CV_RGB2Lab 45
#define CV_BayerBG2BGR 46
#define CV_BayerGB2BGR 47
#define CV_BayerRG2BGR 48
#define CV_BayerGR2BGR 49
#define CV_BayerBG2RGB CV_BayerRG2BGR
#define CV_BayerGB2RGB CV_BayerGR2BGR
#define CV_BayerRG2RGB CV_BayerBG2BGR
#define CV_BayerGR2RGB CV_BayerGB2BGR
#define CV_BayerBG2BGR_VNG 62
#define CV_BayerGB2BGR_VNG 63
#define CV_BayerRG2BGR_VNG 64
#define CV_BayerGR2BGR_VNG 65
#define CV_BGR2Luv 50
#define CV_RGB2Luv 51
#define CV_BGR2HLS 52
#define CV_RGB2HLS 53
#define CV_HSV2BGR 54
#define CV_HSV2RGB 55
#define CV_Lab2BGR 56
#define CV_Lab2RGB 57
#define CV_Luv2BGR 58
#define CV_Luv2RGB 59
#define CV_HLS2BGR 60
#define CV_HLS2RGB 61
#define CV_COLORCVT_MAX 100
#define CV_INTER_NN 0
#define CV_INTER_LINEAR 1
#define CV_INTER_CUBIC 2
#define CV_INTER_AREA 3
#define CV_WARP_FILL_OUTLIERS 8
#define CV_WARP_INVERSE_MAP 16
#define CV_SHAPE_RECT 0
#define CV_SHAPE_CROSS 1
#define CV_SHAPE_ELLIPSE 2
#define CV_SHAPE_CUSTOM 100
#define CV_MOP_OPEN 2
#define CV_MOP_CLOSE 3
#define CV_MOP_GRADIENT 4
#define CV_MOP_TOPHAT 5
#define CV_MOP_BLACKHAT 6
#define CV_TM_SQDIFF 0
#define CV_TM_SQDIFF_NORMED 1
#define CV_TM_CCORR 2
#define CV_TM_CCORR_NORMED 3
#define CV_TM_CCOEFF 4
#define CV_TM_CCOEFF_NORMED 5
#define CV_LKFLOW_PYR_A_READY 1
#define CV_LKFLOW_PYR_B_READY 2
#define CV_LKFLOW_INITIAL_GUESSES 4
#define CV_LKFLOW_GET_MIN_EIGENVALS 8
#define CV_POLY_APPROX_DP 0
#define CV_CONTOURS_MATCH_I1 1
#define CV_CONTOURS_MATCH_I2 2
#define CV_CONTOURS_MATCH_I3 3
#define CV_CLOCKWISE 1
#define CV_COUNTER_CLOCKWISE 2
#define CV_COMP_CORREL 0
#define CV_COMP_CHISQR 1
#define CV_COMP_INTERSECT 2
#define CV_COMP_BHATTACHARYYA 3
#define CV_DIST_MASK_3 3
#define CV_DIST_MASK_5 5
#define CV_DIST_MASK_PRECISE 0
#define CV_THRESH_BINARY 0 /* value = value > threshold ? max_value : 0 */
#define CV_THRESH_BINARY_INV 1 /* value = value > threshold ? 0 : max_value */
#define CV_THRESH_TRUNC 2 /* value = value > threshold ? threshold : value */
#define CV_THRESH_TOZERO 3 /* value = value > threshold ? value : 0 */
#define CV_THRESH_TOZERO_INV 4 /* value = value > threshold ? 0 : value */
#define CV_THRESH_MASK 7
#define CV_THRESH_OTSU 8 /* use Otsu algorithm to choose the optimal threshold value;
#define CV_ADAPTIVE_THRESH_MEAN_C 0
#define CV_ADAPTIVE_THRESH_GAUSSIAN_C 1
#define CV_FLOODFILL_FIXED_RANGE (1 << 16)
#define CV_FLOODFILL_MASK_ONLY (1 << 17)
#define CV_CANNY_L2_GRADIENT (1 << 31)
#define CV_HOUGH_STANDARD 0
#define CV_HOUGH_PROBABILISTIC 1
#define CV_HOUGH_MULTI_SCALE 2
#define CV_HOUGH_GRADIENT 3
#define CV_HAAR_DO_CANNY_PRUNING 1
#define CV_HAAR_SCALE_IMAGE 2
#define CV_HAAR_FIND_BIGGEST_OBJECT 4
#define CV_HAAR_DO_ROUGH_SEARCH 8
#define CV_LMEDS 4
#define CV_RANSAC 8
#define CV_CALIB_CB_ADAPTIVE_THRESH 1
#define CV_CALIB_CB_NORMALIZE_IMAGE 2
#define CV_CALIB_CB_FILTER_QUADS 4
#define CV_CALIB_USE_INTRINSIC_GUESS 1
#define CV_CALIB_FIX_ASPECT_RATIO 2
#define CV_CALIB_FIX_PRINCIPAL_POINT 4
#define CV_CALIB_ZERO_TANGENT_DIST 8
#define CV_CALIB_FIX_FOCAL_LENGTH 16
#define CV_CALIB_FIX_K1 32
#define CV_CALIB_FIX_K2 64
#define CV_CALIB_FIX_K3 128
#define CV_CALIB_FIX_INTRINSIC 256
#define CV_CALIB_SAME_FOCAL_LENGTH 512
#define CV_CALIB_ZERO_DISPARITY 1024
#define CV_FM_7POINT 1
#define CV_FM_8POINT 2
#define CV_FM_LMEDS_ONLY CV_LMEDS
#define CV_FM_RANSAC_ONLY CV_RANSAC
#define CV_FM_LMEDS CV_LMEDS
#define CV_FM_RANSAC CV_RANSAC
#define CV_STEREO_BM_NORMALIZED_RESPONSE 0
#define CV_STEREO_BM_BASIC 0
#define CV_STEREO_BM_FISH_EYE 1
#define CV_STEREO_BM_NARROW 2
#define CV_STEREO_GC_OCCLUDED SHRT_MAX
#define CV_AUTOSTEP 0x7fffffff
#define CV_MAX_ARR 10
#define CV_NO_DEPTH_CHECK 1
#define CV_NO_CN_CHECK 2
#define CV_NO_SIZE_CHECK 4
#define CV_CMP_EQ 0
#define CV_CMP_GT 1
#define CV_CMP_GE 2
#define CV_CMP_LT 3
#define CV_CMP_LE 4
#define CV_CMP_NE 5
#define CV_CHECK_RANGE 1
#define CV_CHECK_QUIET 2
#define CV_RAND_UNI 0
#define CV_RAND_NORMAL 1
#define CV_SORT_EVERY_ROW 0
#define CV_SORT_EVERY_COLUMN 1
#define CV_SORT_ASCENDING 0
#define CV_SORT_DESCENDING 16
#define CV_GEMM_A_T 1
#define CV_GEMM_B_T 2
#define CV_GEMM_C_T 4
#define CV_SVD_MODIFY_A 1
#define CV_SVD_U_T 2
#define CV_SVD_V_T 4
#define CV_LU 0
#define CV_SVD 1
#define CV_SVD_SYM 2
#define CV_CHOLESKY 3
#define CV_QR 4
#define CV_NORMAL 16
#define CV_COVAR_SCRAMBLED 0
#define CV_COVAR_NORMAL 1
#define CV_COVAR_USE_AVG 2
#define CV_COVAR_SCALE 4
#define CV_COVAR_ROWS 8
#define CV_COVAR_COLS 16
#define CV_PCA_DATA_AS_ROW 0
#define CV_PCA_DATA_AS_COL 1
#define CV_PCA_USE_AVG 2
#define CV_C 1
#define CV_L1 2
#define CV_L2 4
#define CV_NORM_MASK 7
#define CV_RELATIVE 8
#define CV_DIFF 16
#define CV_MINMAX 32
#define CV_DIFF_C (CV_DIFF | CV_C)
#define CV_DIFF_L1 (CV_DIFF | CV_L1)
#define CV_DIFF_L2 (CV_DIFF | CV_L2)
#define CV_RELATIVE_C (CV_RELATIVE | CV_C)
#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1)
#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2)
#define CV_REDUCE_SUM 0
#define CV_REDUCE_AVG 1
#define CV_REDUCE_MAX 2
#define CV_REDUCE_MIN 3
#define CV_DXT_FORWARD 0
#define CV_DXT_INVERSE 1
#define CV_DXT_SCALE 2 /* divide result by size of array */
#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE)
#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE
#define CV_DXT_ROWS 4 /* transform each row individually */
#define CV_DXT_MUL_CONJ 8 /* conjugate the second argument of cvMulSpectrums */
#define CV_FRONT 1
#define CV_BACK 0
#define CV_GRAPH_VERTEX 1
#define CV_GRAPH_TREE_EDGE 2
#define CV_GRAPH_BACK_EDGE 4
#define CV_GRAPH_FORWARD_EDGE 8
#define CV_GRAPH_CROSS_EDGE 16
#define CV_GRAPH_ANY_EDGE 30
#define CV_GRAPH_NEW_TREE 32
#define CV_GRAPH_BACKTRACKING 64
#define CV_GRAPH_OVER -1
#define CV_GRAPH_ALL_ITEMS -1
#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30)
#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29)
#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28)
#define CV_FILLED -1
#define CV_AA 16
#define CV_FONT_HERSHEY_SIMPLEX 0
#define CV_FONT_HERSHEY_PLAIN 1
#define CV_FONT_HERSHEY_DUPLEX 2
#define CV_FONT_HERSHEY_COMPLEX 3
#define CV_FONT_HERSHEY_TRIPLEX 4
#define CV_FONT_HERSHEY_COMPLEX_SMALL 5
#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6
#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7
#define CV_FONT_ITALIC 16
#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX
#define CV_KMEANS_USE_INITIAL_LABELS 1
#define CV_ErrModeLeaf 0 /* Print error and exit program */
#define CV_ErrModeParent 1 /* Print error and continue */
#define CV_ErrModeSilent 2 /* Don't print and continue */
#define CV_RETR_EXTERNAL 0
#define CV_RETR_LIST 1
#define CV_RETR_CCOMP 2
#define CV_RETR_TREE 3
#define CV_CHAIN_CODE 0
#define CV_CHAIN_APPROX_NONE 1
#define CV_CHAIN_APPROX_SIMPLE 2
#define CV_CHAIN_APPROX_TC89_L1 3
#define CV_CHAIN_APPROX_TC89_KCOS 4
#define CV_LINK_RUNS 5
#define CV_SUBDIV2D_VIRTUAL_POINT_FLAG (1 << 30)
#define CV_DIST_USER -1 /* User defined distance */
#define CV_DIST_L1 1 /* distance = |x1-x2| + |y1-y2| */
#define CV_DIST_L2 2 /* the simple euclidean distance */
#define CV_DIST_C 3 /* distance = max(|x1-x2|,|y1-y2|) */
#define CV_DIST_L12 4 /* L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */
#define CV_DIST_FAIR 5 /* distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */
#define CV_DIST_WELSCH 6 /* distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */
#define CV_DIST_HUBER 7 /* distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 */
#define CV_HAAR_MAGIC_VAL 0x42500000
#define CV_HAAR_FEATURE_MAX 3
#define CV_TERMCRIT_ITER 1
#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER
#define CV_TERMCRIT_EPS 2
#define CV_EVENT_MOUSEMOVE 0
#define CV_EVENT_LBUTTONDOWN 1
#define CV_EVENT_RBUTTONDOWN 2
#define CV_EVENT_MBUTTONDOWN 3
#define CV_EVENT_LBUTTONUP 4
#define CV_EVENT_RBUTTONUP 5
#define CV_EVENT_MBUTTONUP 6
#define CV_EVENT_LBUTTONDBLCLK 7
#define CV_EVENT_RBUTTONDBLCLK 8
#define CV_EVENT_MBUTTONDBLCLK 9
#define CV_EVENT_FLAG_LBUTTON 1
#define CV_EVENT_FLAG_RBUTTON 2
#define CV_EVENT_FLAG_MBUTTON 4
#define CV_EVENT_FLAG_CTRLKEY 8
#define CV_EVENT_FLAG_SHIFTKEY 16
#define CV_EVENT_FLAG_ALTKEY 32
#define CV_MAX_DIM 32
#define CV_CAP_PROP_POS_MSEC 0
#define CV_CAP_PROP_POS_FRAMES 1
#define CV_CAP_PROP_POS_AVI_RATIO 2
#define CV_CAP_PROP_FRAME_WIDTH 3
#define CV_CAP_PROP_FRAME_HEIGHT 4
#define CV_CAP_PROP_FPS 5
#define CV_CAP_PROP_FOURCC 6
#define CV_CAP_PROP_FRAME_COUNT 7
#define CV_CAP_PROP_FORMAT 8
#define CV_CAP_PROP_MODE 9
#define CV_CAP_PROP_BRIGHTNESS 10
#define CV_CAP_PROP_CONTRAST 11
#define CV_CAP_PROP_SATURATION 12
#define CV_CAP_PROP_HUE 13
#define CV_CAP_PROP_GAIN 14
#define CV_CAP_PROP_EXPOSURE 15
#define CV_CAP_PROP_CONVERT_RGB 16
#define CV_CAP_PROP_RECTIFICATION 18
#define CV_CAP_OPENNI 900
#define CV_CAP_OPENNI_DEPTH_GENERATOR 2147483648
#define CV_CAP_OPENNI_IMAGE_GENERATOR 1073741824
#define CV_CAP_OPENNI_DEPTH_MAP 0
#define CV_CAP_OPENNI_POINT_CLOUD_MAP 1
#define CV_CAP_OPENNI_DISPARITY_MAP 2
#define CV_CAP_OPENNI_DISPARITY_MAP_32F 3
#define CV_CAP_OPENNI_VALID_DEPTH_MASK 4
#define CV_CAP_OPENNI_BGR_IMAGE 5
#define CV_CAP_OPENNI_GRAY_IMAGE 6
#define CV_CAP_PROP_OPENNI_OUTPUT_MODE 100
#define CV_CAP_OPENNI_VGA_30HZ 0
#define CV_CAP_OPENNI_SXGA_15HZ 1
#define CV_CAP_PROP_OPENNI_REGISTRATION 104
#define CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH 101
#define CV_CAP_PROP_OPENNI_BASELINE 102
#define CV_CAP_PROP_OPENNI_FOCAL_LENGTH 103
#define CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE 1073741924
#define CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE 2147483750
#define CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH 2147483751
#define CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION 2147483752
#define CV_CN_SHIFT 3
#define CV_IMWRITE_JPEG_QUALITY 1
#define CV_IMWRITE_PNG_COMPRESSION 16
#define CV_IMWRITE_PXM_BINARY 32
#define IPL_ORIGIN_TL 0
#define IPL_ORIGIN_BL 1
#define CV_GAUSSIAN_5x5
#define CV_CN_MAX
#define CV_WINDOW_AUTOSIZE 1
#define CV_WINDOW_NORMAL 0
#define CV_WINDOW_FULLSCREEN 1
#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE
#define CV_CVTIMG_FLIP 1
#define CV_CVTIMG_SWAP_RB 2

View File

@ -1,631 +0,0 @@
#!/usr/bin/env python
import sys
from string import Template
class argument:
def __init__(self, fields):
self.ty = fields[0]
self.nm = fields[1]
self.flags = ""
self.init = None
if len(fields) > 2:
if fields[2][0] == '/':
self.flags = fields[2][1:].split(",")
else:
self.init = fields[2]
api = []
for l in open("%s/api" % sys.argv[1]):
if l[0] == '#':
continue
l = l.rstrip()
if (not l.startswith(' ')) and ('/' in l):
(l, flags) = l.split('/')
else:
flags = ""
f = l.split()
if len(f) != 0:
if l[0] != ' ':
if len(f) > 1:
ty = f[1]
else:
ty = None
api.append((f[0], [], ty, flags))
else:
api[-1][1].append(argument(f))
# Validation: check that any optional arguments are last
had_error = False
for (f, args, ty, flags) in api:
has_init = [(a.init != None) for a in args if not 'O' in a.flags]
if True in has_init and not all(has_init[has_init.index(True):]):
print 'Error in definition for "%s", optional arguments must be last' % f
had_error = True
if had_error:
sys.exit(1)
def cname(n):
if n.startswith("CV"):
return '_' + n
elif n[0].isdigit():
return '_' + n
else:
return n
# RHS is how the aggregate gets expanded in the C call
aggregate = {
'pts_npts_contours' : '!.pts,!.npts,!.contours',
'cvarr_count' : '!.cvarr,!.count',
'cvarr_plane_count' : '!.cvarr,!.count',
'floats' : '!.f',
'ints' : '!.i',
'ints0' : '!.i',
'CvPoints' : '!.p,!.count',
'CvPoint2D32fs' : '!.p,!.count',
'CvPoint3D32fs' : '!.p,!.count',
'cvarrseq' : '!.seq',
'CvArrs' : '!.ims',
'IplImages' : '!.ims',
'intpair' : '!.pairs,!.count',
'cvpoint2d32f_count' : '!.points,&!.count'
}
conversion_types = [
'char',
'CvArr',
'CvArrSeq',
'CvBox2D', # '((ff)(ff)f)',
'CvBox2D*',
'CvCapture*',
'CvStereoBMState*',
'CvStereoGCState*',
'CvKalman*',
'CvVideoWriter*',
'CvContourTree*',
'CvFont',
'CvFont*',
'CvHaarClassifierCascade*',
'CvHistogram',
'CvMat',
'CvMatND',
'CvMemStorage',
'CvMoments',
'CvMoments*',
'CvNextEdgeType',
'CvPoint',
'CvPoint*',
'CvPoint2D32f', # '(ff)',
'CvPoint2D32f*',
'CvPoint3D32f*',
'CvPoint2D64f',
'CvPOSITObject*',
'CvRect',
'CvRect*',
'CvRNG*',
'CvScalar',
'CvSeq',
'CvSeqOfCvConvexityDefect',
'CvSize',
'CvSlice',
'CvStarDetectorParams',
'CvSubdiv2D*',
'CvSubdiv2DEdge',
'CvTermCriteria',
'generic',
'IplConvKernel*',
'IplImage',
'PyObject*',
'PyCallableObject*'
]
def safename(s):
return s.replace('*', 'PTR').replace('[', '_').replace(']', '_')
def has_optional(al):
""" return true if any argument is optional """
return any([a.init for a in al])
def gen(name, args, ty, flags):
yield ""
if has_optional(args):
yield "static PyObject *pycv%s(PyObject *self, PyObject *args, PyObject *kw)" % cname(name)
else:
yield "static PyObject *pycv%s(PyObject *self, PyObject *args)" % cname(name)
if 'doconly' in flags:
yield ";"
else:
yield "{"
destinations = []
for a in args:
remap = {
'CvArr' : 'CvArr*',
'CvMat' : 'CvMat*',
'CvMatND' : 'CvMatND*',
'IplImage' : 'IplImage*',
'CvMemStorage' : 'CvMemStorage*',
'CvHistogram':'CvHistogram*',
'CvSeq':'CvSeq*',
'CvHaarClassifierCascade' : 'CvHaarClassifierCascade*'
}
ctype = remap.get(a.ty, a.ty)
if a.init:
init = " = %s" % a.init
else:
init = ''
yield " %s %s%s;" % (ctype, a.nm, init)
if 'O' in a.flags:
continue
if a.ty in (conversion_types + aggregate.keys()):
yield ' PyObject *pyobj_%s = NULL;' % (a.nm)
destinations.append('&pyobj_%s' % (a.nm))
elif a.ty in [ 'CvPoint2D32f' ]:
destinations.append('&%s.x, &%s.y' % (a.nm, a.nm))
elif a.ty in [ 'CvTermCriteria' ]:
destinations.append('&%s.type, &%s.max_iter, &%s.epsilon' % ((a.nm,)*3))
elif a.ty in [ 'CvSURFParams' ]:
destinations.append('&%s.extended, &%s.hessianThreshold, &%s.nOctaves, &%s.nOctaveLayers' % ((a.nm,)*4))
elif a.nm in [ 'CvBox2D' ]:
s = ", ".join([('&' + a.nm +'.' + fld) for fld in [ 'center.x', 'center.y', 'size.width', 'size.height', 'angle' ] ])
destinations.append(s)
else:
destinations.append('&%s' % a.nm)
fmap = {
'CvSURFParams' : '(idii)',
'double' : 'd',
'float' : 'f',
'int' : 'i',
'int64' : 'L',
'char*' : 's',
}
for k in (conversion_types + aggregate.keys()):
fmap[k] = 'O'
in_args = [ a for a in args if not 'O' in a.flags ]
fmt0 = "".join([ fmap[a.ty] for a in in_args if not a.init])
fmt1 = "".join([ fmap[a.ty] for a in in_args if a.init])
yield ''
if len(fmt0 + fmt1) > 0:
if len(fmt1) > 0:
yield ' const char *keywords[] = { %s };' % (", ".join([ '"%s"' % arg.nm for arg in args if not 'O' in arg.flags ] + ['NULL']))
yield ' if (!PyArg_ParseTupleAndKeywords(args, kw, "%s|%s", %s))' % (fmt0, fmt1, ", ".join(['(char**)keywords'] + destinations))
if '(' in (fmt0 + fmt1):
print "Tuple with kwargs is not allowed, function", name
sys.exit(1)
else:
yield ' if (!PyArg_ParseTuple(args, "%s", %s))' % (fmt0, ", ".join(destinations))
yield ' return NULL;'
# Do the conversions:
for a in args:
joinwith = [f[2:] for f in a.flags if f.startswith("J:")]
if len(joinwith) > 0:
yield 'preShareData(%s, &%s);' % (joinwith[0], a.nm)
if 'O' in a.flags:
continue
if a.ty in (conversion_types + aggregate.keys()):
if a.init:
pred = '(pyobj_%s != NULL) && ' % a.nm
else:
pred = ''
yield ' if (%s!convert_to_%s(pyobj_%s, &%s, "%s")) return NULL;' % (pred, safename(a.ty), a.nm, a.nm, a.nm)
yield '#ifdef CVPY_VALIDATE_%s' % name
yield 'CVPY_VALIDATE_%s();' % name
yield '#endif'
def invokename(a):
if 'K' in a.flags:
prefix = "(const CvArr **)"
elif 'O' in a.flags and not 'A' in a.flags:
prefix = "&"
else:
prefix = ""
if a.ty in aggregate:
return prefix + aggregate[a.ty].replace('!', a.nm)
else:
return prefix + a.nm
def funcname(s):
# The name by which the function is called, in C
if s.startswith("CV"):
return s
else:
return "cv" + s
tocall = '%s(%s)' % (funcname(name), ", ".join(invokename(a) for a in args))
if 'stub' in flags:
yield ' return stub%s(%s);' % (name, ", ".join(invokename(a) for a in args))
elif ty == None:
yield ' ERRWRAP(%s);' % tocall
yield ' Py_RETURN_NONE;'
else:
Rtypes = [
'int',
'int64',
'double',
'CvCapture*',
'CvVideoWriter*',
'CvPOSITObject*',
'CvScalar',
'CvSize',
'CvRect',
'CvSeq*',
'CvBox2D',
'CvSeqOfCvAvgComp*',
'CvSeqOfCvConvexityDefect*',
'CvSeqOfCvStarKeypoint*',
'CvSeqOfCvSURFPoint*',
'CvSeqOfCvSURFDescriptor*',
'CvContourTree*',
'IplConvKernel*',
'IplImage*',
'CvMat*',
'constCvMat*',
'ROCvMat*',
'CvMatND*',
'CvPoint2D32f_4',
'CvRNG',
'CvSubdiv2D*',
'CvSubdiv2DPoint*',
'CvSubdiv2DEdge',
'ROIplImage*',
'CvStereoBMState*',
'CvStereoGCState*',
'CvKalman*',
'float',
'generic',
'unsigned' ]
if ty in Rtypes:
yield ' %s r;' % (ty)
yield ' ERRWRAP(r = %s);' % (tocall)
yield ' return FROM_%s(r);' % safename(ty)
else:
all_returns = ty.split(",")
return_value_from_call = len(set(Rtypes) & set(all_returns)) != 0
if return_value_from_call:
yield ' %s r;' % list(set(Rtypes) & set(all_returns))[0]
yield ' ERRWRAP(r = %s);' % (tocall)
else:
yield ' ERRWRAP(%s);' % (tocall)
typed = dict([ (a.nm,a.ty) for a in args])
for i in range(len(all_returns)):
if all_returns[i] in Rtypes:
typed['r'] = all_returns[i]
all_returns[i] = "r"
if len(all_returns) == 1:
af = dict([ (a.nm,a.flags) for a in args])
joinwith = [f[2:] for f in af.get(all_returns[0], []) if f.startswith("J:")]
if len(joinwith) > 0:
yield ' return shareData(pyobj_%s, %s, %s);' % (joinwith[0], joinwith[0], all_returns[0])
else:
yield ' return FROM_%s(%s);' % (safename(typed[all_returns[0]]), all_returns[0])
else:
yield ' return Py_BuildValue("%s", %s);' % ("N" * len(all_returns), ", ".join(["FROM_%s(%s)" % (safename(typed[n]), n) for n in all_returns]))
yield '}'
gen_c = [ open("generated%d.i" % i, "w") for i in range(5) ]
print "Generated %d functions" % len(api)
for nm,args,ty,flags in sorted(api):
# Figure out docstring into ds_*
ds_args = []
mandatory = [a.nm for a in args if not ('O' in a.flags) and not a.init]
optional = [a.nm for a in args if not ('O' in a.flags) and a.init]
ds_args = ", ".join(mandatory)
def o2s(o):
if o == []:
return ""
else:
return ' [, %s%s]' % (o[0], o2s(o[1:]))
ds_args += o2s(optional)
ds = "%s(%s) -> %s" % (nm, ds_args, str(ty))
#print ds
if has_optional(args):
entry = '{"%%s", (PyCFunction)pycv%s, METH_KEYWORDS, "%s"},' % (cname(nm), ds)
else:
entry = '{"%%s", pycv%s, METH_VARARGS, "%s"},' % (cname(nm), ds)
print >>gen_c[1], entry % (nm)
if nm.startswith('CV_'):
print >>gen_c[1], entry % (nm[3:])
for l in gen(nm,args,ty,flags):
print >>gen_c[0], l
for l in open("%s/defs" % sys.argv[1]):
print >>gen_c[2], "PUBLISH(%s);" % l.split()[1]
########################################################################
# Generated objects.
########################################################################
# gen_c[3] is the code, gen_c[4] initializers
gensimple = Template("""
/*
${cvtype} is the OpenCV C struct
${ourname}_t is the Python object
*/
struct ${ourname}_t {
PyObject_HEAD
${cvtype} v;
};
static PyObject *${ourname}_repr(PyObject *self)
{
${ourname}_t *p = (${ourname}_t*)self;
char str[1000];
sprintf(str, "<${ourname} %p>", p);
return PyString_FromString(str);
}
${getset_funcs}
static PyGetSetDef ${ourname}_getseters[] = {
${getset_inits}
{NULL} /* Sentinel */
};
static PyTypeObject ${ourname}_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /*size*/
MODULESTR".${ourname}", /*name*/
sizeof(${ourname}_t), /*basicsize*/
};
static void ${ourname}_specials(void)
{
${ourname}_Type.tp_repr = ${ourname}_repr;
${ourname}_Type.tp_getset = ${ourname}_getseters;
}
static PyObject *FROM_${cvtype}(${cvtype} r)
{
${ourname}_t *m = PyObject_NEW(${ourname}_t, &${ourname}_Type);
m->v = r;
return (PyObject*)m;
}
static int convert_to_${cvtype}PTR(PyObject *o, ${cvtype}** dst, const char *name = "no_name")
{
${allownull}
if (PyType_IsSubtype(o->ob_type, &${ourname}_Type)) {
*dst = &(((${ourname}_t*)o)->v);
return 1;
} else {
(*dst) = (${cvtype}*)NULL;
return failmsg("Expected ${cvtype} for argument '%s'", name);
}
}
""")
genptr = Template("""
/*
${cvtype} is the OpenCV C struct
${ourname}_t is the Python object
*/
struct ${ourname}_t {
PyObject_HEAD
${cvtype} *v;
};
static void ${ourname}_dealloc(PyObject *self)
{
${ourname}_t *p = (${ourname}_t*)self;
cvRelease${ourname}(&p->v);
PyObject_Del(self);
}
static PyObject *${ourname}_repr(PyObject *self)
{
${ourname}_t *p = (${ourname}_t*)self;
char str[1000];
sprintf(str, "<${ourname} %p>", p);
return PyString_FromString(str);
}
${getset_funcs}
static PyGetSetDef ${ourname}_getseters[] = {
${getset_inits}
{NULL} /* Sentinel */
};
static PyTypeObject ${ourname}_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /*size*/
MODULESTR".${ourname}", /*name*/
sizeof(${ourname}_t), /*basicsize*/
};
static void ${ourname}_specials(void)
{
${ourname}_Type.tp_dealloc = ${ourname}_dealloc;
${ourname}_Type.tp_repr = ${ourname}_repr;
${ourname}_Type.tp_getset = ${ourname}_getseters;
}
static PyObject *FROM_${cvtype}PTR(${cvtype} *r)
{
${ourname}_t *m = PyObject_NEW(${ourname}_t, &${ourname}_Type);
m->v = r;
return (PyObject*)m;
}
static int convert_to_${cvtype}PTR(PyObject *o, ${cvtype}** dst, const char *name = "no_name")
{
${allownull}
if (PyType_IsSubtype(o->ob_type, &${ourname}_Type)) {
*dst = ((${ourname}_t*)o)->v;
return 1;
} else {
(*dst) = (${cvtype}*)NULL;
return failmsg("Expected ${cvtype} for argument '%s'", name);
}
}
""")
getset_func_template = Template("""
static PyObject *${ourname}_get_${member}(${ourname}_t *p, void *closure)
{
return ${rconverter}(p->v${accessor}${member});
}
static int ${ourname}_set_${member}(${ourname}_t *p, PyObject *value, void *closure)
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the ${member} attribute");
return -1;
}
if (! ${checker}(value)) {
PyErr_SetString(PyExc_TypeError, "The ${member} attribute value must be a ${typename}");
return -1;
}
p->v${accessor}${member} = ${converter}(value);
return 0;
}
""")
getset_init_template = Template("""
{(char*)"${member}", (getter)${ourname}_get_${member}, (setter)${ourname}_set_${member}, (char*)"${member}", NULL},
""")
objects = [
( 'IplConvKernel', ['allownull'], {
"nCols" : 'i',
"nRows" : 'i',
"anchorX" : 'i',
"anchorY" : 'i',
}),
( 'CvCapture', [], {}),
( 'CvHaarClassifierCascade', [], {}),
( 'CvPOSITObject', [], {}),
( 'CvVideoWriter', [], {}),
( 'CvStereoBMState', [], {
"preFilterType" : 'i',
"preFilterSize" : 'i',
"preFilterCap" : 'i',
"SADWindowSize" : 'i',
"minDisparity" : 'i',
"numberOfDisparities" : 'i',
"textureThreshold" : 'i',
"uniquenessRatio" : 'i',
"speckleWindowSize" : 'i',
"speckleRange" : 'i',
}),
( 'CvStereoGCState', [], {
"Ithreshold" : 'i',
"interactionRadius" : 'i',
"K" : 'f',
"lambda" : 'f',
"lambda1" : 'f',
"lambda2" : 'f',
"occlusionCost" : 'i',
"minDisparity" : 'i',
"numberOfDisparities" : 'i',
"maxIters" : 'i',
}),
( 'CvKalman', [], {
"MP" : 'i',
"DP" : 'i',
"CP" : 'i',
"state_pre" : 'mr',
"state_post" : 'mr',
"transition_matrix" : 'mr',
"control_matrix" : 'mr',
"measurement_matrix" : 'mr',
"control_matrix" : 'mr',
"process_noise_cov" : 'mr',
"measurement_noise_cov" : 'mr',
"error_cov_pre" : 'mr',
"gain" : 'mr',
"error_cov_post" : 'mr',
}),
( 'CvMoments', ['copy'], {
"m00" : 'f',
"m10" : 'f',
"m01" : 'f',
"m20" : 'f',
"m11" : 'f',
"m02" : 'f',
"m30" : 'f',
"m21" : 'f',
"m12" : 'f',
"m03" : 'f',
"mu20" : 'f',
"mu11" : 'f',
"mu02" : 'f',
"mu30" : 'f',
"mu21" : 'f',
"mu12" : 'f',
"mu03" : 'f',
"inv_sqrt_m00" : 'f',
}),
]
checkers = {
'i' : 'PyNumber_Check',
'f' : 'PyNumber_Check',
'm' : 'is_cvmat',
'mr' : 'is_cvmat'
}
# Python -> C
converters = {
'i' : 'PyInt_AsLong',
'f' : 'PyFloat_AsDouble',
'm' : 'PyCvMat_AsCvMat',
'mr' : 'PyCvMat_AsCvMat'
}
# C -> Python
rconverters = {
'i' : 'PyInt_FromLong',
'f' : 'PyFloat_FromDouble',
'm' : 'FROM_CvMat',
'mr' : 'FROM_ROCvMatPTR'
}
# Human-readable type names
typenames = {
'i' : 'integer',
'f' : 'float',
'm' : 'list of CvMat',
'mr' : 'list of CvMat',
}
for (t, flags, members) in objects:
map = {'cvtype' : t,
'ourname' : t.replace('Cv', '')}
# gsf is all the generated code for the member accessors
if 'copy' in flags:
a = '.'
else:
a = '->'
gsf = "".join([getset_func_template.substitute(map, accessor = a, member = m, checker = checkers[t], converter = converters[t], rconverter = rconverters[t], typename = typenames[t]) for (m, t) in members.items()])
# gsi is the generated code for the initializer for each accessor
gsi = "".join([getset_init_template.substitute(map, member = m) for (m, t) in members.items()])
# s is the template that pulls everything together
if 'allownull' in flags:
nullcode = """if (o == Py_None) { *dst = (%s*)NULL; return 1; }""" % map['cvtype']
else:
nullcode = ""
if 'copy' in flags:
print >>gen_c[3], gensimple.substitute(map, getset_funcs = gsf, getset_inits = gsi, allownull = nullcode)
else:
print >>gen_c[3], genptr.substitute(map, getset_funcs = gsf, getset_inits = gsi, allownull = nullcode)
print >>gen_c[4], "MKTYPE(%s);" % map['ourname']
for f in gen_c:
f.close()