separated opencv 1.x and opencv 2.x wrappers. moved tests/python/* to modules/python/test

This commit is contained in:
Vadim Pisarevsky 2011-05-03 16:00:31 +00:00
parent 0c9e5f6c9c
commit 7f7965bc93
19 changed files with 4614 additions and 6993 deletions

View File

@ -5,7 +5,8 @@ project(opencv_python)
include_directories(${PYTHON_INCLUDE_PATH})
include_directories(
"${CMAKE_CURRENT_SOURCE_DIR}/src"
"${CMAKE_CURRENT_SOURCE_DIR}/src1"
"${CMAKE_CURRENT_SOURCE_DIR}/src2"
"${CMAKE_SOURCE_DIR}/modules/core/include"
"${CMAKE_SOURCE_DIR}/modules/imgproc/include"
"${CMAKE_SOURCE_DIR}/modules/video/include"
@ -30,64 +31,75 @@ set(opencv_hdrs "${CMAKE_SOURCE_DIR}/modules/core/include/opencv2/core/core.hpp"
"${CMAKE_SOURCE_DIR}/modules/features2d/include/opencv2/features2d/features2d.hpp"
"${CMAKE_SOURCE_DIR}/modules/calib3d/include/opencv2/calib3d/calib3d.hpp"
"${CMAKE_SOURCE_DIR}/modules/objdetect/include/opencv2/objdetect/objdetect.hpp"
"${CMAKE_SOURCE_DIR}/modules/python/src/opencv_extra_api.hpp")
set(generated_hdrs
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_funcs.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_func_tab.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_types.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_type_reg.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_const_reg.h")
"${CMAKE_SOURCE_DIR}/modules/python/src2/opencv_extra_api.hpp")
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3")
endif()
file(GLOB lib_srcs "src/*.cpp")
file(GLOB lib_hdrs "src/*.h")
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/generated0.i
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src/gen.py" "${CMAKE_CURRENT_SOURCE_DIR}/src"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/api
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/defs
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/gen.py
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src1/gen.py" "${CMAKE_CURRENT_SOURCE_DIR}/src1"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src1/api
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src1/defs
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src1/gen.py
)
add_custom_command(
OUTPUT ${generated_hdrs}
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src/gen2.py" ${CMAKE_CURRENT_BINARY_DIR} ${opencv_hdrs}
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/gen2.py
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/hdr_parser.py
DEPENDS ${opencv_hdrs}
)
set(the_target "opencv_python")
add_library(${the_target} ${lib_srcs} ${lib_hdrs} ${lib_int_hdrs} ${CMAKE_CURRENT_BINARY_DIR}/generated0.i src/opencv2x.h src/opencv_extra_api.hpp ${generated_hdrs})
target_link_libraries(${the_target} ${PYTHON_LIBRARIES} opencv_core opencv_imgproc opencv_video opencv_ml opencv_features2d opencv_highgui opencv_calib3d opencv_objdetect opencv_legacy opencv_contrib)
set(cv_target "opencv_python")
add_library(${cv_target} src1/cv.cpp ${CMAKE_CURRENT_BINARY_DIR}/generated0.i)
target_link_libraries(${cv_target} ${PYTHON_LIBRARIES} opencv_core opencv_imgproc opencv_video opencv_ml opencv_features2d opencv_highgui opencv_calib3d opencv_objdetect opencv_legacy opencv_contrib)
set_target_properties(${the_target} PROPERTIES PREFIX "")
set_target_properties(${the_target} PROPERTIES OUTPUT_NAME "cv")
set_target_properties(${cv_target} PROPERTIES PREFIX "")
set_target_properties(${cv_target} PROPERTIES OUTPUT_NAME "cv")
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import distutils.sysconfig; print distutils.sysconfig.get_config_var('SO')"
RESULT_VARIABLE PYTHON_CVPY_PROCESS
OUTPUT_VARIABLE CVPY_SUFFIX
OUTPUT_STRIP_TRAILING_WHITESPACE)
set_target_properties(${the_target} PROPERTIES SUFFIX ${CVPY_SUFFIX})
set_target_properties(${cv_target} PROPERTIES SUFFIX ${CVPY_SUFFIX})
set(cvpy_files cv${CVPY_SUFFIX})
set(cvpymodules ${cv_target})
if(PYTHON_USE_NUMPY)
set(cv2_generated_hdrs
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_funcs.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_func_tab.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_types.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_type_reg.h"
"${CMAKE_CURRENT_BINARY_DIR}/pyopencv_generated_const_reg.h")
add_custom_command(
OUTPUT ${cv2_generated_hdrs}
COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/src2/gen2.py" ${CMAKE_CURRENT_BINARY_DIR} ${opencv_hdrs}
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/gen2.py
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src2/hdr_parser.py
DEPENDS ${opencv_hdrs})
set(cv2_target "opencv2_python")
add_library(${cv2_target} src2/cv2.cpp src2/opencv_extra_api.hpp ${cv2_generated_headers})
target_link_libraries(${cv2_target} ${PYTHON_LIBRARIES} opencv_core opencv_imgproc opencv_video opencv_ml opencv_features2d opencv_highgui opencv_calib3d opencv_objdetect opencv_legacy opencv_contrib)
set_target_properties(${cv2_target} PROPERTIES PREFIX "")
set_target_properties(${cv2_target} PROPERTIES OUTPUT_NAME "cv2")
set_target_properties(${cv2_target} PROPERTIES SUFFIX ${CVPY_SUFFIX})
set(cvpymodules ${cvpymodules} ${cv2_target})
endif()
if(WIN32)
install(TARGETS ${the_target}
RUNTIME DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
LIBRARY DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
ARCHIVE DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
)
install(TARGETS ${cvpymodules}
RUNTIME DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
LIBRARY DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
ARCHIVE DESTINATION "Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages" COMPONENT main
)
else()
#install(FILES ${LIBRARY_OUTPUT_PATH}/cv${CVPY_SUFFIX} DESTINATION ${PYTHON_PACKAGES_PATH})
install(TARGETS ${the_target}
RUNTIME DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main
LIBRARY DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main
ARCHIVE DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main)
#install(FILES ${LIBRARY_OUTPUT_PATH}/cv${CVPY_SUFFIX} DESTINATION ${PYTHON_PACKAGES_PATH})
install(TARGETS ${cvpymodules}
RUNTIME DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main
LIBRARY DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main
ARCHIVE DESTINATION ${PYTHON_PACKAGES_PATH} COMPONENT main)
endif()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,339 +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_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 @@
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:
if f == 'PolarToCart':
print f, [(a.init != None) for a in args]
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()

View File

@ -1,5 +1,12 @@
#ifndef OPENCV2X_PYTHON_WRAPPERS
#define OPENCV2X_PYTHON_WRAPPERS
#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 "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
@ -12,6 +19,21 @@
#include "opencv2/highgui/highgui.hpp"
#include "opencv_extra_api.hpp"
static PyObject* opencv_error = 0;
static int failmsg(const char *fmt, ...)
{
char str[1000];
va_list ap;
va_start(ap, fmt);
vsnprintf(str, sizeof(str), fmt, ap);
va_end(ap);
PyErr_SetString(PyExc_TypeError, str);
return 0;
}
#define ERRWRAP2(expr) \
try \
{ \
@ -693,4 +715,131 @@ static inline PyObject* pyopencv_from(const CvDTreeNode* node)
return value == ivalue ? PyInt_FromLong(ivalue) : PyFloat_FromDouble(value);
}
#define MKTYPE2(NAME) pyopencv_##NAME##_specials(); if (!to_ok(&pyopencv_##NAME##_Type)) return
#include "pyopencv_generated_types.h"
#include "pyopencv_generated_funcs.h"
static PyMethodDef methods[] = {
#include "pyopencv_generated_func_tab.h"
{NULL, NULL},
};
/************************************************************************/
/* Module init */
static int to_ok(PyTypeObject *to)
{
to->tp_alloc = PyType_GenericAlloc;
to->tp_new = PyType_GenericNew;
to->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
return (PyType_Ready(to) == 0);
}
extern "C"
#if defined WIN32 || defined _WIN32
__declspec(dllexport)
#endif
void initcv2()
{
#if PYTHON_USE_NUMPY
import_array();
#endif
#if PYTHON_USE_NUMPY
#include "pyopencv_generated_type_reg.h"
#endif
PyObject* m = Py_InitModule(MODULESTR"", methods);
PyObject* d = PyModule_GetDict(m);
PyDict_SetItemString(d, "__version__", PyString_FromString("$Rev: 4557 $"));
opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
PyDict_SetItemString(d, "error", opencv_error);
// AFAIK the only floating-point constant
PyDict_SetItemString(d, "CV_PI", PyFloat_FromDouble(CV_PI));
#define PUBLISH(I) PyDict_SetItemString(d, #I, PyInt_FromLong(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);
PUBLISH(CV_8UC3);
PUBLISH(CV_8UC4);
PUBLISH(CV_8S);
PUBLISH(CV_8SC1);
PUBLISH(CV_8SC2);
PUBLISH(CV_8SC3);
PUBLISH(CV_8SC4);
PUBLISH(CV_16U);
PUBLISH(CV_16UC1);
PUBLISH(CV_16UC2);
PUBLISH(CV_16UC3);
PUBLISH(CV_16UC4);
PUBLISH(CV_16S);
PUBLISH(CV_16SC1);
PUBLISH(CV_16SC2);
PUBLISH(CV_16SC3);
PUBLISH(CV_16SC4);
PUBLISH(CV_32S);
PUBLISH(CV_32SC1);
PUBLISH(CV_32SC2);
PUBLISH(CV_32SC3);
PUBLISH(CV_32SC4);
PUBLISH(CV_32F);
PUBLISH(CV_32FC1);
PUBLISH(CV_32FC2);
PUBLISH(CV_32FC3);
PUBLISH(CV_32FC4);
PUBLISH(CV_64F);
PUBLISH(CV_64FC1);
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);
#include "pyopencv_generated_const_reg.h"
}

View File

@ -0,0 +1,358 @@
import sys
import math
import time
import random
import numpy
import transformations
import cv
def clamp(a, x, b):
return numpy.maximum(a, numpy.minimum(x, b))
def norm(v):
mag = numpy.sqrt(sum([e * e for e in v]))
return v / mag
class Vec3:
def __init__(self, x, y, z):
self.v = (x, y, z)
def x(self):
return self.v[0]
def y(self):
return self.v[1]
def z(self):
return self.v[2]
def __repr__(self):
return "<Vec3 (%s,%s,%s)>" % tuple([repr(c) for c in self.v])
def __add__(self, other):
return Vec3(*[self.v[i] + other.v[i] for i in range(3)])
def __sub__(self, other):
return Vec3(*[self.v[i] - other.v[i] for i in range(3)])
def __mul__(self, other):
if isinstance(other, Vec3):
return Vec3(*[self.v[i] * other.v[i] for i in range(3)])
else:
return Vec3(*[self.v[i] * other for i in range(3)])
def mag2(self):
return sum([e * e for e in self.v])
def __abs__(self):
return numpy.sqrt(sum([e * e for e in self.v]))
def norm(self):
return self * (1.0 / abs(self))
def dot(self, other):
return sum([self.v[i] * other.v[i] for i in range(3)])
def cross(self, other):
(ax, ay, az) = self.v
(bx, by, bz) = other.v
return Vec3(ay * bz - by * az, az * bx - bz * ax, ax * by - bx * ay)
class Ray:
def __init__(self, o, d):
self.o = o
self.d = d
def project(self, d):
return self.o + self.d * d
class Camera:
def __init__(self, F):
R = Vec3(1., 0., 0.)
U = Vec3(0, 1., 0)
self.center = Vec3(0, 0, 0)
self.pcenter = Vec3(0, 0, F)
self.up = U
self.right = R
def genray(self, x, y):
""" -1 <= y <= 1 """
r = numpy.sqrt(x * x + y * y)
if 0:
rprime = r + (0.17 * r**2)
else:
rprime = (10 * numpy.sqrt(17 * r + 25) - 50) / 17
print "scale", rprime / r
x *= rprime / r
y *= rprime / r
o = self.center
r = (self.pcenter + (self.right * x) + (self.up * y)) - o
return Ray(o, r.norm())
class Sphere:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def hit(self, r):
# a = mag2(r.d)
a = 1.
v = r.o - self.center
b = 2 * r.d.dot(v)
c = self.center.mag2() + r.o.mag2() + -2 * self.center.dot(r.o) - (self.radius ** 2)
det = (b * b) - (4 * c)
pred = 0 < det
sq = numpy.sqrt(abs(det))
h0 = (-b - sq) / (2)
h1 = (-b + sq) / (2)
h = numpy.minimum(h0, h1)
pred = pred & (h > 0)
normal = (r.project(h) - self.center) * (1.0 / self.radius)
return (pred, numpy.where(pred, h, 999999.), normal)
def pt2plane(p, plane):
return p.dot(plane) * (1. / abs(plane))
class Plane:
def __init__(self, p, n, right):
self.D = -pt2plane(p, n)
self.Pn = n
self.right = right
self.rightD = -pt2plane(p, right)
self.up = n.cross(right)
self.upD = -pt2plane(p, self.up)
def hit(self, r):
Vd = self.Pn.dot(r.d)
V0 = -(self.Pn.dot(r.o) + self.D)
h = V0 / Vd
pred = (0 <= h)
return (pred, numpy.where(pred, h, 999999.), self.Pn)
def localxy(self, loc):
x = (loc.dot(self.right) + self.rightD)
y = (loc.dot(self.up) + self.upD)
return (x, y)
# lena = numpy.fromstring(cv.LoadImage("../samples/c/lena.jpg", 0).tostring(), numpy.uint8) / 255.0
def texture(xy):
x,y = xy
xa = numpy.floor(x * 512)
ya = numpy.floor(y * 512)
a = (512 * ya) + xa
safe = (0 <= x) & (0 <= y) & (x < 1) & (y < 1)
if 0:
a = numpy.where(safe, a, 0).astype(numpy.int)
return numpy.where(safe, numpy.take(lena, a), 0.0)
else:
xi = numpy.floor(x * 11).astype(numpy.int)
yi = numpy.floor(y * 11).astype(numpy.int)
inside = (1 <= xi) & (xi < 10) & (2 <= yi) & (yi < 9)
checker = (xi & 1) ^ (yi & 1)
final = numpy.where(inside, checker, 1.0)
return numpy.where(safe, final, 0.5)
def under(vv, m):
return Vec3(*(numpy.dot(m, vv.v + (1,))[:3]))
class Renderer:
def __init__(self, w, h, oversample):
self.w = w
self.h = h
random.seed(1)
x = numpy.arange(self.w*self.h) % self.w
y = numpy.floor(numpy.arange(self.w*self.h) / self.w)
h2 = h / 2.0
w2 = w / 2.0
self.r = [ None ] * oversample
for o in range(oversample):
stoch_x = numpy.random.rand(self.w * self.h)
stoch_y = numpy.random.rand(self.w * self.h)
nx = (x + stoch_x - 0.5 - w2) / h2
ny = (y + stoch_y - 0.5 - h2) / h2
self.r[o] = cam.genray(nx, ny)
self.rnds = [random.random() for i in range(10)]
def frame(self, i):
rnds = self.rnds
roll = math.sin(i * .01 * rnds[0] + rnds[1])
pitch = math.sin(i * .01 * rnds[2] + rnds[3])
yaw = math.pi * math.sin(i * .01 * rnds[4] + rnds[5])
x = math.sin(i * 0.01 * rnds[6])
y = math.sin(i * 0.01 * rnds[7])
x,y,z = -0.5,0.5,1
roll,pitch,yaw = (0,0,0)
z = 4 + 3 * math.sin(i * 0.1 * rnds[8])
print z
rz = transformations.euler_matrix(roll, pitch, yaw)
p = Plane(Vec3(x, y, z), under(Vec3(0,0,-1), rz), under(Vec3(1, 0, 0), rz))
acc = 0
for r in self.r:
(pred, h, norm) = p.hit(r)
l = numpy.where(pred, texture(p.localxy(r.project(h))), 0.0)
acc += l
acc *= (1.0 / len(self.r))
# print "took", time.time() - st
img = cv.CreateMat(self.h, self.w, cv.CV_8UC1)
cv.SetData(img, (clamp(0, acc, 1) * 255).astype(numpy.uint8).tostring(), self.w)
return img
#########################################################################
num_x_ints = 8
num_y_ints = 6
num_pts = num_x_ints * num_y_ints
def get_corners(mono, refine = False):
(ok, corners) = cv.FindChessboardCorners(mono, (num_x_ints, num_y_ints), cv.CV_CALIB_CB_ADAPTIVE_THRESH | cv.CV_CALIB_CB_NORMALIZE_IMAGE)
if refine and ok:
corners = cv.FindCornerSubPix(mono, corners, (5,5), (-1,-1), ( cv.CV_TERMCRIT_EPS+cv.CV_TERMCRIT_ITER, 30, 0.1 ))
return (ok, corners)
def mk_object_points(nimages, squaresize = 1):
opts = cv.CreateMat(nimages * num_pts, 3, cv.CV_32FC1)
for i in range(nimages):
for j in range(num_pts):
opts[i * num_pts + j, 0] = (j / num_x_ints) * squaresize
opts[i * num_pts + j, 1] = (j % num_x_ints) * squaresize
opts[i * num_pts + j, 2] = 0
return opts
def mk_image_points(goodcorners):
ipts = cv.CreateMat(len(goodcorners) * num_pts, 2, cv.CV_32FC1)
for (i, co) in enumerate(goodcorners):
for j in range(num_pts):
ipts[i * num_pts + j, 0] = co[j][0]
ipts[i * num_pts + j, 1] = co[j][1]
return ipts
def mk_point_counts(nimages):
npts = cv.CreateMat(nimages, 1, cv.CV_32SC1)
for i in range(nimages):
npts[i, 0] = num_pts
return npts
def cvmat_iterator(cvmat):
for i in range(cvmat.rows):
for j in range(cvmat.cols):
yield cvmat[i,j]
cam = Camera(3.0)
rend = Renderer(640, 480, 2)
cv.NamedWindow("snap")
#images = [rend.frame(i) for i in range(0, 2000, 400)]
images = [rend.frame(i) for i in [1200]]
if 0:
for i,img in enumerate(images):
cv.SaveImage("final/%06d.png" % i, img)
size = cv.GetSize(images[0])
corners = [get_corners(i) for i in images]
goodcorners = [co for (im, (ok, co)) in zip(images, corners) if ok]
def checkerboard_error(xformed):
def pt2line(a, b, c):
x0,y0 = a
x1,y1 = b
x2,y2 = c
return abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
errorsum = 0.
for im in xformed:
for row in range(6):
l0 = im[8 * row]
l1 = im[8 * row + 7]
for col in range(1, 7):
e = pt2line(im[8 * row + col], l0, l1)
#print "row", row, "e", e
errorsum += e
return errorsum
if True:
from scipy.optimize import fmin
def xf(pt, poly):
x, y = pt
r = math.sqrt((x - 320) ** 2 + (y - 240) ** 2)
fr = poly(r) / r
return (320 + (x - 320) * fr, 240 + (y - 240) * fr)
def silly(p, goodcorners):
# print "eval", p
d = 1.0 # - sum(p)
poly = numpy.poly1d(list(p) + [d, 0.])
xformed = [[xf(pt, poly) for pt in co] for co in goodcorners]
return checkerboard_error(xformed)
x0 = [ 0. ]
#print silly(x0, goodcorners)
print "initial error", silly(x0, goodcorners)
xopt = fmin(silly, x0, args=(goodcorners,))
print "xopt", xopt
print "final error", silly(xopt, goodcorners)
d = 1.0 # - sum(xopt)
poly = numpy.poly1d(list(xopt) + [d, 0.])
print "final polynomial"
print poly
for co in goodcorners:
scrib = cv.CreateMat(480, 640, cv.CV_8UC3)
cv.SetZero(scrib)
cv.DrawChessboardCorners(scrib, (num_x_ints, num_y_ints), [xf(pt, poly) for pt in co], True)
cv.ShowImage("snap", scrib)
cv.WaitKey()
sys.exit(0)
for (i, (img, (ok, co))) in enumerate(zip(images, corners)):
scrib = cv.CreateMat(img.rows, img.cols, cv.CV_8UC3)
cv.CvtColor(img, scrib, cv.CV_GRAY2BGR)
if ok:
cv.DrawChessboardCorners(scrib, (num_x_ints, num_y_ints), co, True)
cv.ShowImage("snap", scrib)
cv.WaitKey()
print len(goodcorners)
ipts = mk_image_points(goodcorners)
opts = mk_object_points(len(goodcorners), .1)
npts = mk_point_counts(len(goodcorners))
intrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
distortion = cv.CreateMat(4, 1, cv.CV_64FC1)
cv.SetZero(intrinsics)
cv.SetZero(distortion)
# focal lengths have 1/1 ratio
intrinsics[0,0] = 1.0
intrinsics[1,1] = 1.0
cv.CalibrateCamera2(opts, ipts, npts,
cv.GetSize(images[0]),
intrinsics,
distortion,
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
flags = 0) # cv.CV_CALIB_ZERO_TANGENT_DIST)
print "D =", list(cvmat_iterator(distortion))
print "K =", list(cvmat_iterator(intrinsics))
mapx = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
mapy = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
cv.InitUndistortMap(intrinsics, distortion, mapx, mapy)
for img in images:
r = cv.CloneMat(img)
cv.Remap(img, r, mapx, mapy)
cv.ShowImage("snap", r)
cv.WaitKey()

View File

@ -0,0 +1,34 @@
import cv
import unittest
class TestGoodFeaturesToTrack(unittest.TestCase):
def test(self):
arr = cv.LoadImage("../samples/c/lena.jpg", 0)
original = cv.CloneImage(arr)
size = cv.GetSize(arr)
eig_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
temp_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
threshes = [ x / 100. for x in range(1,10) ]
results = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])
# Check that GoodFeaturesToTrack has not modified input image
self.assert_(arr.tostring() == original.tostring())
# Check for repeatability
for i in range(10):
results2 = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])
self.assert_(results == results2)
for t0,t1 in zip(threshes, threshes[1:]):
r0 = results[t0]
r1 = results[t1]
# Increasing thresh should make result list shorter
self.assert_(len(r0) > len(r1))
# Increasing thresh should monly truncate result list
self.assert_(r0[:len(r1)] == r1)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,7 @@
import cv
import numpy as np
cv.NamedWindow('Leak')
while 1:
leak = np.random.random((480, 640)) * 255
cv.ShowImage('Leak', leak.astype(np.uint8))
cv.WaitKey(10)

View File

@ -0,0 +1,10 @@
import cv
import numpy as np
import time
while True:
for i in range(4000):
a = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)
b = cv.CreateMat(1024, 1024, cv.CV_8UC1)
c = cv.CreateMatND([1024,1024], cv.CV_8UC1)
print "pause..."

View File

@ -0,0 +1,6 @@
import cv
import math
import time
while True:
h = cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)

View File

@ -0,0 +1,9 @@
import cv
import math
import time
N=50000
print "leak4"
while True:
seq=list((i*1., i*1.) for i in range(N))
cv.Moments(seq)

2177
modules/python/test/test.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
import urllib
import cv
import Image
import unittest
class TestLoadImage(unittest.TestCase):
def setUp(self):
open("large.jpg", "w").write(urllib.urlopen("http://www.cs.ubc.ca/labs/lci/curious_george/img/ROS_bug_imgs/IMG_3560.jpg").read())
def test_load(self):
pilim = Image.open("large.jpg")
cvim = cv.LoadImage("large.jpg")
self.assert_(len(pilim.tostring()) == len(cvim.tostring()))
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,89 @@
import unittest
import random
import time
import math
import sys
import array
import os
import cv
def find_sample(s):
for d in ["../samples/c/", "../doc/pics/"]:
path = os.path.join(d, s)
if os.access(path, os.R_OK):
return path
return s
class TestTickets(unittest.TestCase):
def test_2542670(self):
xys = [(94, 121), (94, 122), (93, 123), (92, 123), (91, 124), (91, 125), (91, 126), (92, 127), (92, 128), (92, 129), (92, 130), (92, 131), (91, 132), (90, 131), (90, 130), (90, 131), (91, 132), (92, 133), (92, 134), (93, 135), (94, 136), (94, 137), (94, 138), (95, 139), (96, 140), (96, 141), (96, 142), (96, 143), (97, 144), (97, 145), (98, 146), (99, 146), (100, 146), (101, 146), (102, 146), (103, 146), (104, 146), (105, 146), (106, 146), (107, 146), (108, 146), (109, 146), (110, 146), (111, 146), (112, 146), (113, 146), (114, 146), (115, 146), (116, 146), (117, 146), (118, 146), (119, 146), (120, 146), (121, 146), (122, 146), (123, 146), (124, 146), (125, 146), (126, 146), (126, 145), (126, 144), (126, 143), (126, 142), (126, 141), (126, 140), (127, 139), (127, 138), (127, 137), (127, 136), (127, 135), (127, 134), (127, 133), (128, 132), (129, 132), (130, 131), (131, 130), (131, 129), (131, 128), (132, 127), (133, 126), (134, 125), (134, 124), (135, 123), (136, 122), (136, 121), (135, 121), (134, 121), (133, 121), (132, 121), (131, 121), (130, 121), (129, 121), (128, 121), (127, 121), (126, 121), (125, 121), (124, 121), (123, 121), (122, 121), (121, 121), (120, 121), (119, 121), (118, 121), (117, 121), (116, 121), (115, 121), (114, 121), (113, 121), (112, 121), (111, 121), (110, 121), (109, 121), (108, 121), (107, 121), (106, 121), (105, 121), (104, 121), (103, 121), (102, 121), (101, 121), (100, 121), (99, 121), (98, 121), (97, 121), (96, 121), (95, 121)]
#xys = xys[:12] + xys[16:]
pts = cv.CreateMat(len(xys), 1, cv.CV_32SC2)
for i,(x,y) in enumerate(xys):
pts[i,0] = (x, y)
storage = cv.CreateMemStorage()
hull = cv.ConvexHull2(pts, storage)
hullp = cv.ConvexHull2(pts, storage, return_points = 1)
defects = cv.ConvexityDefects(pts, hull, storage)
vis = cv.CreateImage((1000,1000), 8, 3)
x0 = min([x for (x,y) in xys]) - 10
x1 = max([x for (x,y) in xys]) + 10
y0 = min([y for (y,y) in xys]) - 10
y1 = max([y for (y,y) in xys]) + 10
def xform(pt):
x,y = pt
return (1000 * (x - x0) / (x1 - x0),
1000 * (y - y0) / (y1 - y0))
for d in defects[:2]:
cv.Zero(vis)
# First draw the defect as a red triangle
cv.FillConvexPoly(vis, [xform(p) for p in d[:3]], cv.RGB(255,0,0))
# Draw the convex hull as a thick green line
for a,b in zip(hullp, hullp[1:]):
cv.Line(vis, xform(a), xform(b), cv.RGB(0,128,0), 3)
# Draw the original contour as a white line
for a,b in zip(xys, xys[1:]):
cv.Line(vis, xform(a), xform(b), (255,255,255))
self.snap(vis)
def test_2686307(self):
lena = cv.LoadImage(find_sample("lena.jpg"), 1)
dst = cv.CreateImage((512,512), 8, 3)
cv.Set(dst, (128,192,255))
mask = cv.CreateImage((512,512), 8, 1)
cv.Zero(mask)
cv.Rectangle(mask, (10,10), (300,100), 255, -1)
cv.Copy(lena, dst, mask)
self.snapL([lena, dst, mask])
m = cv.CreateMat(480, 640, cv.CV_8UC1)
print "ji", m
print m.rows, m.cols, m.type, m.step
def snap(self, img):
self.snapL([img])
def snapL(self, L):
for i,img in enumerate(L):
cv.NamedWindow("snap-%d" % i, 1)
cv.ShowImage("snap-%d" % i, img)
cv.WaitKey()
cv.DestroyAllWindows()
if __name__ == '__main__':
random.seed(0)
if len(sys.argv) == 1:
suite = unittest.TestLoader().loadTestsFromTestCase(TestTickets)
unittest.TextTestRunner(verbosity=2).run(suite)
else:
suite = unittest.TestSuite()
suite.addTest(TestTickets(sys.argv[1]))
unittest.TextTestRunner(verbosity=2).run(suite)

File diff suppressed because it is too large Load Diff