"atomic bomb" commit. Reorganized OpenCV directory structure
This commit is contained in:
1
interfaces/swig/python/.cvsignore
Normal file
1
interfaces/swig/python/.cvsignore
Normal file
@@ -0,0 +1 @@
|
||||
build
|
118
interfaces/swig/python/CMakeLists.txt
Normal file
118
interfaces/swig/python/CMakeLists.txt
Normal file
@@ -0,0 +1,118 @@
|
||||
# ----------------------------------------------------------------------------
|
||||
# CMake file for python support
|
||||
# ----------------------------------------------------------------------------
|
||||
project(python_support)
|
||||
|
||||
find_package(SWIG REQUIRED)
|
||||
include(${SWIG_USE_FILE})
|
||||
|
||||
include_directories(${PYTHON_INCLUDE_PATH})
|
||||
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../filtered)
|
||||
|
||||
if(MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3")
|
||||
endif()
|
||||
|
||||
# ----------------------------------- cv module ------------------------------
|
||||
|
||||
set_source_files_properties(cv.i PROPERTIES
|
||||
CPLUSPLUS ON
|
||||
SWIG_FLAGS -includeall
|
||||
SWIG_FLAGS -DSKIP_INCLUDES
|
||||
)
|
||||
|
||||
set(opencv_headers
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/cxtypes.h
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/cxcore.h
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/cvtypes.h
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/cv.h
|
||||
)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/cvaliases_autogen.i
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/utils/extract_aliases.py
|
||||
${opencv_headers} > ${CMAKE_CURRENT_BINARY_DIR}/cvaliases_autogen.i
|
||||
DEPENDS ${opencv_headers}
|
||||
)
|
||||
|
||||
set(SWIG_MODULE_cv_EXTRA_DEPS
|
||||
imagedata.i cvarr.i ${CMAKE_CURRENT_BINARY_DIR}/cvaliases_autogen.i cvaliases.i pyhelpers.i
|
||||
nointpb.i pytypemaps.i cvshadow.i cvseq.i
|
||||
../general/cv.i ../general/memory.i ../general/typemaps.i
|
||||
../general/extensions.i ../general/doublepointers.i
|
||||
../general/sizeof.i ../general/cvmacros.i
|
||||
)
|
||||
|
||||
SWIG_ADD_MODULE(cv python cv.i cvshadow.cpp error.cpp error.h pyhelpers.cpp pyhelpers.h cvshadow.h pycvseq.hpp)
|
||||
SWIG_LINK_LIBRARIES(cv ${PYTHON_LIBRARIES} cxcore cv)
|
||||
|
||||
# ----------------------------------- ml module ------------------------------
|
||||
|
||||
set_source_files_properties(ml.i PROPERTIES
|
||||
CPLUSPLUS ON
|
||||
SWIG_FLAGS -includeall
|
||||
SWIG_FLAGS -DSKIP_INCLUDES
|
||||
)
|
||||
|
||||
set(SWIG_MODULE_ml_EXTRA_DEPS
|
||||
nointpb.i pytypemaps.i
|
||||
../general/memory.i ../general/typemaps.i
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/ml.h
|
||||
)
|
||||
|
||||
SWIG_ADD_MODULE(ml python ml.i pyhelpers.cpp pyhelpers.h)
|
||||
SWIG_LINK_LIBRARIES(ml ${PYTHON_LIBRARIES} cxcore ml)
|
||||
|
||||
# --------------------------------highgui module ------------------------------
|
||||
|
||||
set_source_files_properties(highgui.i PROPERTIES
|
||||
CPLUSPLUS ON
|
||||
SWIG_FLAGS -includeall
|
||||
SWIG_FLAGS -DSKIP_INCLUDES
|
||||
)
|
||||
|
||||
set(SWIG_MODULE_highgui_EXTRA_DEPS
|
||||
nointpb.i pytypemaps.i
|
||||
../general/highgui.i
|
||||
../general/memory.i ../general/typemaps.i
|
||||
${CMAKE_SOURCE_DIR}/include/opencv/highgui.h
|
||||
)
|
||||
|
||||
SWIG_ADD_MODULE(highgui python highgui.i pyhelpers.cpp pyhelpers.h)
|
||||
SWIG_LINK_LIBRARIES(highgui ${PYTHON_LIBRARIES} cxcore cv highgui)
|
||||
|
||||
# ------------------------------ installation ----------------------------------
|
||||
|
||||
if(WIN32)
|
||||
set_target_properties(
|
||||
${SWIG_MODULE_cv_REAL_NAME}
|
||||
${SWIG_MODULE_ml_REAL_NAME}
|
||||
${SWIG_MODULE_highgui_REAL_NAME}
|
||||
PROPERTIES SUFFIX ".pyd")
|
||||
endif()
|
||||
|
||||
get_target_property(LOC_CV ${SWIG_MODULE_cv_REAL_NAME} LOCATION)
|
||||
get_target_property(LOC_ML ${SWIG_MODULE_ml_REAL_NAME} LOCATION)
|
||||
get_target_property(LOC_HIGHGUI ${SWIG_MODULE_highgui_REAL_NAME} LOCATION)
|
||||
|
||||
set(pyopencv_files __init__.py adaptors.py matlab_syntax.py
|
||||
${CMAKE_CURRENT_BINARY_DIR}/cv.py
|
||||
${CMAKE_CURRENT_BINARY_DIR}/ml.py
|
||||
${CMAKE_CURRENT_BINARY_DIR}/highgui.py)
|
||||
|
||||
foreach(m ${LOC_CV} ${LOC_ML} ${LOC_HIGHGUI})
|
||||
string(REPLACE "\$(OutDir)" "\${CMAKE_INSTALL_CONFIG_NAME}" m1 ${m})
|
||||
set(pyopencv_files ${pyopencv_files} ${m1})
|
||||
endforeach()
|
||||
|
||||
|
||||
# TODO: need to compile *.py files
|
||||
if(WIN32)
|
||||
install(FILES ${pyopencv_files} DESTINATION
|
||||
"Python${PYTHON_VERSION_MAJOR_MINOR}/Lib/site-packages/opencv"
|
||||
COMPONENT main)
|
||||
else()
|
||||
install(FILES ${pyopencv_files} DESTINATION ${PYTHON_PLUGIN_INSTALL_PATH} COMPONENT main)
|
||||
endif()
|
||||
|
76
interfaces/swig/python/__init__.py
Normal file
76
interfaces/swig/python/__init__.py
Normal file
@@ -0,0 +1,76 @@
|
||||
#########################################################################################
|
||||
#
|
||||
# IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
#
|
||||
# By downloading, copying, installing or using the software you agree to this license.
|
||||
# If you do not agree to this license, do not download, install,
|
||||
# copy or use the software.
|
||||
#
|
||||
#
|
||||
# Intel License Agreement
|
||||
# For Open Source Computer Vision Library
|
||||
#
|
||||
# Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
# Third party copyrights are property of their respective owners.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistribution's of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
# * The name of Intel Corporation may not be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# This software is provided by the copyright holders and contributors "as is" and
|
||||
# any express or implied warranties, including, but not limited to, the implied
|
||||
# warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
# In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
# indirect, incidental, special, exemplary, or consequential damages
|
||||
# (including, but not limited to, procurement of substitute goods or services;
|
||||
# loss of use, data, or profits; or business interruption) however caused
|
||||
# and on any theory of liability, whether in contract, strict liability,
|
||||
# or tort (including negligence or otherwise) arising in any way out of
|
||||
# the use of this software, even if advised of the possibility of such damage.
|
||||
#
|
||||
#########################################################################################
|
||||
|
||||
# 2004-03-16, Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
# Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
"""The Open Computer Vision Library
|
||||
|
||||
OpenCV is the Open Computer Vision library, an open source effort originally started
|
||||
by intel to provide computer vision algorithms for standard PC hardware.
|
||||
|
||||
This wrapper was semi-automatically created from the C/C++ headers and therefore
|
||||
contains no Python documentation. Because all identifiers are identical to their
|
||||
C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
|
||||
|
||||
In detail, this python package contains four sub-modules:
|
||||
|
||||
cv core components (cxcore and cv)
|
||||
ml machine learning
|
||||
highgui simple user interface, video and image I/O
|
||||
adaptors pure python module offering conversion to numpy/scipy matrices
|
||||
and PIL (python imaging library) images
|
||||
matlab_syntax pure python module offering syntax that is similar to Matlab
|
||||
for those who switched
|
||||
|
||||
All methods and data types from cv, ml and adaptors are automatically imported into
|
||||
the opencv namespace. Contents from highgui and matlab_syntax must be explicitly
|
||||
imported - to avoid conflicts with other UI toolkits and the python matlab interface.
|
||||
"""
|
||||
|
||||
# the module consists of these four sub-modules
|
||||
__all__ = ['cv', 'ml', 'highgui', 'adaptors', 'matlab_syntax']
|
||||
|
||||
# always import functionality from cxcore, cv and ml to this namespace
|
||||
# try to import PIL and numpy adaptors
|
||||
from cv import *
|
||||
from ml import *
|
||||
from adaptors import *
|
109468
interfaces/swig/python/_cv.cpp
Normal file
109468
interfaces/swig/python/_cv.cpp
Normal file
File diff suppressed because it is too large
Load Diff
9429
interfaces/swig/python/_highgui.cpp
Normal file
9429
interfaces/swig/python/_highgui.cpp
Normal file
File diff suppressed because it is too large
Load Diff
50413
interfaces/swig/python/_ml.cpp
Normal file
50413
interfaces/swig/python/_ml.cpp
Normal file
File diff suppressed because it is too large
Load Diff
339
interfaces/swig/python/adaptors.py
Normal file
339
interfaces/swig/python/adaptors.py
Normal file
@@ -0,0 +1,339 @@
|
||||
#########################################################################################
|
||||
#
|
||||
# IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
#
|
||||
# By downloading, copying, installing or using the software you agree to this license.
|
||||
# If you do not agree to this license, do not download, install,
|
||||
# copy or use the software.
|
||||
#
|
||||
#
|
||||
# Intel License Agreement
|
||||
# For Open Source Computer Vision Library
|
||||
#
|
||||
# Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
# Third party copyrights are property of their respective owners.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistribution's of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
# * The name of Intel Corporation may not be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# This software is provided by the copyright holders and contributors "as is" and
|
||||
# any express or implied warranties, including, but not limited to, the implied
|
||||
# warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
# In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
# indirect, incidental, special, exemplary, or consequential damages
|
||||
# (including, but not limited to, procurement of substitute goods or services;
|
||||
# loss of use, data, or profits; or business interruption) however caused
|
||||
# and on any theory of liability, whether in contract, strict liability,
|
||||
# or tort (including negligence or otherwise) arising in any way out of
|
||||
# the use of this software, even if advised of the possibility of such damage.
|
||||
#
|
||||
#########################################################################################
|
||||
|
||||
|
||||
# 2004-03-16, Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
# Institute of Communications Engineering, RWTH Aachen University
|
||||
# 2007-02-xx, direct interface to numpy by Vicent Mas <vmas@carabos.com>
|
||||
# Carabos Coop. V.
|
||||
# 2007-10-08, try/catch
|
||||
|
||||
"""Adaptors to interchange data with numpy and/or PIL
|
||||
|
||||
This module provides explicit conversion of OpenCV images/matrices to and from
|
||||
the Python Imaging Library (PIL) and python's newest numeric library (numpy).
|
||||
|
||||
Currently supported image/matrix formats are:
|
||||
- 3 x 8 bit RGB (GBR)
|
||||
- 1 x 8 bit Grayscale
|
||||
- 1 x 32 bit Float
|
||||
|
||||
In numpy, images are represented as multidimensional arrays with
|
||||
a third dimension representing the image channels if more than one
|
||||
channel is present.
|
||||
"""
|
||||
|
||||
import cv
|
||||
|
||||
try:
|
||||
import PIL.Image
|
||||
|
||||
###########################################################################
|
||||
def Ipl2PIL(input):
|
||||
"""Converts an OpenCV/IPL image to PIL the Python Imaging Library.
|
||||
|
||||
Supported input image formats are
|
||||
IPL_DEPTH_8U x 1 channel
|
||||
IPL_DEPTH_8U x 3 channels
|
||||
IPL_DEPTH_32F x 1 channel
|
||||
"""
|
||||
|
||||
if not isinstance(input, cv.CvMat):
|
||||
raise TypeError, 'must be called with a cv.CvMat!'
|
||||
|
||||
#orientation
|
||||
if input.origin == 0:
|
||||
orientation = 1 # top left
|
||||
elif input.origin == 1:
|
||||
orientation = -1 # bottom left
|
||||
else:
|
||||
raise ValueError, 'origin must be 0 or 1!'
|
||||
|
||||
# mode dictionary:
|
||||
# (channels, depth) : (source mode, dest mode, depth in byte)
|
||||
mode_list = {
|
||||
(1, cv.IPL_DEPTH_8U) : ("L", "L", 1),
|
||||
(3, cv.IPL_DEPTH_8U) : ("BGR", "RGB", 3),
|
||||
(1, cv.IPL_DEPTH_32F) : ("F", "F", 4)
|
||||
}
|
||||
|
||||
key = (input.nChannels, input.depth)
|
||||
if not mode_list.has_key(key):
|
||||
raise ValueError, 'unknown or unsupported input mode'
|
||||
|
||||
modes = mode_list[key]
|
||||
|
||||
return PIL.Image.fromstring(
|
||||
modes[1], # mode
|
||||
(input.width, input.height), # size tuple
|
||||
input.imageData, # data
|
||||
"raw",
|
||||
modes[0], # raw mode
|
||||
input.widthStep, # stride
|
||||
orientation # orientation
|
||||
)
|
||||
|
||||
|
||||
###########################################################################
|
||||
def PIL2Ipl(input):
|
||||
"""Converts a PIL image to the OpenCV/IPL CvMat data format.
|
||||
|
||||
Supported input image formats are:
|
||||
RGB
|
||||
L
|
||||
F
|
||||
"""
|
||||
|
||||
if not (isinstance(input, PIL.Image.Image)):
|
||||
raise TypeError, 'Must be called with PIL.Image.Image!'
|
||||
|
||||
# mode dictionary:
|
||||
# (pil_mode : (ipl_depth, ipl_channels)
|
||||
mode_list = {
|
||||
"RGB" : (cv.IPL_DEPTH_8U, 3),
|
||||
"L" : (cv.IPL_DEPTH_8U, 1),
|
||||
"F" : (cv.IPL_DEPTH_32F, 1)
|
||||
}
|
||||
|
||||
if not mode_list.has_key(input.mode):
|
||||
raise ValueError, 'unknown or unsupported input mode'
|
||||
|
||||
result = cv.cvCreateImage(
|
||||
cv.cvSize(input.size[0], input.size[1]), # size
|
||||
mode_list[input.mode][0], # depth
|
||||
mode_list[input.mode][1] # channels
|
||||
)
|
||||
|
||||
# set imageData
|
||||
result.imageData = input.tostring()
|
||||
return result
|
||||
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
#############################################################################
|
||||
#############################################################################
|
||||
|
||||
try:
|
||||
|
||||
import numpy
|
||||
|
||||
|
||||
###########################################################################
|
||||
def NumPy2Ipl(input):
|
||||
"""Converts a numpy array to the OpenCV/IPL CvMat data format.
|
||||
|
||||
Supported input array layouts:
|
||||
2 dimensions of numpy.uint8
|
||||
3 dimensions of numpy.uint8
|
||||
2 dimensions of numpy.float32
|
||||
2 dimensions of numpy.float64
|
||||
"""
|
||||
|
||||
if not isinstance(input, numpy.ndarray):
|
||||
raise TypeError, 'Must be called with numpy.ndarray!'
|
||||
|
||||
# Check the number of dimensions of the input array
|
||||
ndim = input.ndim
|
||||
if not ndim in (2, 3):
|
||||
raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
|
||||
|
||||
# Get the number of channels
|
||||
if ndim == 2:
|
||||
channels = 1
|
||||
else:
|
||||
channels = input.shape[2]
|
||||
|
||||
# Get the image depth
|
||||
if input.dtype == numpy.uint8:
|
||||
depth = cv.IPL_DEPTH_8U
|
||||
elif input.dtype == numpy.float32:
|
||||
depth = cv.IPL_DEPTH_32F
|
||||
elif input.dtype == numpy.float64:
|
||||
depth = cv.IPL_DEPTH_64F
|
||||
|
||||
# supported modes list: [(channels, dtype), ...]
|
||||
modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32), (1, numpy.float64)]
|
||||
|
||||
# Check if the input array layout is supported
|
||||
if not (channels, input.dtype) in modes_list:
|
||||
raise ValueError, 'Unknown or unsupported input mode'
|
||||
|
||||
result = cv.cvCreateImage(
|
||||
cv.cvSize(input.shape[1], input.shape[0]), # size
|
||||
depth, # depth
|
||||
channels # channels
|
||||
)
|
||||
|
||||
# set imageData
|
||||
result.imageData = input.tostring()
|
||||
|
||||
return result
|
||||
|
||||
|
||||
###########################################################################
|
||||
def Ipl2NumPy(input):
|
||||
"""Converts an OpenCV/IPL image to a numpy array.
|
||||
|
||||
Supported input image formats are
|
||||
IPL_DEPTH_8U x 1 channel
|
||||
IPL_DEPTH_8U x 3 channels
|
||||
IPL_DEPTH_32F x 1 channel
|
||||
IPL_DEPTH_32F x 2 channels
|
||||
IPL_DEPTH_32S x 1 channel
|
||||
IPL_DEPTH_64F x 1 channel
|
||||
IPL_DEPTH_64F x 2 channels
|
||||
"""
|
||||
|
||||
if not isinstance(input, cv.CvMat):
|
||||
raise TypeError, 'must be called with a cv.CvMat!'
|
||||
|
||||
# data type dictionary:
|
||||
# (channels, depth) : numpy dtype
|
||||
ipl2dtype = {
|
||||
(1, cv.IPL_DEPTH_8U) : numpy.uint8,
|
||||
(3, cv.IPL_DEPTH_8U) : numpy.uint8,
|
||||
(1, cv.IPL_DEPTH_32F) : numpy.float32,
|
||||
(2, cv.IPL_DEPTH_32F) : numpy.float32,
|
||||
(1, cv.IPL_DEPTH_32S) : numpy.int32,
|
||||
(1, cv.IPL_DEPTH_64F) : numpy.float64,
|
||||
(2, cv.IPL_DEPTH_64F) : numpy.float64
|
||||
}
|
||||
|
||||
key = (input.nChannels, input.depth)
|
||||
if not ipl2dtype.has_key(key):
|
||||
raise ValueError, 'unknown or unsupported input mode'
|
||||
|
||||
# Get the numpy array and reshape it correctly
|
||||
# ATTENTION: flipped dimensions width/height on 2007-11-15
|
||||
if input.nChannels == 1:
|
||||
array_1d = numpy.fromstring(input.imageData, dtype=ipl2dtype[key])
|
||||
return numpy.reshape(array_1d, (input.height, input.width))
|
||||
elif input.nChannels == 2:
|
||||
array_1d = numpy.fromstring(input.imageData, dtype=ipl2dtype[key])
|
||||
return numpy.reshape(array_1d, (input.height, input.width, 2))
|
||||
elif input.nChannels == 3:
|
||||
# Change the order of channels from BGR to RGB
|
||||
rgb = cv.cvCreateImage(cv.cvSize(input.width, input.height), input.depth, 3)
|
||||
cv.cvCvtColor(input, rgb, cv.CV_BGR2RGB)
|
||||
array_1d = numpy.fromstring(rgb.imageData, dtype=ipl2dtype[key])
|
||||
return numpy.reshape(array_1d, (input.height, input.width, 3))
|
||||
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
###########################################################################
|
||||
###########################################################################
|
||||
|
||||
|
||||
try:
|
||||
|
||||
import PIL.Image
|
||||
import numpy
|
||||
|
||||
###########################################################################
|
||||
def PIL2NumPy(input):
|
||||
"""THIS METHOD IS DEPRECATED
|
||||
|
||||
Converts a PIL image to a numpy array.
|
||||
|
||||
Supported input image formats are:
|
||||
RGB
|
||||
L
|
||||
F
|
||||
"""
|
||||
|
||||
if not (isinstance(input, PIL.Image.Image)):
|
||||
raise TypeError, 'Must be called with PIL.Image.Image!'
|
||||
|
||||
# modes dictionary:
|
||||
# pil_mode : numpy dtype
|
||||
modes_map = {
|
||||
"RGB" : numpy.uint8,
|
||||
"L" : numpy.uint8,
|
||||
"F" : numpy.float32
|
||||
}
|
||||
|
||||
if not modes_map.has_key(input.mode):
|
||||
raise ValueError, 'Unknown or unsupported input mode!. Supported modes are RGB, L and F.'
|
||||
|
||||
result_ro = numpy.asarray(input, dtype=modes_map[input.mode]) # Read-only array
|
||||
return result_ro.copy() # Return a writeable array
|
||||
|
||||
|
||||
###########################################################################
|
||||
def NumPy2PIL(input):
|
||||
"""THIS METHOD IS DEPRECATED
|
||||
|
||||
Converts a numpy array to a PIL image.
|
||||
|
||||
Supported input array layouts:
|
||||
2 dimensions of numpy.uint8
|
||||
3 dimensions of numpy.uint8
|
||||
2 dimensions of numpy.float32
|
||||
"""
|
||||
|
||||
if not isinstance(input, numpy.ndarray):
|
||||
raise TypeError, 'Must be called with numpy.ndarray!'
|
||||
|
||||
# Check the number of dimensions of the input array
|
||||
ndim = input.ndim
|
||||
if not ndim in (2, 3):
|
||||
raise ValueError, 'Only 2D-arrays and 3D-arrays are supported!'
|
||||
|
||||
if ndim == 2:
|
||||
channels = 1
|
||||
else:
|
||||
channels = input.shape[2]
|
||||
|
||||
# supported modes list: [(channels, dtype), ...]
|
||||
modes_list = [(1, numpy.uint8), (3, numpy.uint8), (1, numpy.float32)]
|
||||
|
||||
mode = (channels, input.dtype)
|
||||
if not mode in modes_list:
|
||||
raise ValueError, 'Unknown or unsupported input mode'
|
||||
|
||||
return PIL.Image.fromarray(input)
|
||||
|
||||
except ImportError:
|
||||
pass
|
98
interfaces/swig/python/cv.i
Normal file
98
interfaces/swig/python/cv.i
Normal file
@@ -0,0 +1,98 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
// 2004-03-16, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
|
||||
// Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
%{
|
||||
#include "pyhelpers.h"
|
||||
#include "pycvseq.hpp"
|
||||
#include "error.h"
|
||||
%}
|
||||
|
||||
|
||||
// direct SWIG to generate python docstrings
|
||||
%feature("autodoc", 1);
|
||||
|
||||
// include python-specific files
|
||||
%include "./nointpb.i"
|
||||
%include "./pytypemaps.i"
|
||||
%include "./cvshadow.i"
|
||||
|
||||
// parse OpenCV headers
|
||||
%include "../general/cv.i"
|
||||
|
||||
// Accessors for the CvMat and IplImage data structure are defined here
|
||||
%include "./cvarr.i"
|
||||
|
||||
// Python sequence compatibility for CvSeq
|
||||
%include "./cvseq.i"
|
||||
|
||||
|
||||
%include "./imagedata.i"
|
||||
|
||||
// We integrate OpenCV error handling into the Python exception mechanism
|
||||
%include "./error.h"
|
||||
|
||||
|
||||
// include some wrappers to manipulate CvSeq types
|
||||
%include "./pycvseq.hpp"
|
||||
|
||||
// aliases from #defines
|
||||
%include "./cvaliases_autogen.i"
|
||||
%include "./cvaliases.i"
|
||||
|
||||
%pythoncode
|
||||
%{
|
||||
|
||||
__doc__ = """
|
||||
OpenCV is the Intel Open CV library, an open source effort to provide
|
||||
computer vision algorithms for standard PC hardware.
|
||||
|
||||
This wrapper was semi-automatically created from the C/C++ headers and therefore
|
||||
contains no Python documentation. Because all identifiers are identical to their
|
||||
C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
|
||||
"""
|
||||
|
||||
# this tells OpenCV not to call exit() on errors but throw a python exception instead
|
||||
cvRedirectError(function_ptr_generator(), void_ptr_generator(), void_ptrptr_generator())
|
||||
|
||||
%}
|
8627
interfaces/swig/python/cv.py
Normal file
8627
interfaces/swig/python/cv.py
Normal file
File diff suppressed because it is too large
Load Diff
61
interfaces/swig/python/cvaliases.i
Normal file
61
interfaces/swig/python/cvaliases.i
Normal file
@@ -0,0 +1,61 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
/*M//
|
||||
// This file contains custom python-based aliases for some methods where
|
||||
// an autogenerated wrapper was unusable or missing.
|
||||
//M*/
|
||||
|
||||
// This macro removes the wrapper for the function from_name, and creates
|
||||
// an alias to to_name, so calling from_name() will invoke to_name()
|
||||
%define %myalias(from_name, to_name)
|
||||
%ignore from_name;
|
||||
%pythoncode%{
|
||||
from_name = to_name;
|
||||
%}
|
||||
%enddef
|
||||
|
||||
// Map functions using IplImage ** argument to CvArr ** function instead
|
||||
%myalias(cvCalcBackProject, cvCalcArrBackProject);
|
||||
%myalias(cvCalcBackProjectPatch, cvCalcArrBackProjectPatch);
|
||||
%myalias(cvCalcImageHist, cvCalcArrHist);
|
||||
%myalias(cvCalcHist, cvCalcArrHist);
|
||||
|
56
interfaces/swig/python/cvaliases_autogen.i
Normal file
56
interfaces/swig/python/cvaliases_autogen.i
Normal file
@@ -0,0 +1,56 @@
|
||||
/** This file was automatically generated using util/extract_aliases.py script */
|
||||
%module cv
|
||||
%pythoncode %{
|
||||
IPL_ALIGN_DWORD=IPL_ALIGN_4BYTES
|
||||
IPL_ALIGN_QWORD=IPL_ALIGN_8BYTES
|
||||
CV_MAKE_TYPE=CV_MAKETYPE
|
||||
CV_IS_CONT_MAT=CV_IS_MAT_CONT
|
||||
CV_HIST_TREE=CV_HIST_SPARSE
|
||||
CV_TERMCRIT_NUMBER=CV_TERMCRIT_ITER
|
||||
CV_SEQ_ELTYPE_PTR=CV_USRTYPE1
|
||||
CV_GRAPH=CV_SEQ_KIND_GRAPH
|
||||
CV_SEQ_CONTOUR=CV_SEQ_POLYGON
|
||||
CV_STORAGE_WRITE_TEXT=CV_STORAGE_WRITE
|
||||
CV_STORAGE_WRITE_BINARY=CV_STORAGE_WRITE
|
||||
CV_NODE_INTEGER=CV_NODE_INT
|
||||
CV_NODE_FLOAT=CV_NODE_REAL
|
||||
CV_NODE_STRING=CV_NODE_STR
|
||||
cvGetSubArr=cvGetSubRect
|
||||
cvZero=cvSetZero
|
||||
cvCvtScale=cvConvertScale
|
||||
cvScale=cvConvertScale
|
||||
cvCvtScaleAbs=cvConvertScaleAbs
|
||||
cvCheckArray=cvCheckArr
|
||||
cvMatMulAddEx=cvGEMM
|
||||
cvMatMulAddS=cvTransform
|
||||
cvT=cvTranspose
|
||||
cvMirror=cvFlip
|
||||
cvInv=cvInvert
|
||||
cvMahalonobis=cvMahalanobis
|
||||
CV_DXT_INVERSE_SCALE=CV_DXT_INV_SCALE
|
||||
cvFFT=cvDFT
|
||||
cvGraphFindEdge=cvFindGraphEdge
|
||||
cvGraphFindEdgeByPtr=cvFindGraphEdgeByPtr
|
||||
cvDrawRect=cvRectangle
|
||||
cvDrawLine=cvLine
|
||||
cvDrawCircle=cvCircle
|
||||
cvDrawEllipse=cvEllipse
|
||||
cvDrawPolyLine=cvPolyLine
|
||||
CV_FONT_VECTOR0=CV_FONT_HERSHEY_SIMPLEX
|
||||
CV_RGB2RGBA=CV_BGR2BGRA
|
||||
CV_RGBA2RGB=CV_BGRA2BGR
|
||||
CV_RGB2BGRA=CV_BGR2RGBA
|
||||
CV_BGRA2RGB=CV_RGBA2BGR
|
||||
CV_RGB2BGR=CV_BGR2RGB
|
||||
CV_RGBA2BGRA=CV_BGRA2RGBA
|
||||
CV_GRAY2RGB=CV_GRAY2BGR
|
||||
CV_GRAY2RGBA=CV_GRAY2BGRA
|
||||
CV_BayerBG2RGB=CV_BayerRG2BGR
|
||||
CV_BayerGB2RGB=CV_BayerGR2BGR
|
||||
CV_BayerRG2RGB=CV_BayerBG2BGR
|
||||
CV_BayerGR2RGB=CV_BayerGB2BGR
|
||||
CV_FM_LMEDS_ONLY=CV_LMEDS
|
||||
CV_FM_RANSAC_ONLY=CV_RANSAC
|
||||
CV_FM_LMEDS=CV_LMEDS
|
||||
CV_FM_RANSAC=CV_RANSAC
|
||||
%}
|
534
interfaces/swig/python/cvarr.i
Normal file
534
interfaces/swig/python/cvarr.i
Normal file
@@ -0,0 +1,534 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
// 2006-02-17 Roman Stanchak <rstancha@cse.wustl.edu>
|
||||
// 2006-07-19 Moved most operators to general/cvarr_operators.i for use with other languages
|
||||
// 2009-01-07 Added numpy array interface, Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
|
||||
/*M//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Macros for extending CvMat and IplImage -- primarily for operator overloading
|
||||
//////////////////////////////////////////////////////////////////////////////////////////M*/
|
||||
|
||||
// Macro to define python function of form B = A.f(c)
|
||||
// where A is a CvArr type, c and B are arbitrary types
|
||||
%define %wrap_cvGeneric_CvArr(cname, rettype, pyfunc, argtype, cvfunc, newobjcall)
|
||||
%newobject cname::pyfunc(argtype arg);
|
||||
%extend cname {
|
||||
rettype pyfunc(argtype arg){
|
||||
rettype retarg = newobjcall;
|
||||
cvfunc;
|
||||
return retarg;
|
||||
}
|
||||
}
|
||||
%enddef
|
||||
|
||||
// Macro to define python function of the form B = A.f(c)
|
||||
// where A and B are both CvArr of same size and type
|
||||
%define %wrap_cvArr_binaryop(pyfunc, argtype, cvfunc)
|
||||
%wrap_cvGeneric_CvArr(CvMat, CvMat *, pyfunc, argtype, cvfunc,
|
||||
cvCreateMat(self->rows, self->cols, self->type));
|
||||
%wrap_cvGeneric_CvArr(IplImage, IplImage *, pyfunc, argtype, cvfunc,
|
||||
cvCreateImage(cvGetSize(self), self->depth, self->nChannels));
|
||||
%enddef
|
||||
|
||||
// Macro to define python function of the form A = A.f(c)
|
||||
// where f modifies A inplace
|
||||
// use for +=, etc
|
||||
%define %wrap_cvGeneric_InPlace(cname, rettype, pyfunc, argtype, cvfunc)
|
||||
%wrap_cvGeneric_CvArr(cname, rettype, pyfunc, argtype, cvfunc, self);
|
||||
%enddef
|
||||
|
||||
/*M//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Macros to map operators to specific OpenCV functions
|
||||
//////////////////////////////////////////////////////////////////////////////////////////M*/
|
||||
|
||||
// map any OpenCV function of form cvFunc(src1, src2, dst)
|
||||
%define %wrap_cvArith(pyfunc, cvfunc)
|
||||
%wrap_cvArr_binaryop(pyfunc, CvArr *, cvfunc(self, arg, retarg));
|
||||
%enddef
|
||||
|
||||
// map any OpenCV function of form cvFunc(src1, value, dst)
|
||||
%define %wrap_cvArithS(pyfunc, cvfuncS)
|
||||
%wrap_cvArr_binaryop(pyfunc, CvScalar, cvfuncS(self, arg, retarg));
|
||||
%wrap_cvArr_binaryop(pyfunc, double, cvfuncS(self, cvScalar(arg), retarg));
|
||||
%enddef
|
||||
|
||||
// same as wrap_cvArith
|
||||
%define %wrap_cvLogic(pyfunc, cvfunc)
|
||||
%wrap_cvArr_binaryop(pyfunc, CvArr *, cvfunc(self, arg, retarg))
|
||||
%enddef
|
||||
|
||||
// same as wrap_cvArithS
|
||||
%define %wrap_cvLogicS(pyfunc, cvfuncS)
|
||||
%wrap_cvArr_binaryop(pyfunc, CvScalar, cvfuncS(self, arg, retarg));
|
||||
%wrap_cvArr_binaryop(pyfunc, double, cvfuncS(self, cvScalar(arg), retarg));
|
||||
%enddef
|
||||
|
||||
// Macro to map logical operations to cvCmp
|
||||
%define %wrap_cvCmp(pyfunc, cmp_op)
|
||||
%wrap_cvGeneric_CvArr(CvMat, CvMat *, pyfunc, CvMat *,
|
||||
cvCmp(self, arg, retarg, cmp_op),
|
||||
cvCreateMat(self->rows, self->cols, CV_8U));
|
||||
%wrap_cvGeneric_CvArr(IplImage, IplImage *, pyfunc, IplImage *,
|
||||
cvCmp(self, arg, retarg, cmp_op),
|
||||
cvCreateImage(cvGetSize(self), 8, 1));
|
||||
%enddef
|
||||
|
||||
%define %wrap_cvCmpS(pyfunc, cmp_op)
|
||||
%wrap_cvGeneric_CvArr(CvMat, CvMat *, pyfunc, double,
|
||||
cvCmpS(self, arg, retarg, cmp_op),
|
||||
cvCreateMat(self->rows, self->cols, CV_8U));
|
||||
%wrap_cvGeneric_CvArr(IplImage, IplImage *, pyfunc, double,
|
||||
cvCmpS(self, arg, retarg, cmp_op),
|
||||
cvCreateImage(cvGetSize(self), 8, 1));
|
||||
%enddef
|
||||
|
||||
// special case for cvScale, /, *
|
||||
%define %wrap_cvScale(pyfunc, scale)
|
||||
%wrap_cvGeneric_CvArr(CvMat, CvMat *, pyfunc, double,
|
||||
cvScale(self, retarg, scale),
|
||||
cvCreateMat(self->rows, self->cols, self->type));
|
||||
%wrap_cvGeneric_CvArr(IplImage, IplImage *, pyfunc, double,
|
||||
cvScale(self, retarg, scale),
|
||||
cvCreateImage(cvGetSize(self), self->depth, self->nChannels));
|
||||
%enddef
|
||||
|
||||
/*M//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Actual Operator Declarations
|
||||
//////////////////////////////////////////////////////////////////////////////////////////M*/
|
||||
|
||||
// Arithmetic operators
|
||||
%wrap_cvArith(__radd__, cvAdd);
|
||||
|
||||
// special case for reverse operations
|
||||
%wrap_cvArr_binaryop(__rsub__, CvArr *, cvSub(arg, self, retarg));
|
||||
%wrap_cvArr_binaryop(__rdiv__, CvArr *, cvDiv(arg, self, retarg));
|
||||
%wrap_cvArr_binaryop(__rmul__, CvArr *, cvMul(arg, self, retarg));
|
||||
|
||||
%wrap_cvArithS(__radd__, cvAddS);
|
||||
%wrap_cvArithS(__rsub__, cvSubRS);
|
||||
|
||||
%wrap_cvScale(__rmul__, arg);
|
||||
|
||||
%wrap_cvLogicS(__ror__, cvOrS)
|
||||
%wrap_cvLogicS(__rand__, cvAndS)
|
||||
%wrap_cvLogicS(__rxor__, cvXorS)
|
||||
|
||||
%wrap_cvCmpS(__req__, CV_CMP_EQ);
|
||||
%wrap_cvCmpS(__rgt__, CV_CMP_GT);
|
||||
%wrap_cvCmpS(__rge__, CV_CMP_GE);
|
||||
%wrap_cvCmpS(__rlt__, CV_CMP_LT);
|
||||
%wrap_cvCmpS(__rle__, CV_CMP_LE);
|
||||
%wrap_cvCmpS(__rne__, CV_CMP_NE);
|
||||
|
||||
// special case for scalar-array division
|
||||
%wrap_cvGeneric_CvArr(CvMat, CvMat *, __rdiv__, double,
|
||||
cvDiv(NULL, self, retarg, arg),
|
||||
cvCreateMat(self->rows, self->cols, self->type));
|
||||
|
||||
// misc operators for python
|
||||
%wrap_cvArr_binaryop(__pow__, double, cvPow(self, retarg, arg))
|
||||
|
||||
// TODO -- other Python operators listed below and at:
|
||||
// http://docs.python.org/ref/numeric-types.html
|
||||
|
||||
// __abs__ -- cvAbs
|
||||
// __nonzero__
|
||||
// __hash__ ??
|
||||
// __repr__ -- full string representation
|
||||
// __str__ -- compact representation
|
||||
// __call__ -- ??
|
||||
// __len__ -- number of rows? or elements?
|
||||
// __iter__ -- ??
|
||||
// __contains__ -- cvCmpS, cvMax ?
|
||||
// __floordiv__ ??
|
||||
// __mul__ -- cvGEMM
|
||||
// __lshift__ -- ??
|
||||
// __rshift__ -- ??
|
||||
// __pow__ -- cvPow
|
||||
|
||||
// Called to implement the unary arithmetic operations (-, +, abs() and ~).
|
||||
//__neg__( self)
|
||||
//__pos__( self)
|
||||
//__abs__( self)
|
||||
//__invert__( self)
|
||||
|
||||
// Called to implement the built-in functions complex(), int(), long(), and float(). Should return a value of the appropriate type. Can I abuse this to return an array of the correct type??? scipy only allows return of length 1 arrays.
|
||||
// __complex__( self )
|
||||
// __int__( self )
|
||||
// __long__( self )
|
||||
// __float__( self )
|
||||
|
||||
/*M//////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Slice access and assignment for CvArr types
|
||||
//////////////////////////////////////////////////////////////////////////////////////////M*/
|
||||
|
||||
// TODO: CvMatND
|
||||
|
||||
%newobject CvMat::__getitem__(PyObject * object);
|
||||
%newobject _IplImage::__getitem__(PyObject * object);
|
||||
|
||||
%header %{
|
||||
int checkSliceBounds(const CvRect & rect, int w, int h){
|
||||
//printf("__setitem__ slice(%d:%d, %d:%d) array(%d,%d)", rect.x, rect.y, rect.x+rect.width, rect.y+rect.height, w, h);
|
||||
if(rect.width<=0 || rect.height<=0 ||
|
||||
rect.width>w || rect.height>h ||
|
||||
rect.x<0 || rect.y<0 ||
|
||||
rect.x>= w || rect.y >=h){
|
||||
char errstr[256];
|
||||
|
||||
// previous function already set error string
|
||||
if(rect.width==0 && rect.height==0 && rect.x==0 && rect.y==0) return -1;
|
||||
|
||||
sprintf(errstr, "Requested slice [ %d:%d %d:%d ] oversteps array sized [ %d %d ]",
|
||||
rect.x, rect.y, rect.x+rect.width, rect.y+rect.height, w, h);
|
||||
PyErr_SetString(PyExc_IndexError, errstr);
|
||||
//PyErr_SetString(PyExc_ValueError, errstr);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
%}
|
||||
// Macro to check bounds of slice and throw error if outside
|
||||
%define CHECK_SLICE_BOUNDS(rect,w,h,retval)
|
||||
if(CheckSliceBounds(&rect,w,h)==-1){ return retval; } else{}
|
||||
%enddef
|
||||
|
||||
// slice access and assignment for CvMat
|
||||
%extend CvMat
|
||||
{
|
||||
char * __str__(){
|
||||
static char str[8];
|
||||
cvArrPrint( self );
|
||||
str[0]=0;
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
// scalar assignment
|
||||
void __setitem__(PyObject * object, double val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, cvScalarAll(val));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvPoint val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, cvScalar(val.x, val.y));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvPoint2D32f val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, );
|
||||
cvSet(&tmp, cvScalar(val.x, val.y));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvScalar val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, );
|
||||
cvSet(&tmp, val);
|
||||
}
|
||||
|
||||
// array slice assignment
|
||||
void __setitem__(PyObject * object, CvArr * arr){
|
||||
CvMat tmp, src_stub, *src;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
|
||||
// Reshape source array to fit destination
|
||||
// This will be used a lot for small arrays b/c
|
||||
// PyObject_to_CvArr tries to compress a 2-D python
|
||||
// array with 1-4 columns into a multichannel vector
|
||||
src=cvReshape(arr, &src_stub, CV_MAT_CN(tmp.type), tmp.rows);
|
||||
|
||||
cvConvert(src, &tmp);
|
||||
}
|
||||
|
||||
// slice access
|
||||
PyObject * __getitem__(PyObject * object){
|
||||
CvMat * mat;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
CHECK_SLICE_BOUNDS( subrect, self->cols, self->rows, NULL );
|
||||
if(subrect.width==1 && subrect.height==1){
|
||||
CvScalar * s;
|
||||
int type = cvGetElemType( self );
|
||||
if(CV_MAT_CN(type) > 1){
|
||||
s = new CvScalar;
|
||||
*s = cvGet2D( self, subrect.y, subrect.x );
|
||||
return SWIG_NewPointerObj( s, $descriptor(CvScalar *), 1 );
|
||||
}
|
||||
switch(CV_MAT_DEPTH(type)){
|
||||
case CV_8U:
|
||||
return PyLong_FromUnsignedLong( CV_MAT_ELEM(*self, uchar, subrect.y, subrect.x ) );
|
||||
case CV_8S:
|
||||
return PyLong_FromLong( CV_MAT_ELEM(*self, char, subrect.y, subrect.x ) );
|
||||
case CV_16U:
|
||||
return PyLong_FromUnsignedLong( CV_MAT_ELEM(*self, ushort, subrect.y, subrect.x ) );
|
||||
case CV_16S:
|
||||
return PyLong_FromLong( CV_MAT_ELEM(*self, short, subrect.y, subrect.x ) );
|
||||
case CV_32S:
|
||||
return PyLong_FromLong( CV_MAT_ELEM(*self, int, subrect.y, subrect.x ) );
|
||||
case CV_32F:
|
||||
return PyFloat_FromDouble( CV_MAT_ELEM(*self, float, subrect.y, subrect.x) );
|
||||
case CV_64F:
|
||||
return PyFloat_FromDouble( CV_MAT_ELEM(*self, double, subrect.y, subrect.x) );
|
||||
}
|
||||
}
|
||||
mat = (CvMat *) cvAlloc(sizeof(CvMat));
|
||||
cvGetSubRect(self, mat, subrect);
|
||||
|
||||
// cvGetSubRect doesn't do this since it assumes mat lives on the stack
|
||||
mat->hdr_refcount = self->hdr_refcount;
|
||||
mat->refcount = self->refcount;
|
||||
cvIncRefData(mat);
|
||||
|
||||
return SWIG_NewPointerObj( mat, $descriptor(CvMat *), 1 );
|
||||
}
|
||||
|
||||
// ~ operator -- swig doesn't generate this from the C++ equivalent
|
||||
CvMat * __invert__(){
|
||||
CvMat * res = cvCreateMat(self->rows, self->cols, self->type);
|
||||
cvNot( self, res );
|
||||
return res;
|
||||
}
|
||||
|
||||
%pythoncode %{
|
||||
def __iter__(self):
|
||||
"""
|
||||
generator function iterating through rows in matrix or elements in vector
|
||||
"""
|
||||
if self.rows==1:
|
||||
return self.colrange()
|
||||
return self.rowrange()
|
||||
|
||||
def rowrange(self):
|
||||
"""
|
||||
generator function iterating along rows in matrix
|
||||
"""
|
||||
for i in range(self.rows):
|
||||
yield self[i]
|
||||
|
||||
def colrange(self):
|
||||
"""
|
||||
generator function iterating along columns in matrix
|
||||
"""
|
||||
for i in range(self.cols):
|
||||
yield self[:,i]
|
||||
|
||||
# if arg is None, python still calls our operator overloads
|
||||
# but we want
|
||||
# if mat != None
|
||||
# if mat == None
|
||||
# to do the right thing -- so redefine __ne__ and __eq__
|
||||
|
||||
def __eq__(self, arg):
|
||||
"""
|
||||
__eq__(self, None)
|
||||
__eq__(self, CvArr src)
|
||||
__eq__(self, double val)
|
||||
"""
|
||||
|
||||
if not arg:
|
||||
return False
|
||||
return _cv.CvMat___eq__(self, arg)
|
||||
def __ne__(self, arg):
|
||||
"""
|
||||
__ne__(self, None)
|
||||
__ne__(self, CvArr src)
|
||||
__ne__(self, double val)
|
||||
"""
|
||||
|
||||
if not arg:
|
||||
return True
|
||||
return _cv.CvMat___ne__(self, arg)
|
||||
|
||||
def __get_array_interface__ (self):
|
||||
"""Compose numpy array interface
|
||||
|
||||
Via the numpy array interface, OpenCV data structures can be directly passed to numpy
|
||||
methods without copying / converting. This tremendously speeds up mixing code from
|
||||
OpenCV and numpy.
|
||||
|
||||
See: http://numpy.scipy.org/array_interface.shtml
|
||||
|
||||
@author Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
@date 2009-01-07
|
||||
"""
|
||||
|
||||
if self.depth == IPL_DEPTH_8U:
|
||||
typestr = '|u1'
|
||||
bytes_per_pixel = 1
|
||||
elif self.depth == IPL_DEPTH_8S:
|
||||
typestr = '|i1'
|
||||
bytes_per_pixel = 1
|
||||
elif self.depth == IPL_DEPTH_16U:
|
||||
typestr = '|u2'
|
||||
bytes_per_pixel = 2
|
||||
elif self.depth == IPL_DEPTH_16S:
|
||||
typestr = '|i2'
|
||||
bytes_per_pixel = 2
|
||||
elif self.depth == IPL_DEPTH_32S:
|
||||
typestr = '|i4'
|
||||
bytes_per_pixel = 4
|
||||
elif self.depth == IPL_DEPTH_32F:
|
||||
typestr = '|f4'
|
||||
bytes_per_pixel = 4
|
||||
elif self.depth == IPL_DEPTH_64F:
|
||||
typestr = '|f8'
|
||||
bytes_per_pixel = 8
|
||||
else:
|
||||
raise TypeError("unknown resp. unhandled OpenCV image/matrix format")
|
||||
|
||||
if self.nChannels == 1:
|
||||
# monochrome image, matrix with a single channel
|
||||
return {'shape': (self.height, self.width),
|
||||
'typestr': typestr,
|
||||
'version': 3,
|
||||
|
||||
'data': (int (self.data.ptr), False),
|
||||
'strides': (int (self.widthStep), int (bytes_per_pixel))}
|
||||
else:
|
||||
# color image, image with alpha, matrix with multiple channels
|
||||
return {'shape': (self.height, self.width, self.nChannels),
|
||||
'typestr': typestr,
|
||||
'version': 3,
|
||||
|
||||
'data': (int (self.data.ptr), False),
|
||||
'strides': (int (self.widthStep), int (self.nChannels * bytes_per_pixel), int (bytes_per_pixel))}
|
||||
|
||||
__array_interface__ = property (__get_array_interface__, doc = "numpy array interface description")
|
||||
|
||||
%}
|
||||
|
||||
} //extend CvMat
|
||||
|
||||
// slice access and assignment for IplImage
|
||||
%extend _IplImage
|
||||
{
|
||||
char * __str__(){
|
||||
static char str[8];
|
||||
cvArrPrint( self );
|
||||
str[0]=0;
|
||||
return str;
|
||||
}
|
||||
|
||||
// scalar assignment
|
||||
void __setitem__(PyObject * object, double val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, cvScalarAll(val));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvPoint val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, cvScalar(val.x, val.y));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvPoint2D32f val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, cvScalar(val.x, val.y));
|
||||
}
|
||||
void __setitem__(PyObject * object, CvScalar val){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvSet(&tmp, val);
|
||||
}
|
||||
|
||||
// array slice assignment
|
||||
void __setitem__(PyObject * object, CvArr * arr){
|
||||
CvMat tmp;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
cvGetSubRect(self, &tmp, subrect);
|
||||
cvConvert(arr, &tmp);
|
||||
}
|
||||
|
||||
// slice access
|
||||
PyObject * __getitem__(PyObject * object){
|
||||
CvMat mat;
|
||||
IplImage * im;
|
||||
CvRect subrect = PySlice_to_CvRect( self, object );
|
||||
|
||||
// return scalar if single element
|
||||
if(subrect.width==1 && subrect.height==1){
|
||||
CvScalar * s;
|
||||
int type = cvGetElemType( self );
|
||||
if(CV_MAT_CN(type) > 1){
|
||||
s = new CvScalar;
|
||||
*s = cvGet2D( self, subrect.y, subrect.x );
|
||||
return SWIG_NewPointerObj( s, $descriptor(CvScalar *), 1 );
|
||||
}
|
||||
switch(CV_MAT_DEPTH(type)){
|
||||
case CV_8U:
|
||||
return PyLong_FromUnsignedLong( CV_IMAGE_ELEM(self, uchar, subrect.y, subrect.x ) );
|
||||
case CV_8S:
|
||||
return PyLong_FromLong( CV_IMAGE_ELEM(self, char, subrect.y, subrect.x ) );
|
||||
case CV_16U:
|
||||
return PyLong_FromUnsignedLong( CV_IMAGE_ELEM(self, ushort, subrect.y, subrect.x ) );
|
||||
case CV_16S:
|
||||
return PyLong_FromLong( CV_IMAGE_ELEM(self, short, subrect.y, subrect.x ) );
|
||||
case CV_32S:
|
||||
return PyLong_FromLong( CV_IMAGE_ELEM(self, int, subrect.y, subrect.x ) );
|
||||
case CV_32F:
|
||||
return PyFloat_FromDouble( CV_IMAGE_ELEM(self, float, subrect.y, subrect.x) );
|
||||
case CV_64F:
|
||||
return PyFloat_FromDouble( CV_IMAGE_ELEM(self, double, subrect.y, subrect.x) );
|
||||
}
|
||||
}
|
||||
|
||||
// otherwise return array
|
||||
im = (IplImage *) cvAlloc(sizeof(IplImage));
|
||||
cvGetSubRect(self, &mat, subrect);
|
||||
im = cvGetImage(&mat, im);
|
||||
return SWIG_NewPointerObj( im, $descriptor(_IplImage *), 1 );
|
||||
}
|
||||
}
|
||||
|
105
interfaces/swig/python/cvseq.i
Normal file
105
interfaces/swig/python/cvseq.i
Normal file
@@ -0,0 +1,105 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
// 2006-08-02 Roman Stanchak <rstancha@cse.wustl.edu>
|
||||
|
||||
%include "pycvseq.hpp"
|
||||
%template (CvTuple_CvPoint_2) CvTuple<CvPoint,2>;
|
||||
%template (CvTuple_float_2) CvTuple<float,2>;
|
||||
%template (CvTuple_float_3) CvTuple<float,3>;
|
||||
|
||||
%template (CvSeq_CvPoint) CvTypedSeq<CvPoint>;
|
||||
%template (CvSeq_CvPoint2D32f) CvTypedSeq<CvPoint2D32f>;
|
||||
%template (CvSeq_CvRect) CvTypedSeq<CvRect>;
|
||||
%template (CvSeq_CvSeq) CvTypedSeq<CvSeq *>;
|
||||
%template (CvSeq_CvQuadEdge2D) CvTypedSeq<CvQuadEdge2D>;
|
||||
%template (CvSeq_CvConnectedComp) CvTypedSeq<CvConnectedComp>;
|
||||
%template (CvSeq_CvPoint_2) CvTypedSeq< CvTuple<CvPoint,2> >;
|
||||
%template (CvSeq_float_2) CvTypedSeq< CvTuple<float,2> >;
|
||||
%template (CvSeq_float_3) CvTypedSeq< CvTuple<float,3> >;
|
||||
|
||||
%extend CvSeq {
|
||||
%pythoncode %{
|
||||
def __iter__(self):
|
||||
"""
|
||||
generator function iterating elements in the sequence
|
||||
"""
|
||||
for i in range(self.total):
|
||||
yield self[i]
|
||||
|
||||
def vrange(self):
|
||||
"""
|
||||
generator function iterating along v_next
|
||||
"""
|
||||
s = self
|
||||
t = type(self)
|
||||
while s:
|
||||
yield s
|
||||
s = t.cast(s.v_next)
|
||||
|
||||
def hrange(self):
|
||||
"""
|
||||
generator function iterating along h_next
|
||||
"""
|
||||
s = self
|
||||
t = type(self)
|
||||
while s:
|
||||
yield s
|
||||
s = t.cast(s.h_next)
|
||||
%}
|
||||
}
|
||||
|
||||
// accessor to turn edges into a typed sequence
|
||||
%extend CvSubdiv2D {
|
||||
CvTypedSeq<CvQuadEdge2D> * typed_edges;
|
||||
CvTypedSeq<CvQuadEdge2D> * typed_edges_get(){
|
||||
return (CvTypedSeq<CvQuadEdge2D> *) self->edges;
|
||||
}
|
||||
void typed_edges_set( CvTypedSeq<CvQuadEdge2D> * ){
|
||||
}
|
||||
%pythoncode %{
|
||||
def __iter__(self):
|
||||
s = CvSeq_QuadEdge2D.cast(self)
|
||||
for i in range(s.total):
|
||||
yield s[i]
|
||||
%}
|
||||
}
|
||||
|
83
interfaces/swig/python/cvshadow.cpp
Normal file
83
interfaces/swig/python/cvshadow.cpp
Normal file
@@ -0,0 +1,83 @@
|
||||
#include <cxcore.h>
|
||||
#include <cv.h>
|
||||
#include <stdio.h>
|
||||
#include "cvshadow.h"
|
||||
|
||||
CvArr * cvCvtSeqToArray_Shadow( const CvSeq* seq, CvArr * elements, CvSlice slice){
|
||||
CvMat stub, *mat=(CvMat *)elements;
|
||||
if(!CV_IS_MAT(mat)){
|
||||
mat = cvGetMat(elements, &stub);
|
||||
}
|
||||
cvCvtSeqToArray( seq, mat->data.ptr, slice );
|
||||
return elements;
|
||||
}
|
||||
|
||||
double cvArcLength_Shadow( const CvSeq * seq, CvSlice slice, int is_closed){
|
||||
return cvArcLength( seq, slice, is_closed );
|
||||
}
|
||||
double cvArcLength_Shadow( const CvArr * arr, CvSlice slice, int is_closed){
|
||||
return cvArcLength( arr, slice, is_closed );
|
||||
}
|
||||
|
||||
void cvMoments_Shadow( const CvSeq * seq, CvMoments * moments, int binary ){
|
||||
cvMoments( seq, moments, binary );
|
||||
}
|
||||
|
||||
void cvMoments_Shadow( const CvArr * seq, CvMoments * moments, int binary ){
|
||||
cvMoments( seq, moments, binary );
|
||||
}
|
||||
|
||||
|
||||
CvTypedSeq<CvRect> * cvHaarDetectObjects_Shadow( const CvArr* image, CvHaarClassifierCascade* cascade,
|
||||
CvMemStorage* storage, double scale_factor, int min_neighbors, int flags,
|
||||
CvSize min_size )
|
||||
{
|
||||
return (CvTypedSeq<CvRect> *) cvHaarDetectObjects( image, cascade, storage, scale_factor,
|
||||
min_neighbors, flags, min_size);
|
||||
}
|
||||
|
||||
CvTypedSeq<CvConnectedComp> * cvSegmentMotion_Shadow( const CvArr* mhi, CvArr* seg_mask, CvMemStorage* storage,
|
||||
double timestamp, double seg_thresh ){
|
||||
return (CvTypedSeq<CvConnectedComp> *) cvSegmentMotion( mhi, seg_mask, storage, timestamp, seg_thresh );
|
||||
}
|
||||
|
||||
CvTypedSeq<CvPoint> * cvApproxPoly_Shadow( const void* src_seq, int header_size, CvMemStorage* storage,
|
||||
int method, double parameter, int parameter2)
|
||||
{
|
||||
return (CvTypedSeq<CvPoint> *) cvApproxPoly( src_seq, header_size, storage, method, parameter, parameter2 );
|
||||
}
|
||||
|
||||
// Always return a new Mat of indices
|
||||
CvMat * cvConvexHull2_Shadow( const CvArr * points, int orientation, int return_points){
|
||||
CvMat * hull=0;
|
||||
CvMat * points_mat=(CvMat *) points;
|
||||
CvSeq * points_seq=(CvSeq *) points;
|
||||
int npoints, type;
|
||||
|
||||
if(CV_IS_MAT(points_mat)){
|
||||
npoints = MAX(points_mat->rows, points_mat->cols);
|
||||
type = return_points ? points_mat->type : CV_32S;
|
||||
}
|
||||
else if(CV_IS_SEQ(points_seq)){
|
||||
npoints = points_seq->total;
|
||||
type = return_points ? CV_SEQ_ELTYPE(points_seq) : 1;
|
||||
}
|
||||
else{
|
||||
CV_Error(CV_StsBadArg, "points must be a CvSeq or CvMat");
|
||||
}
|
||||
hull=cvCreateMat(1,npoints,type);
|
||||
cvConvexHull2(points, hull, orientation, return_points);
|
||||
|
||||
return hull;
|
||||
}
|
||||
std::vector<CvPoint> cvSnakeImage_Shadow( const CvMat * image, std::vector<CvPoint> points,
|
||||
std::vector<float> alpha, std::vector<float> beta,
|
||||
std::vector<float> gamma,
|
||||
CvSize win, CvTermCriteria criteria, int calc_gradient ){
|
||||
IplImage ipl_stub;
|
||||
cvSnakeImage( cvGetImage(image, &ipl_stub), &(points[0]), points.size(),
|
||||
&((alpha)[0]), &((beta)[0]), &((gamma)[0]),
|
||||
(alpha.size()>1 && beta.size()>1 && gamma.size()>1 ? CV_ARRAY : CV_VALUE),
|
||||
win, criteria, calc_gradient );
|
||||
return points;
|
||||
}
|
29
interfaces/swig/python/cvshadow.h
Normal file
29
interfaces/swig/python/cvshadow.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef CV_SHADOW_H
|
||||
#define CV_SHADOW_H
|
||||
|
||||
#include <vector>
|
||||
#include "cxtypes.h"
|
||||
#include "cvtypes.h"
|
||||
#include "pycvseq.hpp"
|
||||
|
||||
// modify cvCvtSeqToArray to take CvArr as input instead of raw data
|
||||
CvArr * cvCvtSeqToArray_Shadow( const CvSeq* seq, CvArr * elements, CvSlice slice=CV_WHOLE_SEQ);
|
||||
|
||||
// Return a typed sequence instead of generic CvSeq
|
||||
CvTypedSeq<CvRect> * cvHaarDetectObjects_Shadow( const CvArr* image, CvHaarClassifierCascade* cascade,
|
||||
CvMemStorage* storage, double scale_factor=1.1, int min_neighbors=3, int flags=0,
|
||||
CvSize min_size=cvSize(0,0) );
|
||||
CvTypedSeq<CvConnectedComp> * cvSegmentMotion_Shadow( const CvArr* mhi, CvArr* seg_mask, CvMemStorage* storage,
|
||||
double timestamp, double seg_thresh );
|
||||
CvTypedSeq<CvPoint> * cvApproxPoly_Shadow( const void* src_seq, int header_size, CvMemStorage* storage,
|
||||
int method, double parameter, int parameter2=0);
|
||||
|
||||
// Always return a new Mat of indices
|
||||
CvMat * cvConvexHull2_Shadow( const CvArr * points, int orientation=CV_CLOCKWISE,
|
||||
int return_points=0);
|
||||
|
||||
std::vector<CvPoint> cvSnakeImage_Shadow( const CvMat * image, std::vector<CvPoint> points,
|
||||
std::vector<float> alpha, std::vector<float> beta, std::vector<float> gamma,
|
||||
CvSize win, CvTermCriteria criteria, int calc_gradient=1 );
|
||||
|
||||
#endif
|
137
interfaces/swig/python/cvshadow.i
Normal file
137
interfaces/swig/python/cvshadow.i
Normal file
@@ -0,0 +1,137 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
/* This file contains custom python shadow class code for certain troublesome functions */
|
||||
|
||||
%{
|
||||
#include "cvshadow.h"
|
||||
%}
|
||||
|
||||
// source %myshadow, %myrelease macros
|
||||
%include "cvswigmacros.i"
|
||||
|
||||
%include "stl.i"
|
||||
|
||||
// %ignore, %rename must come before %include
|
||||
%myshadow(cvCvtSeqToArray);
|
||||
%myshadow(cvHaarDetectObjects);
|
||||
%myshadow(cvSegmentMotion);
|
||||
%myshadow(cvApproxPoly);
|
||||
%myshadow(cvConvexHull2);
|
||||
%newobject cvConvexHull2_Shadow; // shadowed functioned always returns new object
|
||||
|
||||
/* cvSnakeImage shadow uses a vector<CvPoint> and vector<float> */
|
||||
%template(FloatVector) std::vector<float>;
|
||||
%template(CvPointVector) std::vector<CvPoint>;
|
||||
%myshadow(cvSnakeImage);
|
||||
|
||||
// must come after %ignore, %rename
|
||||
%include "cvshadow.h"
|
||||
|
||||
/* return a typed CvSeq instead of generic for CvSubdiv2D edges -- see cvseq.i */
|
||||
%rename (untyped_edges) CvSubdiv2D::edges;
|
||||
%ignore CvSubdiv2D::edges;
|
||||
%rename (edges) CvSubdiv2D::typed_edges;
|
||||
|
||||
/* Python doesn't know what to do with these */
|
||||
%rename (asIplImage) operator IplImage*;
|
||||
%rename (asCvMat) operator CvMat*;
|
||||
%ignore operator const IplImage*;
|
||||
%ignore operator const CvMat*;
|
||||
|
||||
/* Define sequence type for functions returning sequences */
|
||||
%define %cast_seq( cvfunc, type )
|
||||
%rename (cvfunc##Untyped) cvfunc;
|
||||
%pythoncode %{
|
||||
def cvfunc(*args):
|
||||
seq = cvfunc##Untyped( *args )
|
||||
return type.cast(seq)
|
||||
%}
|
||||
%enddef
|
||||
|
||||
%cast_seq( cvHoughCircles, CvSeq_float_3 );
|
||||
%cast_seq( cvPyrSegmentation, CvSeq_CvConnectedComp );
|
||||
%cast_seq( cvApproxChains, CvSeq_CvPoint);
|
||||
%cast_seq( cvContourFromContourTree, CvSeq_CvPoint );
|
||||
%cast_seq( cvConvexityDefects, CvSeq_CvConvexityDefect );
|
||||
|
||||
/* Special cases ... */
|
||||
%rename(cvFindContoursUntyped) cvFindContours;
|
||||
%pythoncode %{
|
||||
def cvFindContours( *args ):
|
||||
count, seq = cvFindContoursUntyped( *args )
|
||||
return count, CvSeq_CvPoint.cast(seq)
|
||||
%}
|
||||
|
||||
/* cvHoughLines2 returns a different type of sequence depending on its args */
|
||||
%rename (cvHoughLinesUntyped) cvHoughLines2;
|
||||
%pythoncode %{
|
||||
def cvHoughLines2( *args ):
|
||||
seq = cvHoughLinesUntyped( *args )
|
||||
type = CV_SEQ_ELTYPE(seq)
|
||||
if type == CV_32SC4:
|
||||
return CvSeq_CvPoint_2.cast(seq)
|
||||
return CvSeq_float_2.cast(seq)
|
||||
%}
|
||||
|
||||
// cvPointSeqFromMat
|
||||
// cvSeqPartition
|
||||
// cvSeqSlice
|
||||
// cvTreeToNodeSeq
|
||||
|
||||
// Fix cvRelease* function to play nice w/ Python
|
||||
// TODO some of these objects lack the delete method -- why???
|
||||
%myrelease(cv, cvReleaseImage, CvMat); // IplImage is CvMat in Python
|
||||
%myrelease(cv, cvReleaseMat, CvMat);
|
||||
%myrelease(cv, cvReleaseStructuringElement, IplConvKernel);
|
||||
%myrelease(cv, cvReleaseKalman, CvKalman);
|
||||
%myrelease(cv, cvReleaseHist, CvHistogram);
|
||||
%myrelease(cv, cvReleaseHaarClassifierCascade, CvHaarClassifierCascade);
|
||||
//%myrelease(cvReleasePOSITObject, CvPOSITObject);
|
||||
%myrelease(cv, cvReleaseImageHeader, CvMat); // IplImage is CvMat
|
||||
%myrelease(cv, cvReleaseMatND, CvMatND);
|
||||
%myrelease(cv, cvReleaseSparseMat, CvSparseMat);
|
||||
%myrelease(cv, cvReleaseMemStorage, CvMemStorage);
|
||||
%myrelease(cv, cvReleaseGraphScanner, CvGraphScanner);
|
||||
//%myrelease(cvReleaseFileStorage, CvFileStorage);
|
||||
|
||||
// TODO implement this
|
||||
%ignore cvRelease;
|
75
interfaces/swig/python/cvswigmacros.i
Normal file
75
interfaces/swig/python/cvswigmacros.i
Normal file
@@ -0,0 +1,75 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
/* This file contains swig macros that are used in several typemap files */
|
||||
|
||||
|
||||
%define %myshadow(function)
|
||||
%ignore function;
|
||||
%rename (function) function##_Shadow;
|
||||
%enddef
|
||||
|
||||
// Elsewhere in this wrapper, the cvRelease* functions are mapped to
|
||||
// the destructors for the corresponding OpenCV object wrapper. This
|
||||
// is done in order to let Python handle memory management. If the
|
||||
// reference count of the Python object wrapping the OpenCV object
|
||||
// goes to 0, the garbage collector will call the destructor, and
|
||||
// therefore the cvRelease* function, before freeing the Python object.
|
||||
// However, if the user explicitly calls the cvRelease* function, we
|
||||
// must prevent the Python garbage collector from calling it again when
|
||||
// the refcount reaches 0 -- otherwise a double-free error occurs.
|
||||
//
|
||||
// Thus, below, we redirect each cvRelease* function to the
|
||||
// corresponding OpenCV object's destructor. This has the effect of:
|
||||
// (1) Calling the corresponding cvRelease* function, and therefore
|
||||
// immediately releasing the OpenCV object.
|
||||
// (2) Telling SWIG to disown memory management for this OpenCV object.
|
||||
//
|
||||
// Thus, when the refcount for the Python object reaches 0, the Python
|
||||
// object is garbage collected, but since it no longer owns the OpenCV
|
||||
// object, this is not freed again.
|
||||
%define %myrelease(module, Function, Type)
|
||||
%ignore Function;
|
||||
%rename (Function) Function##_Shadow;
|
||||
%pythoncode %{
|
||||
Function = _##module##.delete_##Type
|
||||
%}
|
||||
%enddef
|
113
interfaces/swig/python/error.cpp
Normal file
113
interfaces/swig/python/error.cpp
Normal file
@@ -0,0 +1,113 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
|
||||
// 2004-03-17, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
|
||||
// Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
|
||||
// Python header.
|
||||
// It may be required that this header is the first to be included
|
||||
// (see Python documentation for details)
|
||||
#include "Python.h"
|
||||
|
||||
#include "error.h"
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
|
||||
// OpenCV headers
|
||||
#include "cxcore.h"
|
||||
#include "cxerror.h"
|
||||
|
||||
|
||||
//=========================================================================
|
||||
int SendErrorToPython
|
||||
(
|
||||
int status,
|
||||
const char* func_name,
|
||||
const char* err_msg,
|
||||
const char* file_name,
|
||||
int line,
|
||||
void* /*userdata*/
|
||||
)
|
||||
throw(int)
|
||||
{
|
||||
std::stringstream message;
|
||||
message
|
||||
<< " openCV Error:"
|
||||
<< "\n Status=" << cvErrorStr(status)
|
||||
<< "\n function name=" << (func_name ? func_name : "unknown")
|
||||
<< "\n error message=" << (err_msg ? err_msg : "unknown")
|
||||
<< "\n file_name=" << (file_name ? file_name : "unknown")
|
||||
<< "\n line=" << line
|
||||
<< std::flush;
|
||||
|
||||
// Clear OpenCV's error status for the next call!
|
||||
cvSetErrStatus( CV_StsOk );
|
||||
|
||||
// Set Python Error.
|
||||
// ATTENTION: this only works if the function returning to
|
||||
// Python returns 0 instead of a PyObject (see also "custom_typemaps.i"
|
||||
PyErr_SetString(PyExc_RuntimeError, message.str().c_str());
|
||||
throw 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
//=========================================================================
|
||||
void* void_ptr_generator()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
//=========================================================================
|
||||
void** void_ptrptr_generator()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
//=========================================================================
|
||||
CvErrorCallback function_ptr_generator()
|
||||
{
|
||||
return &SendErrorToPython;
|
||||
}
|
||||
|
68
interfaces/swig/python/error.h
Normal file
68
interfaces/swig/python/error.h
Normal file
@@ -0,0 +1,68 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
|
||||
// 2004-03-17, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
|
||||
// Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
|
||||
#include "cxcore.h"
|
||||
|
||||
/**
|
||||
* This function will set a Python error and throw an int.
|
||||
* Exceptions are catched automatically by the SWIG code from "typemaps.i"
|
||||
*/
|
||||
int SendErrorToPython ( int status,
|
||||
const char * func_name,
|
||||
const char * err_msg,
|
||||
const char * file_name,
|
||||
int line,
|
||||
void * /*userdata*/) throw(int);
|
||||
|
||||
/// Returns the adress of the static method "SendErrorToPython()"
|
||||
CvErrorCallback function_ptr_generator();
|
||||
|
||||
/// Dummy to generate an empty void pointer
|
||||
void * void_ptr_generator();
|
||||
|
||||
/// Dummy to generate an empty void double pointer
|
||||
void ** void_ptrptr_generator();
|
296
interfaces/swig/python/highgui.i
Normal file
296
interfaces/swig/python/highgui.i
Normal file
@@ -0,0 +1,296 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
|
||||
// 2004-03-16, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
|
||||
// Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
%{
|
||||
#include <cxtypes.h>
|
||||
#include <cv.h>
|
||||
#include <highgui.h>
|
||||
#include "pyhelpers.h"
|
||||
#include "pycvseq.hpp"
|
||||
%}
|
||||
// include python-specific files
|
||||
%include "./nointpb.i"
|
||||
%include "./pytypemaps.i"
|
||||
%include "exception.i"
|
||||
%include "cvswigmacros.i"
|
||||
|
||||
// handle camera and video writer destruction
|
||||
%myrelease(highgui, cvReleaseCapture, CvCapture);
|
||||
%myrelease(highgui, cvReleaseVideoWriter, CvVideoWriter);
|
||||
|
||||
/* the wrapping code to enable the use of Python-based mouse callbacks */
|
||||
%header %{
|
||||
/* This encapsulates the python callback and user_data for mouse callback */
|
||||
struct PyCvMouseCBData {
|
||||
PyObject * py_func;
|
||||
PyObject * user_data;
|
||||
};
|
||||
/* This encapsulates the python callback and user_data for mouse callback */
|
||||
/* C helper function which is responsible for calling
|
||||
the Python real trackbar callback function */
|
||||
static void icvPyOnMouse (int event, int x, int y,
|
||||
int flags, PyCvMouseCBData * param) {
|
||||
|
||||
/* Must ensure this thread has a lock on the interpreter */
|
||||
PyGILState_STATE state = PyGILState_Ensure();
|
||||
|
||||
PyObject *result;
|
||||
|
||||
/* the argument of the callback ready to be passed to Python code */
|
||||
PyObject *arg1 = PyInt_FromLong (event);
|
||||
PyObject *arg2 = PyInt_FromLong (x);
|
||||
PyObject *arg3 = PyInt_FromLong (y);
|
||||
PyObject *arg4 = PyInt_FromLong (flags);
|
||||
PyObject *arg5 = param->user_data; // assume this is already a PyObject
|
||||
|
||||
/* build the tuple for calling the Python callback */
|
||||
PyObject *arglist = Py_BuildValue ("(OOOOO)",
|
||||
arg1, arg2, arg3, arg4, arg5);
|
||||
|
||||
/* call the Python callback */
|
||||
result = PyEval_CallObject (param->py_func, arglist);
|
||||
|
||||
/* Errors in Python callback get swallowed, so report them here */
|
||||
if(!result){
|
||||
PyErr_Print();
|
||||
cvError( CV_StsInternal, "icvPyOnMouse", "", __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
/* cleanup */
|
||||
Py_XDECREF (result);
|
||||
|
||||
/* Release Interpreter lock */
|
||||
PyGILState_Release(state);
|
||||
}
|
||||
%}
|
||||
/**
|
||||
* adapt cvSetMouseCallback to use python callback
|
||||
*/
|
||||
%rename (cvSetMouseCallbackOld) cvSetMouseCallback;
|
||||
%rename (cvSetMouseCallback) cvSetMouseCallbackPy;
|
||||
%inline %{
|
||||
void cvSetMouseCallbackPy( const char* window_name, PyObject * on_mouse, PyObject * param=NULL ){
|
||||
// TODO potential memory leak if mouse callback is redefined
|
||||
PyCvMouseCBData * py_callback = new PyCvMouseCBData;
|
||||
py_callback->py_func = on_mouse;
|
||||
py_callback->user_data = param ? param : Py_None;
|
||||
|
||||
Py_XINCREF(py_callback->py_func);
|
||||
Py_XINCREF(py_callback->user_data);
|
||||
|
||||
cvSetMouseCallback( window_name, (CvMouseCallback) icvPyOnMouse, (void *) py_callback );
|
||||
}
|
||||
%}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The following code enables trackbar callbacks from python. Unfortunately, there is no
|
||||
* way to distinguish which trackbar the event originated from, so must hard code a
|
||||
* fixed number of unique c callback functions using the macros below
|
||||
*/
|
||||
%wrapper %{
|
||||
/* C helper function which is responsible for calling
|
||||
the Python real trackbar callback function */
|
||||
static void icvPyOnTrackbar( PyObject * py_cb_func, int pos) {
|
||||
|
||||
/* Must ensure this thread has a lock on the interpreter */
|
||||
PyGILState_STATE state = PyGILState_Ensure();
|
||||
|
||||
PyObject *result;
|
||||
|
||||
/* the argument of the callback ready to be passed to Python code */
|
||||
PyObject *arg1 = PyInt_FromLong (pos);
|
||||
|
||||
/* build the tuple for calling the Python callback */
|
||||
PyObject *arglist = Py_BuildValue ("(O)", arg1);
|
||||
|
||||
/* call the Python callback */
|
||||
result = PyEval_CallObject (py_cb_func, arglist);
|
||||
|
||||
/* Errors in Python callback get swallowed, so report them here */
|
||||
if(!result){
|
||||
PyErr_Print();
|
||||
cvError( CV_StsInternal, "icvPyOnTrackbar", "", __FILE__, __LINE__);
|
||||
}
|
||||
|
||||
|
||||
/* cleanup */
|
||||
Py_XDECREF (result);
|
||||
|
||||
/* Release Interpreter lock */
|
||||
PyGILState_Release(state);
|
||||
}
|
||||
|
||||
#define ICV_PY_MAX_CB 10
|
||||
|
||||
struct PyCvTrackbar {
|
||||
CvTrackbarCallback cv_func;
|
||||
PyObject * py_func;
|
||||
PyObject * py_pos;
|
||||
};
|
||||
|
||||
static int my_trackbar_cb_size=0;
|
||||
extern PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB];
|
||||
%}
|
||||
|
||||
/* Callback table entry */
|
||||
%define %ICV_PY_CB_TAB_ENTRY(idx)
|
||||
{(CvTrackbarCallback) icvPyTrackbarCB##idx, NULL, NULL }
|
||||
%enddef
|
||||
|
||||
/* Table of callbacks */
|
||||
%define %ICV_PY_CB_TAB
|
||||
%wrapper %{
|
||||
PyCvTrackbar my_trackbar_cb_funcs[ICV_PY_MAX_CB] = {
|
||||
%ICV_PY_CB_TAB_ENTRY(0),
|
||||
%ICV_PY_CB_TAB_ENTRY(1),
|
||||
%ICV_PY_CB_TAB_ENTRY(2),
|
||||
%ICV_PY_CB_TAB_ENTRY(3),
|
||||
%ICV_PY_CB_TAB_ENTRY(4),
|
||||
%ICV_PY_CB_TAB_ENTRY(5),
|
||||
%ICV_PY_CB_TAB_ENTRY(6),
|
||||
%ICV_PY_CB_TAB_ENTRY(7),
|
||||
%ICV_PY_CB_TAB_ENTRY(8),
|
||||
%ICV_PY_CB_TAB_ENTRY(9)
|
||||
};
|
||||
%}
|
||||
%enddef
|
||||
|
||||
/* Callback definition */
|
||||
%define %ICV_PY_CB_IMPL(idx)
|
||||
%wrapper %{
|
||||
static void icvPyTrackbarCB##idx(int pos){
|
||||
if(!my_trackbar_cb_funcs[idx].py_func) return;
|
||||
icvPyOnTrackbar( my_trackbar_cb_funcs[idx].py_func, pos );
|
||||
}
|
||||
%}
|
||||
%enddef
|
||||
|
||||
|
||||
%ICV_PY_CB_IMPL(0);
|
||||
%ICV_PY_CB_IMPL(1);
|
||||
%ICV_PY_CB_IMPL(2);
|
||||
%ICV_PY_CB_IMPL(3);
|
||||
%ICV_PY_CB_IMPL(4);
|
||||
%ICV_PY_CB_IMPL(5);
|
||||
%ICV_PY_CB_IMPL(6);
|
||||
%ICV_PY_CB_IMPL(7);
|
||||
%ICV_PY_CB_IMPL(8);
|
||||
%ICV_PY_CB_IMPL(9);
|
||||
|
||||
%ICV_PY_CB_TAB;
|
||||
|
||||
|
||||
/**
|
||||
* typemap to memorize the Python callback when doing cvCreateTrackbar ()
|
||||
*/
|
||||
%typemap(in) CvTrackbarCallback {
|
||||
|
||||
if(my_trackbar_cb_size == ICV_PY_MAX_CB){
|
||||
SWIG_exception(SWIG_IndexError, "Exceeded maximum number of trackbars");
|
||||
}
|
||||
|
||||
my_trackbar_cb_size++;
|
||||
|
||||
if (!PyCallable_Check($input)) {
|
||||
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
|
||||
return 0;
|
||||
}
|
||||
Py_XINCREF((PyObject*) $input); /* Add a reference to new callback */
|
||||
Py_XDECREF(my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func); /* Dispose of previous callback */
|
||||
my_trackbar_cb_funcs[my_trackbar_cb_size-1].py_func = (PyObject *) $input;
|
||||
|
||||
/* prepare to call the C function who will register the callback */
|
||||
$1 = my_trackbar_cb_funcs[ my_trackbar_cb_size-1 ].cv_func;
|
||||
}
|
||||
|
||||
/**
|
||||
* typemap so that cvWaitKey returns a character in all cases except -1
|
||||
*/
|
||||
%rename (cvWaitKeyC) cvWaitKey;
|
||||
%rename (cvWaitKey) cvWaitKeyPy;
|
||||
%inline %{
|
||||
PyObject * cvWaitKeyPy(int delay=0){
|
||||
// In order for the event processing thread to run a python callback
|
||||
// it must acquire the global interpreter lock, but cvWaitKey blocks, so
|
||||
// this thread can never release the lock. So release it here.
|
||||
PyThreadState * thread_state = PyEval_SaveThread();
|
||||
int res = cvWaitKey(delay);
|
||||
PyEval_RestoreThread( thread_state );
|
||||
|
||||
char str[2]={(char)res,0};
|
||||
if(res==-1){
|
||||
return PyLong_FromLong(-1);
|
||||
}
|
||||
return PyString_FromString(str);
|
||||
}
|
||||
%}
|
||||
/* HighGUI Python module initialization
|
||||
* needed for callbacks to work in a threaded environment
|
||||
*/
|
||||
%init %{
|
||||
PyEval_InitThreads();
|
||||
%}
|
||||
|
||||
|
||||
%include "../general/highgui.i"
|
||||
|
||||
%pythoncode
|
||||
%{
|
||||
|
||||
__doc__ = """HighGUI provides minimalistic user interface parts and video input/output.
|
||||
|
||||
Dependent on the platform it was compiled on, this library provides methods
|
||||
to draw a window for image display, capture video from a camera or framegrabber
|
||||
or read/write video streams from/to the file system.
|
||||
|
||||
This wrapper was semi-automatically created from the C/C++ headers and therefore
|
||||
contains no Python documentation. Because all identifiers are identical to their
|
||||
C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
|
||||
"""
|
||||
|
||||
%}
|
457
interfaces/swig/python/highgui.py
Normal file
457
interfaces/swig/python/highgui.py
Normal file
@@ -0,0 +1,457 @@
|
||||
# This file was automatically generated by SWIG (http://www.swig.org).
|
||||
# Version 1.3.40
|
||||
#
|
||||
# Do not make changes to this file unless you know what you are doing--modify
|
||||
# the SWIG interface file instead.
|
||||
# This file is compatible with both classic and new-style classes.
|
||||
|
||||
from sys import version_info
|
||||
if version_info >= (2,6,0):
|
||||
def swig_import_helper():
|
||||
from os.path import dirname
|
||||
import imp
|
||||
fp = None
|
||||
try:
|
||||
fp, pathname, description = imp.find_module('_highgui', [dirname(__file__)])
|
||||
except ImportError:
|
||||
import _highgui
|
||||
return _highgui
|
||||
if fp is not None:
|
||||
try:
|
||||
_mod = imp.load_module('_highgui', fp, pathname, description)
|
||||
finally:
|
||||
fp.close()
|
||||
return _mod
|
||||
_highgui = swig_import_helper()
|
||||
del swig_import_helper
|
||||
else:
|
||||
import _highgui
|
||||
del version_info
|
||||
try:
|
||||
_swig_property = property
|
||||
except NameError:
|
||||
pass # Python < 2.2 doesn't have 'property'.
|
||||
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
|
||||
if (name == "thisown"): return self.this.own(value)
|
||||
if (name == "this"):
|
||||
if type(value).__name__ == 'SwigPyObject':
|
||||
self.__dict__[name] = value
|
||||
return
|
||||
method = class_type.__swig_setmethods__.get(name,None)
|
||||
if method: return method(self,value)
|
||||
if (not static) or hasattr(self,name):
|
||||
self.__dict__[name] = value
|
||||
else:
|
||||
raise AttributeError("You cannot add attributes to %s" % self)
|
||||
|
||||
def _swig_setattr(self,class_type,name,value):
|
||||
return _swig_setattr_nondynamic(self,class_type,name,value,0)
|
||||
|
||||
def _swig_getattr(self,class_type,name):
|
||||
if (name == "thisown"): return self.this.own()
|
||||
method = class_type.__swig_getmethods__.get(name,None)
|
||||
if method: return method(self)
|
||||
raise AttributeError(name)
|
||||
|
||||
def _swig_repr(self):
|
||||
try: strthis = "proxy of " + self.this.__repr__()
|
||||
except: strthis = ""
|
||||
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
|
||||
|
||||
try:
|
||||
_object = object
|
||||
_newclass = 1
|
||||
except AttributeError:
|
||||
class _object : pass
|
||||
_newclass = 0
|
||||
|
||||
|
||||
class CvRNG_Wrapper(_object):
|
||||
__swig_setmethods__ = {}
|
||||
__setattr__ = lambda self, name, value: _swig_setattr(self, CvRNG_Wrapper, name, value)
|
||||
__swig_getmethods__ = {}
|
||||
__getattr__ = lambda self, name: _swig_getattr(self, CvRNG_Wrapper, name)
|
||||
__repr__ = _swig_repr
|
||||
def __init__(self, *args):
|
||||
this = _highgui.new_CvRNG_Wrapper(*args)
|
||||
try: self.this.append(this)
|
||||
except: self.this = this
|
||||
def ptr(self): return _highgui.CvRNG_Wrapper_ptr(self)
|
||||
def ref(self): return _highgui.CvRNG_Wrapper_ref(self)
|
||||
def __eq__(self, *args): return _highgui.CvRNG_Wrapper___eq__(self, *args)
|
||||
def __ne__(self, *args): return _highgui.CvRNG_Wrapper___ne__(self, *args)
|
||||
__swig_destroy__ = _highgui.delete_CvRNG_Wrapper
|
||||
__del__ = lambda self : None;
|
||||
CvRNG_Wrapper_swigregister = _highgui.CvRNG_Wrapper_swigregister
|
||||
CvRNG_Wrapper_swigregister(CvRNG_Wrapper)
|
||||
|
||||
class CvSubdiv2DEdge_Wrapper(_object):
|
||||
__swig_setmethods__ = {}
|
||||
__setattr__ = lambda self, name, value: _swig_setattr(self, CvSubdiv2DEdge_Wrapper, name, value)
|
||||
__swig_getmethods__ = {}
|
||||
__getattr__ = lambda self, name: _swig_getattr(self, CvSubdiv2DEdge_Wrapper, name)
|
||||
__repr__ = _swig_repr
|
||||
def __init__(self, *args):
|
||||
this = _highgui.new_CvSubdiv2DEdge_Wrapper(*args)
|
||||
try: self.this.append(this)
|
||||
except: self.this = this
|
||||
def ptr(self): return _highgui.CvSubdiv2DEdge_Wrapper_ptr(self)
|
||||
def ref(self): return _highgui.CvSubdiv2DEdge_Wrapper_ref(self)
|
||||
def __eq__(self, *args): return _highgui.CvSubdiv2DEdge_Wrapper___eq__(self, *args)
|
||||
def __ne__(self, *args): return _highgui.CvSubdiv2DEdge_Wrapper___ne__(self, *args)
|
||||
__swig_destroy__ = _highgui.delete_CvSubdiv2DEdge_Wrapper
|
||||
__del__ = lambda self : None;
|
||||
CvSubdiv2DEdge_Wrapper_swigregister = _highgui.CvSubdiv2DEdge_Wrapper_swigregister
|
||||
CvSubdiv2DEdge_Wrapper_swigregister(CvSubdiv2DEdge_Wrapper)
|
||||
|
||||
cvReleaseCapture = _highgui.delete_CvCapture
|
||||
|
||||
cvReleaseVideoWriter = _highgui.delete_CvVideoWriter
|
||||
|
||||
|
||||
def cvRetrieveFrame(*args):
|
||||
"""cvRetrieveFrame(CvCapture capture) -> CvMat"""
|
||||
return _highgui.cvRetrieveFrame(*args)
|
||||
|
||||
def cvQueryFrame(*args):
|
||||
"""cvQueryFrame(CvCapture capture) -> CvMat"""
|
||||
return _highgui.cvQueryFrame(*args)
|
||||
|
||||
def cvInitSystem(*args):
|
||||
"""cvInitSystem(int argc, char argv) -> int"""
|
||||
return _highgui.cvInitSystem(*args)
|
||||
|
||||
def cvStartWindowThread():
|
||||
"""cvStartWindowThread() -> int"""
|
||||
return _highgui.cvStartWindowThread()
|
||||
CV_WINDOW_AUTOSIZE = _highgui.CV_WINDOW_AUTOSIZE
|
||||
|
||||
def cvNamedWindow(*args):
|
||||
"""cvNamedWindow(char name, int flags = 1) -> int"""
|
||||
return _highgui.cvNamedWindow(*args)
|
||||
|
||||
def cvShowImage(*args):
|
||||
"""cvShowImage(char name, CvArr image)"""
|
||||
return _highgui.cvShowImage(*args)
|
||||
|
||||
def cvResizeWindow(*args):
|
||||
"""cvResizeWindow(char name, int width, int height)"""
|
||||
return _highgui.cvResizeWindow(*args)
|
||||
|
||||
def cvMoveWindow(*args):
|
||||
"""cvMoveWindow(char name, int x, int y)"""
|
||||
return _highgui.cvMoveWindow(*args)
|
||||
|
||||
def cvDestroyWindow(*args):
|
||||
"""cvDestroyWindow(char name)"""
|
||||
return _highgui.cvDestroyWindow(*args)
|
||||
|
||||
def cvDestroyAllWindows():
|
||||
"""cvDestroyAllWindows()"""
|
||||
return _highgui.cvDestroyAllWindows()
|
||||
|
||||
def cvGetWindowHandle(*args):
|
||||
"""cvGetWindowHandle(char name) -> void"""
|
||||
return _highgui.cvGetWindowHandle(*args)
|
||||
|
||||
def cvGetWindowName(*args):
|
||||
"""cvGetWindowName(void window_handle) -> char"""
|
||||
return _highgui.cvGetWindowName(*args)
|
||||
|
||||
def cvCreateTrackbar(*args):
|
||||
"""
|
||||
cvCreateTrackbar(char trackbar_name, char window_name, int value, int count,
|
||||
CvTrackbarCallback on_change) -> int
|
||||
"""
|
||||
return _highgui.cvCreateTrackbar(*args)
|
||||
|
||||
def cvCreateTrackbar2(*args):
|
||||
"""
|
||||
cvCreateTrackbar2(char trackbar_name, char window_name, int value, int count,
|
||||
CvTrackbarCallback2 on_change, void userdata = None) -> int
|
||||
"""
|
||||
return _highgui.cvCreateTrackbar2(*args)
|
||||
|
||||
def cvGetTrackbarPos(*args):
|
||||
"""cvGetTrackbarPos(char trackbar_name, char window_name) -> int"""
|
||||
return _highgui.cvGetTrackbarPos(*args)
|
||||
|
||||
def cvSetTrackbarPos(*args):
|
||||
"""cvSetTrackbarPos(char trackbar_name, char window_name, int pos)"""
|
||||
return _highgui.cvSetTrackbarPos(*args)
|
||||
CV_EVENT_MOUSEMOVE = _highgui.CV_EVENT_MOUSEMOVE
|
||||
CV_EVENT_LBUTTONDOWN = _highgui.CV_EVENT_LBUTTONDOWN
|
||||
CV_EVENT_RBUTTONDOWN = _highgui.CV_EVENT_RBUTTONDOWN
|
||||
CV_EVENT_MBUTTONDOWN = _highgui.CV_EVENT_MBUTTONDOWN
|
||||
CV_EVENT_LBUTTONUP = _highgui.CV_EVENT_LBUTTONUP
|
||||
CV_EVENT_RBUTTONUP = _highgui.CV_EVENT_RBUTTONUP
|
||||
CV_EVENT_MBUTTONUP = _highgui.CV_EVENT_MBUTTONUP
|
||||
CV_EVENT_LBUTTONDBLCLK = _highgui.CV_EVENT_LBUTTONDBLCLK
|
||||
CV_EVENT_RBUTTONDBLCLK = _highgui.CV_EVENT_RBUTTONDBLCLK
|
||||
CV_EVENT_MBUTTONDBLCLK = _highgui.CV_EVENT_MBUTTONDBLCLK
|
||||
CV_EVENT_FLAG_LBUTTON = _highgui.CV_EVENT_FLAG_LBUTTON
|
||||
CV_EVENT_FLAG_RBUTTON = _highgui.CV_EVENT_FLAG_RBUTTON
|
||||
CV_EVENT_FLAG_MBUTTON = _highgui.CV_EVENT_FLAG_MBUTTON
|
||||
CV_EVENT_FLAG_CTRLKEY = _highgui.CV_EVENT_FLAG_CTRLKEY
|
||||
CV_EVENT_FLAG_SHIFTKEY = _highgui.CV_EVENT_FLAG_SHIFTKEY
|
||||
CV_EVENT_FLAG_ALTKEY = _highgui.CV_EVENT_FLAG_ALTKEY
|
||||
|
||||
def cvSetMouseCallbackOld(*args):
|
||||
"""cvSetMouseCallbackOld(char window_name, CvMouseCallback on_mouse, void param = None)"""
|
||||
return _highgui.cvSetMouseCallbackOld(*args)
|
||||
CV_LOAD_IMAGE_UNCHANGED = _highgui.CV_LOAD_IMAGE_UNCHANGED
|
||||
CV_LOAD_IMAGE_GRAYSCALE = _highgui.CV_LOAD_IMAGE_GRAYSCALE
|
||||
CV_LOAD_IMAGE_COLOR = _highgui.CV_LOAD_IMAGE_COLOR
|
||||
CV_LOAD_IMAGE_ANYDEPTH = _highgui.CV_LOAD_IMAGE_ANYDEPTH
|
||||
CV_LOAD_IMAGE_ANYCOLOR = _highgui.CV_LOAD_IMAGE_ANYCOLOR
|
||||
|
||||
def cvLoadImageM(*args):
|
||||
"""cvLoadImageM(char filename, int iscolor = 1) -> CvMat"""
|
||||
return _highgui.cvLoadImageM(*args)
|
||||
CV_IMWRITE_JPEG_QUALITY = _highgui.CV_IMWRITE_JPEG_QUALITY
|
||||
CV_IMWRITE_PNG_COMPRESSION = _highgui.CV_IMWRITE_PNG_COMPRESSION
|
||||
CV_IMWRITE_PXM_BINARY = _highgui.CV_IMWRITE_PXM_BINARY
|
||||
|
||||
def cvSaveImage(*args):
|
||||
"""cvSaveImage(char filename, CvArr image, int params = None) -> int"""
|
||||
return _highgui.cvSaveImage(*args)
|
||||
|
||||
def cvDecodeImage(*args):
|
||||
"""cvDecodeImage(CvMat buf, int iscolor = 1)"""
|
||||
return _highgui.cvDecodeImage(*args)
|
||||
|
||||
def cvDecodeImageM(*args):
|
||||
"""cvDecodeImageM(CvMat buf, int iscolor = 1) -> CvMat"""
|
||||
return _highgui.cvDecodeImageM(*args)
|
||||
|
||||
def cvEncodeImage(*args):
|
||||
"""cvEncodeImage(char ext, CvArr image, int params = None) -> CvMat"""
|
||||
return _highgui.cvEncodeImage(*args)
|
||||
CV_CVTIMG_FLIP = _highgui.CV_CVTIMG_FLIP
|
||||
CV_CVTIMG_SWAP_RB = _highgui.CV_CVTIMG_SWAP_RB
|
||||
|
||||
def cvConvertImage(*args):
|
||||
"""cvConvertImage(CvArr src, CvArr dst, int flags = 0)"""
|
||||
return _highgui.cvConvertImage(*args)
|
||||
|
||||
def cvWaitKeyC(delay = 0):
|
||||
"""cvWaitKeyC(int delay = 0) -> int"""
|
||||
return _highgui.cvWaitKeyC(delay)
|
||||
|
||||
def cvCreateFileCapture(*args):
|
||||
"""cvCreateFileCapture(char filename) -> CvCapture"""
|
||||
return _highgui.cvCreateFileCapture(*args)
|
||||
CV_CAP_ANY = _highgui.CV_CAP_ANY
|
||||
CV_CAP_MIL = _highgui.CV_CAP_MIL
|
||||
CV_CAP_VFW = _highgui.CV_CAP_VFW
|
||||
CV_CAP_V4L = _highgui.CV_CAP_V4L
|
||||
CV_CAP_V4L2 = _highgui.CV_CAP_V4L2
|
||||
CV_CAP_FIREWARE = _highgui.CV_CAP_FIREWARE
|
||||
CV_CAP_FIREWIRE = _highgui.CV_CAP_FIREWIRE
|
||||
CV_CAP_IEEE1394 = _highgui.CV_CAP_IEEE1394
|
||||
CV_CAP_DC1394 = _highgui.CV_CAP_DC1394
|
||||
CV_CAP_CMU1394 = _highgui.CV_CAP_CMU1394
|
||||
CV_CAP_STEREO = _highgui.CV_CAP_STEREO
|
||||
CV_CAP_TYZX = _highgui.CV_CAP_TYZX
|
||||
CV_TYZX_LEFT = _highgui.CV_TYZX_LEFT
|
||||
CV_TYZX_RIGHT = _highgui.CV_TYZX_RIGHT
|
||||
CV_TYZX_COLOR = _highgui.CV_TYZX_COLOR
|
||||
CV_TYZX_Z = _highgui.CV_TYZX_Z
|
||||
CV_CAP_QT = _highgui.CV_CAP_QT
|
||||
CV_CAP_UNICAP = _highgui.CV_CAP_UNICAP
|
||||
CV_CAP_DSHOW = _highgui.CV_CAP_DSHOW
|
||||
|
||||
def cvCreateCameraCapture(*args):
|
||||
"""cvCreateCameraCapture(int index) -> CvCapture"""
|
||||
return _highgui.cvCreateCameraCapture(*args)
|
||||
|
||||
def cvGrabFrame(*args):
|
||||
"""cvGrabFrame(CvCapture capture) -> int"""
|
||||
return _highgui.cvGrabFrame(*args)
|
||||
|
||||
def cvRetrieveFrame__Deprecated(*args):
|
||||
"""cvRetrieveFrame__Deprecated(CvCapture capture, int streamIdx = 0)"""
|
||||
return _highgui.cvRetrieveFrame__Deprecated(*args)
|
||||
|
||||
def cvQueryFrame__Deprecated(*args):
|
||||
"""cvQueryFrame__Deprecated(CvCapture capture)"""
|
||||
return _highgui.cvQueryFrame__Deprecated(*args)
|
||||
CV_CAP_PROP_POS_MSEC = _highgui.CV_CAP_PROP_POS_MSEC
|
||||
CV_CAP_PROP_POS_FRAMES = _highgui.CV_CAP_PROP_POS_FRAMES
|
||||
CV_CAP_PROP_POS_AVI_RATIO = _highgui.CV_CAP_PROP_POS_AVI_RATIO
|
||||
CV_CAP_PROP_FRAME_WIDTH = _highgui.CV_CAP_PROP_FRAME_WIDTH
|
||||
CV_CAP_PROP_FRAME_HEIGHT = _highgui.CV_CAP_PROP_FRAME_HEIGHT
|
||||
CV_CAP_PROP_FPS = _highgui.CV_CAP_PROP_FPS
|
||||
CV_CAP_PROP_FOURCC = _highgui.CV_CAP_PROP_FOURCC
|
||||
CV_CAP_PROP_FRAME_COUNT = _highgui.CV_CAP_PROP_FRAME_COUNT
|
||||
CV_CAP_PROP_FORMAT = _highgui.CV_CAP_PROP_FORMAT
|
||||
CV_CAP_PROP_MODE = _highgui.CV_CAP_PROP_MODE
|
||||
CV_CAP_PROP_BRIGHTNESS = _highgui.CV_CAP_PROP_BRIGHTNESS
|
||||
CV_CAP_PROP_CONTRAST = _highgui.CV_CAP_PROP_CONTRAST
|
||||
CV_CAP_PROP_SATURATION = _highgui.CV_CAP_PROP_SATURATION
|
||||
CV_CAP_PROP_HUE = _highgui.CV_CAP_PROP_HUE
|
||||
CV_CAP_PROP_GAIN = _highgui.CV_CAP_PROP_GAIN
|
||||
CV_CAP_PROP_EXPOSURE = _highgui.CV_CAP_PROP_EXPOSURE
|
||||
CV_CAP_PROP_CONVERT_RGB = _highgui.CV_CAP_PROP_CONVERT_RGB
|
||||
CV_CAP_PROP_WHITE_BALANCE = _highgui.CV_CAP_PROP_WHITE_BALANCE
|
||||
CV_CAP_PROP_RECTIFICATION = _highgui.CV_CAP_PROP_RECTIFICATION
|
||||
|
||||
def cvGetCaptureProperty(*args):
|
||||
"""cvGetCaptureProperty(CvCapture capture, int property_id) -> double"""
|
||||
return _highgui.cvGetCaptureProperty(*args)
|
||||
|
||||
def cvSetCaptureProperty(*args):
|
||||
"""cvSetCaptureProperty(CvCapture capture, int property_id, double value) -> int"""
|
||||
return _highgui.cvSetCaptureProperty(*args)
|
||||
|
||||
def cvGetCaptureDomain(*args):
|
||||
"""cvGetCaptureDomain(CvCapture capture) -> int"""
|
||||
return _highgui.cvGetCaptureDomain(*args)
|
||||
|
||||
def CV_FOURCC(*args):
|
||||
"""CV_FOURCC(char c1, char c2, char c3, char c4) -> int"""
|
||||
return _highgui.CV_FOURCC(*args)
|
||||
CV_FOURCC_PROMPT = _highgui.CV_FOURCC_PROMPT
|
||||
|
||||
def cvCreateVideoWriter(*args):
|
||||
"""
|
||||
cvCreateVideoWriter(char filename, int fourcc, double fps, CvSize frame_size,
|
||||
int is_color = 1) -> CvVideoWriter
|
||||
"""
|
||||
return _highgui.cvCreateVideoWriter(*args)
|
||||
|
||||
def cvWriteFrame(*args):
|
||||
"""cvWriteFrame(CvVideoWriter writer, image) -> int"""
|
||||
return _highgui.cvWriteFrame(*args)
|
||||
HG_AUTOSIZE = _highgui.HG_AUTOSIZE
|
||||
class CvvImage(_object):
|
||||
"""Proxy of C++ CvvImage class"""
|
||||
__swig_setmethods__ = {}
|
||||
__setattr__ = lambda self, name, value: _swig_setattr(self, CvvImage, name, value)
|
||||
__swig_getmethods__ = {}
|
||||
__getattr__ = lambda self, name: _swig_getattr(self, CvvImage, name)
|
||||
__repr__ = _swig_repr
|
||||
def __init__(self):
|
||||
"""__init__(self) -> CvvImage"""
|
||||
this = _highgui.new_CvvImage()
|
||||
try: self.this.append(this)
|
||||
except: self.this = this
|
||||
__swig_destroy__ = _highgui.delete_CvvImage
|
||||
__del__ = lambda self : None;
|
||||
def Create(self, *args):
|
||||
"""
|
||||
Create(self, int width, int height, int bits_per_pixel, int image_origin = 0) -> bool
|
||||
Create(self, int width, int height, int bits_per_pixel) -> bool
|
||||
"""
|
||||
return _highgui.CvvImage_Create(self, *args)
|
||||
|
||||
def Load(self, *args):
|
||||
"""
|
||||
Load(self, char filename, int desired_color = 1) -> bool
|
||||
Load(self, char filename) -> bool
|
||||
"""
|
||||
return _highgui.CvvImage_Load(self, *args)
|
||||
|
||||
def LoadRect(self, *args):
|
||||
"""LoadRect(self, char filename, int desired_color, CvRect r) -> bool"""
|
||||
return _highgui.CvvImage_LoadRect(self, *args)
|
||||
|
||||
def Save(self, *args):
|
||||
"""Save(self, char filename) -> bool"""
|
||||
return _highgui.CvvImage_Save(self, *args)
|
||||
|
||||
def CopyOf(self, *args):
|
||||
"""
|
||||
CopyOf(self, CvvImage image, int desired_color = -1)
|
||||
CopyOf(self, CvvImage image)
|
||||
CopyOf(self, img, int desired_color = -1)
|
||||
CopyOf(self, img)
|
||||
"""
|
||||
return _highgui.CvvImage_CopyOf(self, *args)
|
||||
|
||||
def GetImage(self):
|
||||
"""GetImage(self)"""
|
||||
return _highgui.CvvImage_GetImage(self)
|
||||
|
||||
def Destroy(self):
|
||||
"""Destroy(self)"""
|
||||
return _highgui.CvvImage_Destroy(self)
|
||||
|
||||
def Width(self):
|
||||
"""Width(self) -> int"""
|
||||
return _highgui.CvvImage_Width(self)
|
||||
|
||||
def Height(self):
|
||||
"""Height(self) -> int"""
|
||||
return _highgui.CvvImage_Height(self)
|
||||
|
||||
def Bpp(self):
|
||||
"""Bpp(self) -> int"""
|
||||
return _highgui.CvvImage_Bpp(self)
|
||||
|
||||
def Fill(self, *args):
|
||||
"""Fill(self, int color)"""
|
||||
return _highgui.CvvImage_Fill(self, *args)
|
||||
|
||||
def Show(self, *args):
|
||||
"""Show(self, char window)"""
|
||||
return _highgui.CvvImage_Show(self, *args)
|
||||
|
||||
CvvImage_swigregister = _highgui.CvvImage_swigregister
|
||||
CvvImage_swigregister(CvvImage)
|
||||
|
||||
def cvSetMouseCallback(*args):
|
||||
return _highgui.cvSetMouseCallback(*args)
|
||||
cvSetMouseCallback = _highgui.cvSetMouseCallback
|
||||
|
||||
def cvWaitKey(delay = 0):
|
||||
return _highgui.cvWaitKey(delay)
|
||||
cvWaitKey = _highgui.cvWaitKey
|
||||
|
||||
def cvLoadImage(*args):
|
||||
"""
|
||||
cvLoadImage(char filename, int iscolor = 1) -> CvMat
|
||||
cvLoadImage(char filename) -> CvMat
|
||||
"""
|
||||
return _highgui.cvLoadImage(*args)
|
||||
|
||||
class CvCapture(_object):
|
||||
"""Proxy of C++ CvCapture class"""
|
||||
__swig_setmethods__ = {}
|
||||
__setattr__ = lambda self, name, value: _swig_setattr(self, CvCapture, name, value)
|
||||
__swig_getmethods__ = {}
|
||||
__getattr__ = lambda self, name: _swig_getattr(self, CvCapture, name)
|
||||
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
|
||||
__repr__ = _swig_repr
|
||||
__swig_destroy__ = _highgui.delete_CvCapture
|
||||
__del__ = lambda self : None;
|
||||
CvCapture_swigregister = _highgui.CvCapture_swigregister
|
||||
CvCapture_swigregister(CvCapture)
|
||||
|
||||
class CvVideoWriter(_object):
|
||||
"""Proxy of C++ CvVideoWriter class"""
|
||||
__swig_setmethods__ = {}
|
||||
__setattr__ = lambda self, name, value: _swig_setattr(self, CvVideoWriter, name, value)
|
||||
__swig_getmethods__ = {}
|
||||
__getattr__ = lambda self, name: _swig_getattr(self, CvVideoWriter, name)
|
||||
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
|
||||
__repr__ = _swig_repr
|
||||
__swig_destroy__ = _highgui.delete_CvVideoWriter
|
||||
__del__ = lambda self : None;
|
||||
CvVideoWriter_swigregister = _highgui.CvVideoWriter_swigregister
|
||||
CvVideoWriter_swigregister(CvVideoWriter)
|
||||
|
||||
__doc__ = """HighGUI provides minimalistic user interface parts and video input/output.
|
||||
|
||||
Dependent on the platform it was compiled on, this library provides methods
|
||||
to draw a window for image display, capture video from a camera or framegrabber
|
||||
or read/write video streams from/to the file system.
|
||||
|
||||
This wrapper was semi-automatically created from the C/C++ headers and therefore
|
||||
contains no Python documentation. Because all identifiers are identical to their
|
||||
C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
152
interfaces/swig/python/imagedata.i
Normal file
152
interfaces/swig/python/imagedata.i
Normal file
@@ -0,0 +1,152 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
|
||||
// 2004-03-16, Gabriel Schreiber <schreiber@ient.rwth-aachen.de>
|
||||
// Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
// 2006-08-29 Roman Stanchak -- converted to use CvMat rather than IplImage
|
||||
|
||||
|
||||
%{
|
||||
|
||||
/// Accessor to convert a Python string into the imageData.
|
||||
void CvMat_imageData_set(CvMat * self, PyObject* object)
|
||||
{
|
||||
char* py_string = PyString_AsString(object);
|
||||
int depth = CV_MAT_DEPTH(self->type);
|
||||
int cn = CV_MAT_CN(self->type);
|
||||
|
||||
int step = self->step ? self->step : CV_ELEM_SIZE(self->type) * self->cols;
|
||||
|
||||
if (depth == CV_8U && cn==3){
|
||||
// RGB case
|
||||
// The data is reordered beause OpenCV uses BGR instead of RGB
|
||||
|
||||
for (long line = 0; line < self->rows; ++line)
|
||||
for (long pixel = 0; pixel < self->cols; ++pixel)
|
||||
{
|
||||
// In OpenCV the beginning of the lines are aligned
|
||||
// to 4 Bytes. So use step instead of cols.
|
||||
long position = line*step + pixel*3;
|
||||
long sourcepos = line*self->cols*3 + pixel*3;
|
||||
self->data.ptr[position ] = py_string[sourcepos+2];
|
||||
self->data.ptr[position+1] = py_string[sourcepos+1];
|
||||
self->data.ptr[position+2] = py_string[sourcepos ];
|
||||
}
|
||||
}
|
||||
else if (depth == CV_8U && cn==1)
|
||||
{
|
||||
// Grayscale 8bit case
|
||||
|
||||
for (long line = 0; line < self->rows; ++line)
|
||||
{
|
||||
// In OpenCV the beginning of the lines are aligned
|
||||
// to 4 Bytes. So use step instead of cols.
|
||||
memcpy
|
||||
(
|
||||
self->data.ptr + line*step,
|
||||
py_string + line*self->cols,
|
||||
step
|
||||
);
|
||||
}
|
||||
}
|
||||
else if ( depth == CV_32F )
|
||||
{
|
||||
// float (32bit) case
|
||||
for (long line = 0; line < self->rows; ++line)
|
||||
{
|
||||
// here we don not have to care about alignment as the Floats are
|
||||
// as long as the alignment
|
||||
memcpy
|
||||
(
|
||||
self->data.ptr + line*step,
|
||||
py_string + line*self->cols*sizeof(float),
|
||||
step
|
||||
);
|
||||
}
|
||||
}
|
||||
else if ( depth == CV_64F )
|
||||
{
|
||||
// double (64bit) case
|
||||
for (long line = 0; line < self->rows; ++line)
|
||||
{
|
||||
// here we don not have to care about alignment as the Floats are
|
||||
// as long as the alignment
|
||||
memcpy
|
||||
(
|
||||
self->data.ptr + line*step,
|
||||
py_string + line*self->cols*sizeof(double),
|
||||
step
|
||||
);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// make some noise
|
||||
SendErrorToPython (SWIG_TypeError,
|
||||
"CvMat_imageData_set",
|
||||
"cannot convert string data to this image format",
|
||||
__FILE__, __LINE__, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
/// Accessor to convert the imageData into a Python string.
|
||||
PyObject* CvMat_imageData_get(CvMat * self)
|
||||
{
|
||||
if (!self->data.ptr)
|
||||
{
|
||||
PyErr_SetString(PyExc_TypeError, "Data pointer of CvMat is NULL");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
int step = self->step ? self->step : CV_ELEM_SIZE(self->type) * self->cols;
|
||||
return PyString_FromStringAndSize((const char *)self->data.ptr, self->rows*step);
|
||||
}
|
||||
|
||||
%}
|
||||
|
||||
// add virtual member variable to CvMat
|
||||
%extend CvMat {
|
||||
PyObject * imageData;
|
||||
};
|
269
interfaces/swig/python/matlab_syntax.py
Normal file
269
interfaces/swig/python/matlab_syntax.py
Normal file
@@ -0,0 +1,269 @@
|
||||
#########################################################################################
|
||||
#
|
||||
# IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
#
|
||||
# By downloading, copying, installing or using the software you agree to this license.
|
||||
# If you do not agree to this license, do not download, install,
|
||||
# copy or use the software.
|
||||
#
|
||||
#
|
||||
# Intel License Agreement
|
||||
# For Open Source Computer Vision Library
|
||||
#
|
||||
# Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
# Third party copyrights are property of their respective owners.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistribution's of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
# * The name of Intel Corporation may not be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# This software is provided by the copyright holders and contributors "as is" and
|
||||
# any express or implied warranties, including, but not limited to, the implied
|
||||
# warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
# In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
# indirect, incidental, special, exemplary, or consequential damages
|
||||
# (including, but not limited to, procurement of substitute goods or services;
|
||||
# loss of use, data, or profits; or business interruption) however caused
|
||||
# and on any theory of liability, whether in contract, strict liability,
|
||||
# or tort (including negligence or otherwise) arising in any way out of
|
||||
# the use of this software, even if advised of the possibility of such damage.
|
||||
#
|
||||
#########################################################################################
|
||||
|
||||
"""Matlab syntax for OpenCV
|
||||
|
||||
For those who have switched from Matlab, this module offers similar syntax to the basic
|
||||
Matlab commands. I.e. you can invoke 'imread' to load images, 'imshow', etc.
|
||||
"""
|
||||
|
||||
from cv import *
|
||||
from highgui import cvShowImage,cvNamedWindow,cvLoadImage,cvWaitKey
|
||||
|
||||
#__all__ = ['imagesc', 'display', 'imread', 'imshow', 'saveimage', 'loadimage', 'pause',
|
||||
# 'Image', 'Image8', 'Image8c3', 'Image32s', 'Image32f', 'Image64f']
|
||||
|
||||
def eye(*args):
|
||||
mat = array(*args)
|
||||
cvSetIdentity(mat);
|
||||
return mat
|
||||
|
||||
def ones(*args):
|
||||
mat = array(*args)
|
||||
cvSet(mat, cvScalarAll(1.0))
|
||||
return mat
|
||||
|
||||
def zeros(*args):
|
||||
mat = array(*args)
|
||||
cvSet(mat, cvScalarAll(0.0))
|
||||
return mat
|
||||
|
||||
def array(*args):
|
||||
m=1
|
||||
n=1
|
||||
c=1
|
||||
classname='single'
|
||||
nargs = len(args)
|
||||
# nasty argument parsing
|
||||
if nargs>0:
|
||||
if isinstance(args[0],tuple) or isinstance(args[0],list) and len(args[0]) > 1:
|
||||
m=args[0][0]
|
||||
n=args[0][1]
|
||||
if len(args[0])>2:
|
||||
c=args[0][2]
|
||||
if len(args)>1:
|
||||
classname = args[1]
|
||||
else:
|
||||
m=args[0]
|
||||
if nargs == 1:
|
||||
n=args[0]
|
||||
elif nargs > 1:
|
||||
# is the last argument the classname?
|
||||
if args[nargs-1].__class__ == str:
|
||||
classname = args[nargs-1]
|
||||
nargs-=1
|
||||
if nargs > 1:
|
||||
n = args[1]
|
||||
if nargs > 2:
|
||||
c = args[2]
|
||||
|
||||
if(classname=='double'):
|
||||
depth=cv.CV_64F
|
||||
elif(classname=='single'):
|
||||
depth=cv.CV_32F
|
||||
elif(classname=='int8'):
|
||||
depth=cv.CV_8S
|
||||
elif(classname=='uint8'):
|
||||
depth=cv.CV_8U
|
||||
elif(classname=='int16'):
|
||||
depth=cv.CV_16S
|
||||
elif(classname=='uint16'):
|
||||
depth=cv.CV_16U
|
||||
elif(classname=='int32' or classname=='uint32' or
|
||||
classname=='int64' or classname=='uint64'):
|
||||
depth=cv.CV_32S
|
||||
else:
|
||||
depth=cv.CV_32F
|
||||
depth = CV_MAKETYPE(depth, c)
|
||||
return cvCreateMat(m,n,depth)
|
||||
|
||||
def size(X,dim=-1):
|
||||
# CvMat
|
||||
if hasattr(X, "type"):
|
||||
sz = (X.rows, X.cols, CV_MAT_CN(X.type))
|
||||
# IplImage
|
||||
elif hasattr(X, "nChannels"):
|
||||
sz = (X.height, X.width, X.nChannels)
|
||||
# CvMatNd
|
||||
else:
|
||||
sz = cvGetDims(X)
|
||||
|
||||
if dim is -1:
|
||||
return sz
|
||||
return sz[dim]
|
||||
|
||||
def reshape(X, m, n=1, c=-1):
|
||||
'''
|
||||
reshape will produce different results in matlab and python due to the
|
||||
order of elements stored in the array (row-major vs. column major)
|
||||
'''
|
||||
if c==-1:
|
||||
c = CV_MAT_CN(X)
|
||||
return cvReshape(X, c, m)
|
||||
|
||||
|
||||
def im2float(im):
|
||||
mat = cvGetMat(im);
|
||||
if CV_MAT_DEPTH(mat.type)==CV_32F:
|
||||
return mat
|
||||
|
||||
im64f = array(size(im), 'float')
|
||||
cvConvertScale(im, im64f, 1.0, 0.0)
|
||||
return im64f
|
||||
|
||||
def im2double(im):
|
||||
mat = cvGetMat(im);
|
||||
if CV_MAT_DEPTH(mat.type)==CV_64F:
|
||||
return mat
|
||||
im64f = array(size(im), 'double')
|
||||
cvConvertScale(im, im64f, 1.0, 0.0)
|
||||
return im64f
|
||||
|
||||
def rgb2ntsc (rgb):
|
||||
trans = [ [0.299, 0.596, 0.211], [0.587, -0.274, -0.523], [0.114, -0.322, 0.312] ];
|
||||
return rgb * trans;
|
||||
|
||||
def rgb2gray(rgb):
|
||||
ntscmap = rgb2ntsc (rgb);
|
||||
graymap = ntscmap [:, 1] * ones (1, 3);
|
||||
return graymap
|
||||
|
||||
class cvImageViewer:
|
||||
"""
|
||||
Wrapper class for some matlab/octave/scilab syntax image viewing functions
|
||||
"""
|
||||
currentWindowName = ""
|
||||
currentWindow = -1
|
||||
maxWindow = -1
|
||||
|
||||
def imagesc(self,im, clims=None):
|
||||
"""
|
||||
Display a normalized version of the image
|
||||
"""
|
||||
if(self.currentWindow==-1):
|
||||
self.display()
|
||||
|
||||
# don't normalize multichannel image
|
||||
#if(im.nChannels>1):
|
||||
# if(im.depth!=cv.IPL_DEPTH_8U):
|
||||
# im2 = cvCreateImage( cvSize(im.width, im.height), cv.IPL_DEPTH_8U, im.nChannels)
|
||||
# cvScale(im, im2)
|
||||
# im = im2
|
||||
# cvShowImage(self.currentWindowName, im)
|
||||
# return self.currentWindow
|
||||
|
||||
# normalize image
|
||||
if clims:
|
||||
[minv, maxv] = clims
|
||||
else:
|
||||
[minv,maxv] = cvMinMaxLoc(im)
|
||||
if maxv != minv:
|
||||
s = 255.0/(maxv-minv)
|
||||
shift = 255*(-minv)/(maxv-minv)
|
||||
else:
|
||||
s = 1.0
|
||||
shift = -maxv
|
||||
|
||||
im2 = array( size(im), 'uint8' )
|
||||
cvConvertScale(im, im2, s, shift)
|
||||
|
||||
cvShowImage(self.currentWindowName, im2)
|
||||
|
||||
def image(self, im):
|
||||
"""
|
||||
Display image as is -- probably not what you'd expect for FP or integer images
|
||||
"""
|
||||
if(self.currentWindow==-1):
|
||||
self.display()
|
||||
|
||||
cvShowImage(self.currentWindowName,im)
|
||||
return self.currentWindow
|
||||
|
||||
|
||||
def display(self, index=-1):
|
||||
"""
|
||||
open a new window
|
||||
"""
|
||||
if(index==-1):
|
||||
self.maxWindow = self.maxWindow+1;
|
||||
index= self.maxWindow;
|
||||
|
||||
if(index > self.maxWindow):
|
||||
self.maxWindow = index;
|
||||
|
||||
self.currentWindow = index;
|
||||
self.currentWindowName = "opencv-python window %d" % self.currentWindow
|
||||
cvNamedWindow(self.currentWindowName,0)
|
||||
return self.currentWindow
|
||||
|
||||
def drawnow():
|
||||
cvWaitKey(10)
|
||||
|
||||
def pause(delay=-1):
|
||||
if delay<0:
|
||||
cvWaitKey(-1)
|
||||
else:
|
||||
cvWaitKey(delay*1000)
|
||||
|
||||
c = cvImageViewer()
|
||||
imagesc = c.imagesc
|
||||
display = c.display
|
||||
image = c.image
|
||||
imshow = c.image
|
||||
|
||||
def imread(fname):
|
||||
return cvLoadImage(fname, -1)
|
||||
loadimage = imread
|
||||
imload = imread
|
||||
|
||||
def imsave(im, fname, format):
|
||||
return cvSaveImage(fname, im)
|
||||
saveimage = imsave
|
||||
|
||||
def gradient(F):
|
||||
F = im2float(F)
|
||||
Fx = array(size(F))
|
||||
Fy = array(size(F))
|
||||
|
||||
# new images
|
||||
cvSobel(F, Fx, 1, 0, CV_SCHARR)
|
||||
cvSobel(F, Fy, 0, 1, CV_SCHARR)
|
||||
return (Fx, Fy)
|
118
interfaces/swig/python/ml.i
Normal file
118
interfaces/swig/python/ml.i
Normal file
@@ -0,0 +1,118 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
|
||||
// 2004-03-16, Mark Asbach <asbach@ient.rwth-aachen.de>
|
||||
// Institute of Communications Engineering, RWTH Aachen University
|
||||
|
||||
%module(package="opencv") ml
|
||||
|
||||
%{
|
||||
#include <ml.h>
|
||||
#include <cxtypes.h>
|
||||
#include <cv.h>
|
||||
#include <highgui.h>
|
||||
#include "pyhelpers.h"
|
||||
#include "pycvseq.hpp"
|
||||
%}
|
||||
|
||||
// include python-specific files
|
||||
%include "./nointpb.i"
|
||||
%include "./pytypemaps.i"
|
||||
%include "exception.i"
|
||||
|
||||
%import "../general/cv.i"
|
||||
|
||||
%include "../general/memory.i"
|
||||
%include "../general/typemaps.i"
|
||||
|
||||
%newobject cvCreateCNNConvolutionLayer;
|
||||
%newobject cvCreateCNNSubSamplingLayer;
|
||||
%newobject cvCreateCNNFullConnectLayer;
|
||||
%newobject cvCreateCNNetwork;
|
||||
%newobject cvTrainCNNClassifier;
|
||||
|
||||
%newobject cvCreateCrossValidationEstimateModel;
|
||||
|
||||
|
||||
%pythoncode
|
||||
%{
|
||||
|
||||
__doc__ = """Machine Learning
|
||||
|
||||
The Machine Learning library (ML) is a set of classes and functions for
|
||||
statistical classification, regression and clustering of data.
|
||||
|
||||
Most of the classification and regression algorithms are implemented as classes.
|
||||
As the algorithms have different sets of features (like ability to handle missing
|
||||
measurements, or categorical input variables etc.), there is only little common
|
||||
ground between the classes. This common ground is defined by the class CvStatModel
|
||||
that all the other ML classes are derived from.
|
||||
|
||||
This wrapper was semi-automatically created from the C/C++ headers and therefore
|
||||
contains no Python documentation. Because all identifiers are identical to their
|
||||
C/C++ counterparts, you can consult the standard manuals that come with OpenCV.
|
||||
"""
|
||||
|
||||
%}
|
||||
|
||||
%extend CvEM
|
||||
{
|
||||
PyObject * get_covs()
|
||||
{
|
||||
CvMat ** pointers = const_cast<CvMat **> (self->get_covs());
|
||||
int n = self->get_nclusters();
|
||||
|
||||
PyObject * result = PyTuple_New(n);
|
||||
for (int i=0; i<n; ++i)
|
||||
{
|
||||
PyObject * obj = SWIG_NewPointerObj(pointers[i], $descriptor(CvMat *), 0);
|
||||
PyTuple_SetItem(result, i, obj);
|
||||
//Py_DECREF(obj);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
%ignore CvEM::get_covs;
|
||||
|
||||
%include "ml.h"
|
1472
interfaces/swig/python/ml.py
Normal file
1472
interfaces/swig/python/ml.py
Normal file
File diff suppressed because it is too large
Load Diff
34
interfaces/swig/python/nointpb.i
Normal file
34
interfaces/swig/python/nointpb.i
Normal file
@@ -0,0 +1,34 @@
|
||||
/* This file is to prevent problems with swig <= 1.3.25 which use
|
||||
PyInt_AS_LONG and may cause some corruption on RedHat systems.
|
||||
|
||||
Include it in every .i file who generate a C/C++ file */
|
||||
|
||||
%runtime%{
|
||||
/* define the PyAPI_FUNC macro if it doesn't exist, for example with Python
|
||||
version below 2.3... But not really tested... */
|
||||
#ifndef PyAPI_FUNC
|
||||
# define PyAPI_FUNC(RTYPE) RTYPE
|
||||
#endif
|
||||
|
||||
/* remove the PyInt_AS_LONG if defined, as this cause problems on RedHat */
|
||||
#ifdef PyInt_AS_LONG
|
||||
#undef PyInt_AS_LONG
|
||||
#endif
|
||||
|
||||
/* wrapper to the better function PyInt_AsLong, removing problems
|
||||
with RedHat (I hope) */
|
||||
long PyInt_AS_LONG (PyObject *obj) {
|
||||
return PyInt_AsLong (obj);
|
||||
}
|
||||
|
||||
/* remove the PyFloat_AS_DOUBLE if defined, to prevent errors */
|
||||
#ifdef PyFloat_AS_DOUBLE
|
||||
#undef PyFloat_AS_DOUBLE
|
||||
#endif
|
||||
|
||||
/* wrapper to the better function PyFloat_AS_DOUBLE, to prevent errors */
|
||||
double PyFloat_AS_DOUBLE (PyObject *obj) {
|
||||
return PyFloat_AsDouble (obj);
|
||||
}
|
||||
%}
|
||||
|
104
interfaces/swig/python/pycvseq.hpp
Normal file
104
interfaces/swig/python/pycvseq.hpp
Normal file
@@ -0,0 +1,104 @@
|
||||
/*M///////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
||||
//
|
||||
// By downloading, copying, installing or using the software you agree to this license.
|
||||
// If you do not agree to this license, do not download, install,
|
||||
// copy or use the software.
|
||||
//
|
||||
//
|
||||
// Intel License Agreement
|
||||
// For Open Source Computer Vision Library
|
||||
//
|
||||
// Copyright (C) 2000, Intel Corporation, all rights reserved.
|
||||
// Third party copyrights are property of their respective owners.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistribution's of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistribution's in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * The name of Intel Corporation may not be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// This software is provided by the copyright holders and contributors "as is" and
|
||||
// any express or implied warranties, including, but not limited to, the implied
|
||||
// warranties of merchantability and fitness for a particular purpose are disclaimed.
|
||||
// In no event shall the Intel Corporation or contributors be liable for any direct,
|
||||
// indirect, incidental, special, exemplary, or consequential damages
|
||||
// (including, but not limited to, procurement of substitute goods or services;
|
||||
// loss of use, data, or profits; or business interruption) however caused
|
||||
// and on any theory of liability, whether in contract, strict liability,
|
||||
// or tort (including negligence or otherwise) arising in any way out of
|
||||
// the use of this software, even if advised of the possibility of such damage.
|
||||
//
|
||||
//M*/
|
||||
|
||||
#ifndef PY_CV_SEQ_H
|
||||
#define PY_CV_SEQ_H
|
||||
|
||||
#include "cxcore.h"
|
||||
#include "cvtypes.h"
|
||||
|
||||
|
||||
/** class to make sequence iteration nicer */
|
||||
template<class T>
|
||||
class CvTypedSeqReader : public CvSeqReader {
|
||||
int pos;
|
||||
public:
|
||||
CvTypedSeqReader( const CvSeq * seq ){
|
||||
cvStartReadSeq( seq, this );
|
||||
pos = 0;
|
||||
}
|
||||
T * current(){
|
||||
return (T*) this->ptr;
|
||||
}
|
||||
void next(){
|
||||
CV_NEXT_SEQ_ELEM( this->seq->elem_size, *this );
|
||||
pos++;
|
||||
}
|
||||
bool valid(){
|
||||
return pos<this->seq->total;
|
||||
}
|
||||
};
|
||||
|
||||
template<class T>
|
||||
class CvTypedSeq : public CvSeq {
|
||||
public:
|
||||
static CvTypedSeq<T> * cast(CvSeq * seq){
|
||||
return (CvTypedSeq<T> *) seq;
|
||||
}
|
||||
T * __getitem__ (int i){
|
||||
return (T *) cvGetSeqElem(this, i);
|
||||
}
|
||||
void __setitem__ (int i, T * obj){
|
||||
T * ptr = this->__getitem__(i);
|
||||
memcpy(ptr, obj, sizeof(T));
|
||||
}
|
||||
void append(T * obj){
|
||||
cvSeqPush( this, obj );
|
||||
}
|
||||
T * pop(){
|
||||
T * obj = new T;
|
||||
cvSeqPop( this, obj );
|
||||
return obj;
|
||||
}
|
||||
};
|
||||
|
||||
template<class T, int size=2>
|
||||
struct CvTuple {
|
||||
T val[2];
|
||||
void __setitem__(int i, T * obj){
|
||||
val[i] = *obj;
|
||||
}
|
||||
const T & __getitem__(int i){
|
||||
return val[i];
|
||||
}
|
||||
};
|
||||
|
||||
#endif //PY_CV_SEQ_H
|
606
interfaces/swig/python/pyhelpers.cpp
Normal file
606
interfaces/swig/python/pyhelpers.cpp
Normal file
@@ -0,0 +1,606 @@
|
||||
#include "pyhelpers.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
int PySwigObject_Check(PyObject *op);
|
||||
|
||||
/* Py_ssize_t for old Pythons */
|
||||
#if PY_VERSION_HEX < 0x02050000
|
||||
typedef int Py_ssize_t;
|
||||
#endif
|
||||
|
||||
PyObject * PyTuple_FromIntArray(int * arr, int len){
|
||||
PyObject * obj = PyTuple_New(len);
|
||||
for(int i=0; i<len; i++){
|
||||
PyTuple_SetItem(obj, i, PyLong_FromLong( arr[i] ) );
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
PyObject * SWIG_SetResult(PyObject * result, PyObject * obj){
|
||||
if(result){
|
||||
Py_DECREF(result);
|
||||
}
|
||||
result = PyTuple_New(1);
|
||||
PyTuple_SetItem(result, 0, obj);
|
||||
return result;
|
||||
}
|
||||
|
||||
PyObject * SWIG_AppendResult(PyObject * result, PyObject ** to_add, int num){
|
||||
if ((!result) || (result == Py_None)) {
|
||||
/* no other results, so just add our values */
|
||||
|
||||
/* if only one object, return that */
|
||||
if(num==1){
|
||||
return to_add[0];
|
||||
}
|
||||
|
||||
/* create a new tuple to put in our new pointer python objects */
|
||||
result = PyTuple_New (num);
|
||||
|
||||
/* put in our new pointer python objects */
|
||||
for(int i=0; i<num; i++){
|
||||
PyTuple_SetItem (result, i, to_add[i]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* we have other results, so add it to the end */
|
||||
|
||||
if (!PyTuple_Check (result)) {
|
||||
/* previous result is not a tuple, so create one and put
|
||||
previous result and current pointer in it */
|
||||
|
||||
/* first, save previous result */
|
||||
PyObject *obj_save = result;
|
||||
|
||||
/* then, create the tuple */
|
||||
result = PyTuple_New (1);
|
||||
|
||||
/* finaly, put the saved value in the tuple */
|
||||
PyTuple_SetItem (result, 0, obj_save);
|
||||
}
|
||||
|
||||
/* create a new tuple to put in our new pointer python object */
|
||||
PyObject *my_obj = PyTuple_New (num);
|
||||
|
||||
/* put in our new pointer python object */
|
||||
for( int i=0; i<num ; i++ ){
|
||||
PyTuple_SetItem (my_obj, i, to_add[i]);
|
||||
}
|
||||
|
||||
/* save the previous result */
|
||||
PyObject *obj_save = result;
|
||||
|
||||
/* concat previous and our new result */
|
||||
result = PySequence_Concat (obj_save, my_obj);
|
||||
|
||||
/* decrement the usage of no more used objects */
|
||||
Py_DECREF (obj_save);
|
||||
Py_DECREF (my_obj);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void cv_arr_write(FILE * f, const char * fmt, T * data, size_t rows, size_t nch, size_t step){
|
||||
size_t i,j,k;
|
||||
char * cdata = (char *) data;
|
||||
const char * chdelim1="", * chdelim2="";
|
||||
|
||||
// only output channel parens if > 1
|
||||
if(nch>1){
|
||||
chdelim1="(";
|
||||
chdelim2=")";
|
||||
}
|
||||
|
||||
fputs("[",f);
|
||||
for(i=0; i<rows; i++){
|
||||
fputs("[",f);
|
||||
|
||||
// first element
|
||||
// out<<chdelim1;
|
||||
fputs(chdelim1, f);
|
||||
fprintf(f, fmt, ((T*)(cdata+i*step))[0]);
|
||||
for(k=1; k<nch; k++){
|
||||
fputs(", ", f);
|
||||
fprintf(f, fmt, ((T*)(cdata+i*step))[k]);
|
||||
}
|
||||
fputs(chdelim2,f);
|
||||
|
||||
// remaining elements
|
||||
for(j=nch*sizeof(T); j<step; j+=(nch*sizeof(T))){
|
||||
fprintf(f, ",%s", chdelim1);
|
||||
fprintf(f, fmt, ((T*)(cdata+i*step+j))[0]);
|
||||
for(k=1; k<nch; k++){
|
||||
fputs(", ", f);
|
||||
fprintf(f, fmt, ((T*)(cdata+i*step+j))[k]);
|
||||
}
|
||||
fputs(chdelim2, f);
|
||||
}
|
||||
fputs( "]\n", f );
|
||||
}
|
||||
fputs( "]", f );
|
||||
}
|
||||
|
||||
void cvArrPrint(CvArr * arr){
|
||||
CvMat * mat;
|
||||
CvMat stub;
|
||||
|
||||
mat = cvGetMat(arr, &stub);
|
||||
|
||||
int cn = CV_MAT_CN(mat->type);
|
||||
int depth = CV_MAT_DEPTH(mat->type);
|
||||
int step = MAX(mat->step, cn*mat->cols*CV_ELEM_SIZE(depth));
|
||||
|
||||
|
||||
switch(depth){
|
||||
case CV_8U:
|
||||
cv_arr_write(stdout, "%u", (uchar *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_8S:
|
||||
cv_arr_write(stdout, "%d", (char *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_16U:
|
||||
cv_arr_write(stdout, "%u", (ushort *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_16S:
|
||||
cv_arr_write(stdout, "%d", (short *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_32S:
|
||||
cv_arr_write(stdout, "%d", (int *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_32F:
|
||||
cv_arr_write(stdout, "%f", (float *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
case CV_64F:
|
||||
cv_arr_write(stdout, "%g", (double *)mat->data.ptr, mat->rows, cn, step);
|
||||
break;
|
||||
default:
|
||||
CV_Error( CV_StsError, "Unknown element type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// deal with negative array indices
|
||||
int PyLong_AsIndex( PyObject * idx_object, int len ){
|
||||
int idx = PyLong_AsLong( idx_object );
|
||||
if(idx<0) return len+idx;
|
||||
return idx;
|
||||
}
|
||||
|
||||
CvRect PySlice_to_CvRect(CvArr * src, PyObject * idx_object){
|
||||
CvSize sz = cvGetSize(src);
|
||||
//printf("Size %dx%d\n", sz.height, sz.width);
|
||||
int lower[2], upper[2];
|
||||
Py_ssize_t len, start, stop, step, slicelength;
|
||||
|
||||
if(PyInt_Check(idx_object) || PyLong_Check(idx_object)){
|
||||
// if array is a row vector, assume index into columns
|
||||
if(sz.height>1){
|
||||
lower[0] = PyLong_AsIndex( idx_object, sz.height );
|
||||
upper[0] = lower[0] + 1;
|
||||
lower[1] = 0;
|
||||
upper[1] = sz.width;
|
||||
}
|
||||
else{
|
||||
lower[0] = 0;
|
||||
upper[0] = sz.height;
|
||||
lower[1] = PyLong_AsIndex( idx_object, sz.width );
|
||||
upper[1] = lower[1]+1;
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Slice
|
||||
else if(PySlice_Check(idx_object)){
|
||||
len = sz.height;
|
||||
if(PySlice_GetIndicesEx( (PySliceObject*)idx_object, len, &start, &stop, &step, &slicelength )!=0){
|
||||
printf("Error in PySlice_GetIndicesEx: returning NULL");
|
||||
PyErr_SetString(PyExc_Exception, "Error");
|
||||
return cvRect(0,0,0,0);
|
||||
}
|
||||
// if array is a row vector, assume index bounds are into columns
|
||||
if(sz.height>1){
|
||||
lower[0] = (int) start; // use c convention of start index = 0
|
||||
upper[0] = (int) stop; // use c convention
|
||||
lower[1] = 0;
|
||||
upper[1] = sz.width;
|
||||
}
|
||||
else{
|
||||
lower[1] = (int) start; // use c convention of start index = 0
|
||||
upper[1] = (int) stop; // use c convention
|
||||
lower[0] = 0;
|
||||
upper[0] = sz.height;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Tuple
|
||||
else if(PyTuple_Check(idx_object)){
|
||||
//printf("PyTuple{\n");
|
||||
if(PyObject_Length(idx_object)!=2){
|
||||
//printf("Expected a sequence of length 2: returning NULL");
|
||||
PyErr_SetString(PyExc_ValueError, "Expected a sequence with 2 elements");
|
||||
return cvRect(0,0,0,0);
|
||||
}
|
||||
for(int i=0; i<2; i++){
|
||||
PyObject *o = PyTuple_GetItem(idx_object, i);
|
||||
|
||||
// 2a. Slice -- same as above
|
||||
if(PySlice_Check(o)){
|
||||
//printf("PySlice\n");
|
||||
len = (i==0 ? sz.height : sz.width);
|
||||
if(PySlice_GetIndicesEx( (PySliceObject*)o, len, &start, &stop, &step, &slicelength )!=0){
|
||||
PyErr_SetString(PyExc_Exception, "Error");
|
||||
printf("Error in PySlice_GetIndicesEx: returning NULL");
|
||||
return cvRect(0,0,0,0);
|
||||
}
|
||||
//printf("PySlice_GetIndecesEx(%d, %d, %d, %d, %d)\n", len, start, stop, step, slicelength);
|
||||
lower[i] = start;
|
||||
upper[i] = stop;
|
||||
|
||||
}
|
||||
|
||||
// 2b. Integer
|
||||
else if(PyInt_Check(o) || PyLong_Check(o)){
|
||||
//printf("PyInt\n");
|
||||
lower[i] = PyLong_AsIndex(o, i==0 ? sz.height : sz.width);
|
||||
upper[i] = lower[i]+1;
|
||||
}
|
||||
|
||||
else {
|
||||
PyErr_SetString(PyExc_TypeError, "Expected a sequence of slices or integers");
|
||||
printf("Expected a slice or int as sequence item: returning NULL");
|
||||
return cvRect(0,0,0,0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
PyErr_SetString( PyExc_TypeError, "Expected a slice or sequence");
|
||||
printf("Expected a slice or sequence: returning NULL");
|
||||
return cvRect(0,0,0,0);
|
||||
}
|
||||
|
||||
//lower[0] = MAX(0, lower[0]);
|
||||
//lower[1] = MAX(0, lower[1]);
|
||||
//upper[0] = MIN(sz.height, upper[0]);
|
||||
//upper[1] = MIN(sz.width, upper[1]);
|
||||
//printf("Slice=%d %d %d %d\n", lower[0], upper[0], lower[1], upper[1]);
|
||||
return cvRect(lower[1],lower[0], upper[1]-lower[1], upper[0]-lower[0]);
|
||||
}
|
||||
|
||||
int CheckSliceBounds(CvRect * rect, int w, int h){
|
||||
//printf("__setitem__ slice(%d:%d, %d:%d) array(%d,%d)", rect.x, rect.y, rect.x+rect.width, rect.y+rect.height, w, h);
|
||||
if(rect->width<=0 || rect->height<=0 ||
|
||||
rect->width>w || rect->height>h ||
|
||||
rect->x<0 || rect->y<0 ||
|
||||
rect->x>= w || rect->y >=h){
|
||||
char errstr[256];
|
||||
|
||||
// previous function already set error string
|
||||
if(rect->width==0 && rect->height==0 && rect->x==0 && rect->y==0) return -1;
|
||||
|
||||
sprintf(errstr, "Requested slice [ %d:%d %d:%d ] oversteps array sized [ %d %d ]",
|
||||
rect->x, rect->y, rect->x+rect->width, rect->y+rect->height, w, h);
|
||||
PyErr_SetString(PyExc_IndexError, errstr);
|
||||
//PyErr_SetString(PyExc_ValueError, errstr);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
double PyObject_AsDouble(PyObject * obj){
|
||||
if(PyNumber_Check(obj)){
|
||||
if(PyFloat_Check(obj)){
|
||||
return PyFloat_AsDouble(obj);
|
||||
}
|
||||
else if(PyInt_Check(obj) || PyLong_Check(obj)){
|
||||
return (double) PyLong_AsLong(obj);
|
||||
}
|
||||
}
|
||||
PyErr_SetString( PyExc_TypeError, "Could not convert python object to Double");
|
||||
return -1;
|
||||
}
|
||||
|
||||
long PyObject_AsLong(PyObject * obj){
|
||||
if(PyNumber_Check(obj)){
|
||||
if(PyFloat_Check(obj)){
|
||||
return (long) PyFloat_AsDouble(obj);
|
||||
}
|
||||
else if(PyInt_Check(obj) || PyLong_Check(obj)){
|
||||
return PyLong_AsLong(obj);
|
||||
}
|
||||
}
|
||||
PyErr_SetString( PyExc_TypeError, "Could not convert python object to Long");
|
||||
return -1;
|
||||
}
|
||||
|
||||
CvArr * PyArray_to_CvArr (PyObject * obj)
|
||||
{
|
||||
// let's try to create a temporary CvMat header that points to the
|
||||
// data owned by obj and reflects its memory layout
|
||||
|
||||
CvArr * cvarr = NULL;
|
||||
|
||||
void * raw_data = 0;
|
||||
long rows;
|
||||
long cols;
|
||||
long channels;
|
||||
long step;
|
||||
long mat_type = 7;
|
||||
long element_size = 1;
|
||||
|
||||
// infer layout from array interface
|
||||
PyObject * interface = PyObject_GetAttrString (obj, "__array_interface__");
|
||||
|
||||
|
||||
// the array interface should be a dict
|
||||
if (PyMapping_Check (interface))
|
||||
{
|
||||
if (PyMapping_HasKeyString (interface, (char*)"version") &&
|
||||
PyMapping_HasKeyString (interface, (char*)"shape") &&
|
||||
PyMapping_HasKeyString (interface, (char*)"typestr") &&
|
||||
PyMapping_HasKeyString (interface, (char*)"data"))
|
||||
{
|
||||
PyObject * version = PyMapping_GetItemString (interface, (char*)"version");
|
||||
PyObject * shape = PyMapping_GetItemString (interface, (char*)"shape");
|
||||
PyObject * typestr = PyMapping_GetItemString (interface, (char*)"typestr");
|
||||
PyObject * data = PyMapping_GetItemString (interface, (char*)"data");
|
||||
|
||||
if (!PyInt_Check (version) || PyInt_AsLong (version) != 3)
|
||||
PyErr_SetString(PyExc_TypeError, "OpenCV understands version 3 of the __array_interface__ only");
|
||||
else
|
||||
{
|
||||
if (!PyTuple_Check (shape) || PyTuple_Size (shape) < 2 || PyTuple_Size (shape) > 3)
|
||||
PyErr_SetString(PyExc_TypeError, "arrays must have a shape with 2 or 3 dimensions");
|
||||
else
|
||||
{
|
||||
rows = PyInt_AsLong (PyTuple_GetItem (shape, 0));
|
||||
cols = PyInt_AsLong (PyTuple_GetItem (shape, 1));
|
||||
channels = PyTuple_Size (shape) < 3 ? 1 : PyInt_AsLong (PyTuple_GetItem (shape, 2));
|
||||
|
||||
if (rows < 1 || cols < 1 || channels < 1 || channels > 4)
|
||||
PyErr_SetString(PyExc_TypeError, "rows and columns must be positive, channels from 1 to 4");
|
||||
else
|
||||
{
|
||||
// fprintf (stderr, "rows: %ld, cols: %ld, channels %ld\n", rows, cols, channels); fflush (stderr);
|
||||
|
||||
if (! PyTuple_Check (data) || PyTuple_Size (data) != 2 ||
|
||||
!(PyInt_Check (PyTuple_GetItem (data,0)) || PyLong_Check (PyTuple_GetItem (data,0))) ||
|
||||
!(PyBool_Check (PyTuple_GetItem (data,1)) && !PyInt_AsLong (PyTuple_GetItem (data,1))))
|
||||
PyErr_SetString (PyExc_TypeError, "arrays must have a pointer to writeable data");
|
||||
else
|
||||
{
|
||||
raw_data = PyLong_AsVoidPtr (PyTuple_GetItem (data,0));
|
||||
// fprintf(stderr, "raw_data: %p\n", raw_data); fflush (stderr);
|
||||
|
||||
char * format_str = NULL;
|
||||
Py_ssize_t len = 0;
|
||||
|
||||
if (!PyString_Check (typestr) || PyString_AsStringAndSize (typestr, & format_str, &len) == -1 || len !=3)
|
||||
PyErr_SetString(PyExc_TypeError, "there is something wrong with the format string");
|
||||
else
|
||||
{
|
||||
// fprintf(stderr, "format: %c %c\n", format_str[1], format_str[2]); fflush (stderr);
|
||||
|
||||
if (format_str[1] == 'u' && format_str[2] == '1')
|
||||
{
|
||||
element_size = 1;
|
||||
mat_type = CV_MAKETYPE(CV_8U, channels);
|
||||
}
|
||||
else if (format_str[1] == 'i' && format_str[2] == '1')
|
||||
{
|
||||
element_size = 1;
|
||||
mat_type = CV_MAKETYPE(CV_8S, channels);
|
||||
}
|
||||
else if (format_str[1] == 'u' && format_str[2] == '2')
|
||||
{
|
||||
element_size = 2;
|
||||
mat_type = CV_MAKETYPE(CV_16U, channels);
|
||||
}
|
||||
else if (format_str[1] == 'i' && format_str[2] == '2')
|
||||
{
|
||||
element_size = 2;
|
||||
mat_type = CV_MAKETYPE(CV_16S, channels);
|
||||
}
|
||||
else if (format_str[1] == 'i' && format_str[2] == '4')
|
||||
{
|
||||
element_size = 4;
|
||||
mat_type = CV_MAKETYPE(CV_32S, channels);
|
||||
}
|
||||
else if (format_str[1] == 'f' && format_str[2] == '4')
|
||||
{
|
||||
element_size = 4;
|
||||
mat_type = CV_MAKETYPE(CV_32F, channels);
|
||||
}
|
||||
else if (format_str[1] == 'f' && format_str[2] == '8')
|
||||
{
|
||||
element_size = 8;
|
||||
mat_type = CV_MAKETYPE(CV_64F, channels);
|
||||
}
|
||||
else
|
||||
{
|
||||
PyErr_SetString(PyExc_TypeError, "unknown or unhandled element format");
|
||||
mat_type = CV_USRTYPE1;
|
||||
}
|
||||
|
||||
// handle strides if given
|
||||
// TODO: implement stride handling
|
||||
step = cols * channels * element_size;
|
||||
if (PyMapping_HasKeyString (interface, (char*)"strides"))
|
||||
{
|
||||
PyObject * strides = PyMapping_GetItemString (interface, (char*)"strides");
|
||||
|
||||
if (strides != Py_None)
|
||||
{
|
||||
fprintf(stderr, "we have strides ... not handled!\n"); fflush (stderr);
|
||||
PyErr_SetString(PyExc_TypeError, "arrays with strides not handled yet");
|
||||
mat_type = CV_USRTYPE1; // use this to denote, we've got an error
|
||||
}
|
||||
|
||||
Py_DECREF (strides);
|
||||
}
|
||||
|
||||
// create matrix header if everything is okay
|
||||
if (mat_type != CV_USRTYPE1)
|
||||
{
|
||||
CvMat * temp_matrix = cvCreateMatHeader (rows, cols, mat_type);
|
||||
cvSetData (temp_matrix, raw_data, step);
|
||||
cvarr = temp_matrix;
|
||||
|
||||
// fprintf(stderr, "step_size: %ld, type: %ld\n", step, mat_type); fflush (stderr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Py_DECREF (data);
|
||||
Py_DECREF (typestr);
|
||||
Py_DECREF (shape);
|
||||
Py_DECREF (version);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Py_DECREF (interface);
|
||||
|
||||
return cvarr;
|
||||
}
|
||||
|
||||
|
||||
// Convert Python lists to CvMat *
|
||||
CvArr * PySequence_to_CvArr (PyObject * obj)
|
||||
{
|
||||
int dims [CV_MAX_DIM] = { 1, 1, 1};
|
||||
PyObject * container[CV_MAX_DIM+1] = {NULL, NULL, NULL, NULL};
|
||||
int ndim = 0;
|
||||
PyObject * item = Py_None;
|
||||
|
||||
// TODO: implement type detection - currently we create CV_64F only
|
||||
// scan full array to
|
||||
// - figure out dimensions
|
||||
// - check consistency of dimensions
|
||||
// - find appropriate data-type and signedness
|
||||
// enum NEEDED_DATATYPE { NEEDS_CHAR, NEEDS_INTEGER, NEEDS_FLOAT, NEEDS_DOUBLE };
|
||||
// NEEDED_DATATYPE needed_datatype = NEEDS_CHAR;
|
||||
// bool needs_sign = false;
|
||||
|
||||
// scan first entries to find out dimensions
|
||||
for (item = obj, ndim = 0; PySequence_Check (item) && ndim <= CV_MAX_DIM; ndim++)
|
||||
{
|
||||
dims [ndim] = PySequence_Size (item);
|
||||
container [ndim] = PySequence_GetItem (item, 0);
|
||||
item = container[ndim];
|
||||
}
|
||||
|
||||
// in contrast to PyTuple_GetItem, PySequence_GetItame returns a NEW reference
|
||||
if (container[0])
|
||||
{
|
||||
Py_DECREF (container[0]);
|
||||
}
|
||||
if (container[1])
|
||||
{
|
||||
Py_DECREF (container[1]);
|
||||
}
|
||||
if (container[2])
|
||||
{
|
||||
Py_DECREF (container[2]);
|
||||
}
|
||||
if (container[3])
|
||||
{
|
||||
Py_DECREF (container[3]);
|
||||
}
|
||||
|
||||
// it only makes sense to support 2 and 3 dimensional data at this time
|
||||
if (ndim < 2 || ndim > 3)
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "Nested sequences should have 2 or 3 dimensions");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// also, the number of channels should match what's typical for OpenCV
|
||||
if (ndim == 3 && (dims[2] < 1 || dims[2] > 4))
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "Currently, the third dimension of CvMat only supports 1 to 4 channels");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// CvMat
|
||||
CvMat * matrix = cvCreateMat (dims[0], dims[1], CV_MAKETYPE (CV_64F, dims[2]));
|
||||
|
||||
for (int y = 0; y < dims[0]; y++)
|
||||
{
|
||||
PyObject * rowobj = PySequence_GetItem (obj, y);
|
||||
|
||||
// double check size
|
||||
if (PySequence_Check (rowobj) && PySequence_Size (rowobj) == dims[1])
|
||||
{
|
||||
for (int x = 0; x < dims[1]; x++)
|
||||
{
|
||||
PyObject * colobj = PySequence_GetItem (rowobj, x);
|
||||
|
||||
if (dims [2] > 1)
|
||||
{
|
||||
if (PySequence_Check (colobj) && PySequence_Size (colobj) == dims[2])
|
||||
{
|
||||
PyObject * tuple = PySequence_Tuple (colobj);
|
||||
|
||||
double a, b, c, d;
|
||||
if (PyArg_ParseTuple (colobj, "d|d|d|d", &a, &b, &c, &d))
|
||||
{
|
||||
cvSet2D (matrix, y, x, cvScalar (a, b, c, d));
|
||||
}
|
||||
else
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
|
||||
cvReleaseMat (& matrix);
|
||||
Py_DECREF (tuple);
|
||||
Py_DECREF (colobj);
|
||||
Py_DECREF (rowobj);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_DECREF (tuple);
|
||||
}
|
||||
else
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
|
||||
cvReleaseMat (& matrix);
|
||||
Py_DECREF (colobj);
|
||||
Py_DECREF (rowobj);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (PyFloat_Check (colobj) || PyInt_Check (colobj))
|
||||
{
|
||||
cvmSet (matrix, y, x, PyFloat_AsDouble (colobj));
|
||||
}
|
||||
else
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "OpenCV only accepts numbers that can be converted to float");
|
||||
cvReleaseMat (& matrix);
|
||||
Py_DECREF (colobj);
|
||||
Py_DECREF (rowobj);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
Py_DECREF (colobj);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
PyErr_SetString (PyExc_TypeError, "All sub-sequences must have the same number of entries");
|
||||
cvReleaseMat (& matrix);
|
||||
Py_DECREF (rowobj);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_DECREF (rowobj);
|
||||
}
|
||||
|
||||
return matrix;
|
||||
}
|
44
interfaces/swig/python/pyhelpers.h
Normal file
44
interfaces/swig/python/pyhelpers.h
Normal file
@@ -0,0 +1,44 @@
|
||||
#ifndef PYHELPERS_H
|
||||
#define PYHELPERS_H
|
||||
|
||||
#include <Python.h>
|
||||
#include <cxcore.h>
|
||||
#include <cv.h>
|
||||
|
||||
/** convert python index object (tuple, integer, or slice) to CvRect for subsequent cvGetSubMat call */
|
||||
CvRect PySlice_to_CvRect(CvArr * src, PyObject * idx_object);
|
||||
|
||||
/** 1 if rectangle is a subrectangle of [0,0,w,h], 0 otherwise */
|
||||
int CheckSliceBounds(CvRect * rect, int w, int h );
|
||||
|
||||
/// convert object that supports the array protocol to CvMat *
|
||||
CvArr * PyArray_to_CvArr (PyObject * obj);
|
||||
|
||||
/// convert nested sequences to CvMat *
|
||||
CvArr * PySequence_to_CvArr (PyObject * obj);
|
||||
|
||||
/** prints array to stdout
|
||||
* TODO: python __str__ and __repr__ return strings, so this should write to a string
|
||||
*/
|
||||
void cvArrPrint (CvArr * mat);
|
||||
|
||||
/** Convert an integer array to python tuple */
|
||||
PyObject * PyTuple_FromIntArray(int * arr, int len);
|
||||
|
||||
/** If result is not NULL or PyNone, release object and replace it with obj */
|
||||
PyObject * SWIG_SetResult(PyObject * result, PyObject * obj);
|
||||
|
||||
/** helper function to append one or more objects to the swig $result array */
|
||||
PyObject * SWIG_AppendResult(PyObject * result, PyObject ** to_add, int num);
|
||||
|
||||
/** helper function to convert python scalar or sequence to int, float or double arrays */
|
||||
double PyObject_AsDouble(PyObject * obj);
|
||||
long PyObject_AsLong(PyObject * obj);
|
||||
|
||||
int PyObject_AsDoubleArray(PyObject * obj, double * array, int len);
|
||||
int PyObject_AsLongArray( PyObject * obj, int * array, int len);
|
||||
int PyObject_AsFloatArray(PyObject * obj, float * array, int len);
|
||||
|
||||
static inline int cvCvToIplDepth(int type) { return cvIplDepth(type); }
|
||||
|
||||
#endif //PYHELPERS_H
|
239
interfaces/swig/python/pyhelpers.i
Normal file
239
interfaces/swig/python/pyhelpers.i
Normal file
@@ -0,0 +1,239 @@
|
||||
/* These functions need the SWIG_* functions defined in the wrapper */
|
||||
%{
|
||||
|
||||
#include "pyhelpers.h"
|
||||
|
||||
static CvArr * PyObject_to_CvArr(PyObject * obj, bool * freearg);
|
||||
|
||||
// convert a python sequence/array/list object into a c-array
|
||||
#define PyObject_AsArrayImpl(func, ctype, ptype) \
|
||||
int func(PyObject * obj, ctype * array, int len){ \
|
||||
void * mat_vptr=NULL; \
|
||||
void * im_vptr=NULL; \
|
||||
if(PyNumber_Check(obj)){ \
|
||||
memset( array, 0, sizeof(ctype)*len ); \
|
||||
array[0] = PyObject_As##ptype( obj ); \
|
||||
} \
|
||||
else if(PyList_Check(obj) || PyTuple_Check(obj)){ \
|
||||
int seqsize = PySequence_Size(obj); \
|
||||
for(int i=0; i<len && i<seqsize; i++){ \
|
||||
if(i<seqsize){ \
|
||||
array[i] = PyObject_As##ptype( PySequence_GetItem(obj, i) ); \
|
||||
} \
|
||||
else{ \
|
||||
array[i] = 0; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else if( SWIG_ConvertPtr(obj, &mat_vptr, SWIGTYPE_p_CvMat, 0)!=-1 || \
|
||||
SWIG_ConvertPtr(obj, &im_vptr, SWIGTYPE_p__IplImage, 0)!=-1) \
|
||||
{ \
|
||||
CvMat * mat = (CvMat *) mat_vptr; \
|
||||
CvMat stub; \
|
||||
if(im_vptr) mat = cvGetMat(im_vptr, &stub); \
|
||||
if( mat->rows!=1 && mat->cols!=1 ){ \
|
||||
PyErr_SetString( PyExc_TypeError, \
|
||||
"PyObject_As*Array: CvArr must be row or column vector" ); \
|
||||
return -1; \
|
||||
} \
|
||||
if( mat->rows==1 && mat->cols==1 ){ \
|
||||
CvScalar val; \
|
||||
if( len!=CV_MAT_CN(mat->type) ){ \
|
||||
PyErr_SetString( PyExc_TypeError, \
|
||||
"PyObject_As*Array: CvArr channels != length" ); \
|
||||
return -1; \
|
||||
} \
|
||||
val = cvGet1D(mat, 0); \
|
||||
for(int i=0; i<len; i++){ \
|
||||
array[i] = (ctype) val.val[i]; \
|
||||
} \
|
||||
} \
|
||||
else{ \
|
||||
mat = cvReshape(mat, &stub, -1, mat->rows*mat->cols); \
|
||||
if( mat->rows != len ){ \
|
||||
PyErr_SetString( PyExc_TypeError, \
|
||||
"PyObject_As*Array: CvArr rows or cols must equal length" ); \
|
||||
return -1; \
|
||||
} \
|
||||
for(int i=0; i<len; i++){ \
|
||||
CvScalar val = cvGet1D(mat, i); \
|
||||
array[i] = (ctype) val.val[0]; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
else{ \
|
||||
PyErr_SetString( PyExc_TypeError, \
|
||||
"PyObject_As*Array: Expected a number, sequence or CvArr" ); \
|
||||
return -1; \
|
||||
} \
|
||||
return 0; \
|
||||
}
|
||||
|
||||
PyObject_AsArrayImpl( PyObject_AsFloatArray, float, Double );
|
||||
PyObject_AsArrayImpl( PyObject_AsDoubleArray, double, Double );
|
||||
PyObject_AsArrayImpl( PyObject_AsLongArray, int, Long );
|
||||
|
||||
static CvPoint PyObject_to_CvPoint(PyObject * obj){
|
||||
CvPoint val;
|
||||
CvPoint *ptr;
|
||||
CvPoint2D32f * ptr2D32f;
|
||||
CvScalar * scalar;
|
||||
|
||||
if( SWIG_ConvertPtr(obj, (void**)&ptr, SWIGTYPE_p_CvPoint, 0) != -1) {
|
||||
return *ptr;
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&ptr2D32f, SWIGTYPE_p_CvPoint2D32f, 0) != -1) {
|
||||
return cvPointFrom32f( *ptr2D32f );
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&scalar, SWIGTYPE_p_CvScalar, 0) != -1) {
|
||||
return cvPointFrom32f(cvPoint2D32f( scalar->val[0], scalar->val[1] ));
|
||||
}
|
||||
if(PyObject_AsLongArray(obj, (int *) &val, 2) != -1){
|
||||
return val;
|
||||
}
|
||||
|
||||
PyErr_SetString( PyExc_TypeError, "could not convert to CvPoint");
|
||||
return cvPoint(0,0);
|
||||
}
|
||||
|
||||
static CvPoint2D32f PyObject_to_CvPoint2D32f(PyObject * obj){
|
||||
CvPoint2D32f val;
|
||||
CvPoint2D32f *ptr2D32f;
|
||||
CvPoint *ptr;
|
||||
CvScalar * scalar;
|
||||
if( SWIG_ConvertPtr(obj, (void**)&ptr2D32f, SWIGTYPE_p_CvPoint2D32f, 0) != -1) {
|
||||
return *ptr2D32f;
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&ptr, SWIGTYPE_p_CvPoint, 0) != -1) {
|
||||
return cvPointTo32f(*ptr);
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&scalar, SWIGTYPE_p_CvScalar, 0) != -1) {
|
||||
return cvPoint2D32f( scalar->val[0], scalar->val[1] );
|
||||
}
|
||||
if(PyObject_AsFloatArray(obj, (float *) &val, 2) != -1){
|
||||
return val;
|
||||
}
|
||||
PyErr_SetString(PyExc_TypeError, "could not convert to CvPoint2D32f");
|
||||
return cvPoint2D32f(0,0);
|
||||
}
|
||||
|
||||
/* Check if this object can be interpreted as a CvScalar */
|
||||
static bool CvScalar_Check(PyObject * obj){
|
||||
void * vptr;
|
||||
CvScalar val;
|
||||
return SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvScalar, 0 ) != -1 ||
|
||||
SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint2D32f, 0 ) != -1 ||
|
||||
SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint, 0 ) != -1 ||
|
||||
PyObject_AsDoubleArray(obj, val.val, 4) !=-1;
|
||||
}
|
||||
|
||||
static CvScalar PyObject_to_CvScalar(PyObject * obj){
|
||||
CvScalar val;
|
||||
CvScalar * ptr;
|
||||
CvPoint2D32f *ptr2D32f;
|
||||
CvPoint *pt_ptr;
|
||||
void * vptr;
|
||||
if( SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvScalar, 0 ) != -1)
|
||||
{
|
||||
ptr = (CvScalar *) vptr;
|
||||
return *ptr;
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&ptr2D32f, SWIGTYPE_p_CvPoint2D32f, 0) != -1) {
|
||||
return cvScalar(ptr2D32f->x, ptr2D32f->y);
|
||||
}
|
||||
if( SWIG_ConvertPtr(obj, (void**)&pt_ptr, SWIGTYPE_p_CvPoint, 0) != -1) {
|
||||
return cvScalar(pt_ptr->x, pt_ptr->y);
|
||||
}
|
||||
if(PyObject_AsDoubleArray(obj, val.val, 4)!=-1){
|
||||
return val;
|
||||
}
|
||||
return cvScalar(-1,-1,-1,-1);
|
||||
}
|
||||
|
||||
static int CvArr_Check( PyObject * obj )
|
||||
{
|
||||
void *ptr;
|
||||
if( obj == Py_None ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_void, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_CvMat, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_CvSeq, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_CvContour, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_CvSparseMat, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr(obj, &ptr, SWIGTYPE_p_CvMatND, 0) ) ||
|
||||
PyObject_HasAttrString(obj, "__array_interface__") ||
|
||||
PySequence_Check(obj) )
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
PyErr_Clear();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* if python sequence type, convert to CvMat or CvMatND */
|
||||
static CvArr * PyObject_to_CvArr (PyObject * obj, bool * freearg)
|
||||
{
|
||||
CvArr * cvarr = NULL;
|
||||
*freearg = false;
|
||||
|
||||
if ( obj == Py_None )
|
||||
{
|
||||
// Interpret None as NULL pointer
|
||||
return NULL;
|
||||
}
|
||||
else if( SWIG_IsOK( SWIG_ConvertPtr(obj, (void **)& cvarr, SWIGTYPE_p_void, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr (obj, (void** )& cvarr, SWIGTYPE_p_CvMat, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr (obj, (void **)& cvarr, SWIGTYPE_p_CvSeq, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr (obj, (void **)& cvarr, SWIGTYPE_p_CvContour, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr (obj, (void **)& cvarr, SWIGTYPE_p_CvSparseMat, 0) ) ||
|
||||
SWIG_IsOK( SWIG_ConvertPtr (obj, (void **)& cvarr, SWIGTYPE_p_CvMatND, 0) ))
|
||||
{
|
||||
// we got a directly wrapped void * pointer, OpenCV array or sequence type
|
||||
return cvarr;
|
||||
}
|
||||
else if (PyObject_HasAttrString (obj, "__array_interface__"))
|
||||
{
|
||||
// if we didn't get our own datatype, let's see if it supports the array protocol
|
||||
// array protocol is great because we just have to create another header but can
|
||||
// use the original data without copying
|
||||
cvarr = PyArray_to_CvArr (obj);
|
||||
*freearg = (cvarr != NULL);
|
||||
}
|
||||
else if (PySequence_Check (obj))
|
||||
{
|
||||
// our next bet is a tuple or list of tuples or lists this has to be copied over, however
|
||||
cvarr = PySequence_to_CvArr (obj);
|
||||
*freearg = (cvarr != NULL);
|
||||
}
|
||||
else if (PyLong_Check (obj) && PyLong_AsLong (obj) == 0)
|
||||
{
|
||||
// Interpret a '0' integer as a NULL pointer
|
||||
* freearg = false;
|
||||
return NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO, throw an error here
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return cvarr;
|
||||
}
|
||||
|
||||
|
||||
static int PyObject_GetElemType(PyObject * obj){
|
||||
void *vptr;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint, 0) != -1) return CV_32SC2;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvSize, 0) != -1) return CV_32SC2;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvRect, 0) != -1) return CV_32SC4;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvSize2D32f, 0) != -1) return CV_32FC2;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint2D32f, 0) != -1) return CV_32FC2;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint3D32f, 0) != -1) return CV_32FC3;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint2D64f, 0) != -1) return CV_64FC2;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvPoint3D64f, 0) != -1) return CV_64FC3;
|
||||
if(SWIG_ConvertPtr(obj, &vptr, SWIGTYPE_p_CvScalar, 0) != -1) return CV_64FC4;
|
||||
if(PyTuple_Check(obj) || PyList_Check(obj)) return CV_MAKE_TYPE(CV_32F, PySequence_Size( obj ));
|
||||
if(PyLong_Check(obj)) return CV_32S;
|
||||
return CV_32F;
|
||||
}
|
||||
|
||||
%}
|
1478
interfaces/swig/python/pytypemaps.i
Normal file
1478
interfaces/swig/python/pytypemaps.i
Normal file
File diff suppressed because it is too large
Load Diff
120
interfaces/swig/python/setup-for-win.py
Normal file
120
interfaces/swig/python/setup-for-win.py
Normal file
@@ -0,0 +1,120 @@
|
||||
from distutils.core import setup, Extension
|
||||
import os
|
||||
opencv_pwrap_dir = r'.'
|
||||
opencv_base_dir = r'../../..'
|
||||
|
||||
def patch_for_win32(filename,outfile,patches,extra_defs):
|
||||
print 'patching '+filename+'...'
|
||||
src = open(filename,'rt')
|
||||
dst = open(outfile, 'wt')
|
||||
for l in src.xreadlines():
|
||||
dl = l
|
||||
for (from_str,to_str) in patches:
|
||||
dl = dl.replace(from_str,to_str)
|
||||
for i in extra_defs:
|
||||
if l.find(i[0]) >= 0:
|
||||
dst.write(i[1])
|
||||
extra_defs.remove(i)
|
||||
dst.write(dl)
|
||||
src.close()
|
||||
dst.close()
|
||||
|
||||
def is_older(a,b):
|
||||
return os.path.getmtime(a)<os.path.getmtime(b)
|
||||
|
||||
if not os.path.exists('_cv_win32.cpp') or is_older('_cv_win32.cpp','_cv.cpp'):
|
||||
patch_for_win32('_cv.cpp', '_cv_win32.cpp',
|
||||
[('unsigned long long','uint64',),('long long','int64'),
|
||||
("char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);",
|
||||
"char *doc = (char*)(((PyCFunctionObject *)obj) -> m_ml -> ml_doc);"),
|
||||
("char *c = methods[i].ml_doc;",
|
||||
"char *c = (char*)methods[i].ml_doc;")],
|
||||
[('PyAPI_FUNC','#undef PyAPI_FUNC\n'), ('cv.h',
|
||||
"""
|
||||
#include "cv.h"
|
||||
|
||||
const signed char icvDepthToType[]=
|
||||
{
|
||||
-1, -1, CV_8U, CV_8S, CV_16U, CV_16S, -1, -1,
|
||||
CV_32F, CV_32S, -1, -1, -1, -1, -1, -1, CV_64F, -1
|
||||
};
|
||||
|
||||
CvModuleInfo* CvModule::first = 0;
|
||||
CvModuleInfo* CvModule::last = 0;
|
||||
CvTypeInfo* CvType::first = 0;
|
||||
CvTypeInfo* CvType::last = 0;
|
||||
|
||||
""")])
|
||||
|
||||
if not os.path.exists('_highgui_win32.cpp') or is_older('_highgui_win32.cpp','_highgui.cpp'):
|
||||
patch_for_win32('_highgui.cpp', '_highgui_win32.cpp',
|
||||
[('unsigned long long','uint64',),('long long','int64'),
|
||||
("char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);",
|
||||
"char *doc = (char*)(((PyCFunctionObject *)obj) -> m_ml -> ml_doc);"),
|
||||
("char *c = methods[i].ml_doc;",
|
||||
"char *c = (char*)methods[i].ml_doc;")],
|
||||
[('PyAPI_FUNC','#undef PyAPI_FUNC\n')])
|
||||
|
||||
if not os.path.exists('_ml_win32.cpp') or is_older('_ml_win32.cpp','_ml.cpp'):
|
||||
patch_for_win32('_ml.cpp', '_ml_win32.cpp',
|
||||
[('unsigned long long','uint64',),('long long','int64'),
|
||||
("char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);",
|
||||
"char *doc = (char*)(((PyCFunctionObject *)obj) -> m_ml -> ml_doc);"),
|
||||
("char *c = methods[i].ml_doc;",
|
||||
"char *c = (char*)methods[i].ml_doc;")],
|
||||
[('PyAPI_FUNC','#undef PyAPI_FUNC\n')])
|
||||
|
||||
|
||||
setup(name='OpenCV Python Wrapper',
|
||||
version='0.0',
|
||||
packages = ['opencv'],
|
||||
package_dir = {'opencv': opencv_pwrap_dir},
|
||||
ext_modules=[Extension('opencv._cv',
|
||||
[os.path.join (opencv_pwrap_dir, '_cv_win32.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'error.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'cvshadow.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'pyhelpers.cpp')],
|
||||
include_dirs = [os.path.join (opencv_base_dir,
|
||||
'cv', 'include'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'cxcore', 'include'),
|
||||
],
|
||||
library_dirs = [os.path.join (opencv_base_dir,
|
||||
'lib')],
|
||||
libraries = ['cv', 'cxcore'],
|
||||
),
|
||||
|
||||
Extension('opencv._ml',
|
||||
[os.path.join (opencv_pwrap_dir, '_ml_win32.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'error.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'cvshadow.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'pyhelpers.cpp')],
|
||||
include_dirs = [os.path.join (opencv_base_dir,
|
||||
'cv', 'include'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'cxcore', 'include'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'ml', 'include'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'otherlibs', 'highgui'),
|
||||
],
|
||||
library_dirs = [os.path.join (opencv_base_dir,
|
||||
'lib')],
|
||||
libraries = ['cv', 'cxcore', 'ml'],
|
||||
),
|
||||
|
||||
Extension('opencv._highgui',
|
||||
[os.path.join (opencv_pwrap_dir, '_highgui_win32.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'error.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'cvshadow.cpp'),
|
||||
os.path.join (opencv_pwrap_dir, 'pyhelpers.cpp')],
|
||||
include_dirs = [os.path.join (opencv_base_dir,
|
||||
'otherlibs', 'highgui'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'cxcore', 'include'),
|
||||
os.path.join (opencv_base_dir,
|
||||
'cv', 'include')],
|
||||
library_dirs = [os.path.join (opencv_base_dir,
|
||||
'lib')],
|
||||
libraries = ['highgui', 'cv', 'cxcore'],
|
||||
)
|
Reference in New Issue
Block a user