Remove OpenCV wrappers for 0.4 release.

This commit is contained in:
Stefan van der Walt
2011-10-11 19:38:15 -07:00
parent 38e50ba498
commit 677c768bb1
14 changed files with 0 additions and 4225 deletions
-6
View File
@@ -29,12 +29,6 @@ Optional Requirements
You can use this scikit with the basic requirements listed above, but some
functionality is only available with the following installed:
`Open CV <http://opencv.willowgarage.com/wiki/>`_ (version 2.1).
Required for functions in ``scikits.image.opencv``.
Note that, under Ubuntu, due to problems with Atlas + OpenCV,
you may have to rebuild your own libcv.
`PyQt4 <http://wiki.python.org/moin/PyQt>`_
The `qt` plugin that provides `imshow` and `scivi`.
-23
View File
@@ -1,23 +0,0 @@
You can use the setup.py in this directory to build ONLY the OpenCV stuff.
It is recommend that you use the main setup.py for the entire scikit.
To install globally::
python setup.py install
To install locally::
python setup.py install --prefix=${HOME}
# Remember to add /home/user/lib/python2.x/lib/site-packages
# to your PYTHONPATH
To compile in-place::
python setup.py build_ext -i
-28
View File
@@ -1,28 +0,0 @@
Copyright (C) 2009 Steven C. Colbert <sccolbert@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions 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.
3. Neither the name of scikits.image nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
-38
View File
@@ -1,38 +0,0 @@
from opencv_constants import *
from .. import get_log as _get_log
_log = _get_log("scikits.image.opencv")
_log.warn("""
The scikits.image OpenCV wrappers will be removed in the next release.
These wrappers were written before OpenCV's own allowed manipulation
of NumPy arrays without copying. Since they now do, please switch to
the official bindings::
http://opencv.willowgarage.com/wiki/""")
# Note: users should be able to import this module even if
# the extensions are uncompiled or the opencv libraries unavailable.
# In that case, the opencv functionality is simply unavailable.
loaded = False
try:
from opencv_cv import *
except ImportError:
print """*** The opencv extension was not compiled. Run
python setup.py build_ext -i
in the source directory to build in-place. Please refer to INSTALL.txt
for further detail."""
except RuntimeError:
# Libraries could not be loaded
print "*** Skipping import of OpenCV functions."
del (opencv_backend, opencv_cv)
else:
loaded = True
del opencv_constants
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env python
# encoding: utf-8
"""
This file properly imports the open CV libraries and returns them
as an object. This function goes a longer way to try to find them
since especially on MacOS X Library Paths are not clearly defined.
This module also removes the code duplication in __init__ and
opencv_cv
"""
__all__ = ["cv", "cxcore"]
import ctypes
import sys
import os.path
import warnings
def _import_opencv_lib(which="cv"):
"""
Try to import a shared library of OpenCV.
which - Which library ["cv", "cxcore", "highgui"]
"""
library_paths = ['',
'/lib/',
'/usr/lib/',
'/usr/local/lib/',
'/opt/local/lib/', # MacPorts
'/sw/lib/', # Fink
]
if sys.platform.startswith('linux'):
extensions = ['.so', '.so.2.1', '.so.1']
elif sys.platform.startswith("darwin"):
extensions = ['.dylib']
else:
extensions = ['.dll']
library_paths = []
lib = 'lib' + which
shared_lib = None
for path in library_paths:
for ext in extensions:
try:
shared_lib = ctypes.CDLL(os.path.join(path, lib + ext))
except OSError:
pass
else:
return shared_lib
warnings.warn(RuntimeWarning(
'The opencv libraries were not found. Please ensure that they '
'are installed and available on the system path. '))
cv = _import_opencv_lib("cv")
cxcore = _import_opencv_lib("cxcore")
-56
View File
@@ -1,56 +0,0 @@
from textwrap import dedent
import numpy as np
# some utility functions for the opencv wrappers
# the doc decorator
class cvdoc(object):
'''A doc decorator which adds the docs for the opencv functions.
It primarily serves to append the appropriate opencv doc url to
each function.
'''
base_url = 'http://opencv.willowgarage.com/documentation/'
branch_urls = {'cv':
{'filter': 'image_filtering',
'feature': 'feature_detection',
'geometry': 'geometric_image_transformations',
'transforms': 'miscellaneous_image_transformations',
'structural': 'structural_analysis',
'calibration': 'camera_calibration_and_3d_reconstruction'
},
'cxcore': {},
'highgui': {}
}
def __init__(self, package='', group='', doc=''):
self.package = str(package)
self.group = str(group)
self.doc = str(doc)
def __call__(self, func):
# if key errors occur, fail silently
try:
self._add_url(func)
np.add_docstring(func, self.doc)
return func
except KeyError:
return func
def _add_url(self, func):
# Remove cv prefix from name
name = func.__name__.lower()[2:]
full_url = (self.base_url +
self.branch_urls[self.package][self.group] +
'.html' + '#' + name)
message = dedent('''
References
----------
.. [1] OpenCV documentation for `%(name)s`, %(url)s.
''' % {'name': name,
'url': full_url})
self.doc += '\n\n' + message
-53
View File
@@ -1,53 +0,0 @@
import numpy as np
cimport numpy as np
from opencv_type cimport *
cdef extern from "Python.h":
void Py_INCREF(object)
cdef extern from "numpy/arrayobject.h":
object PyArray_Empty(int, np.npy_intp*, dtype, int)
bint PyArray_ISCONTIGUOUS(np.ndarray)
ctypedef np.uint8_t UINT8_t
ctypedef np.int8_t INT8_t
ctypedef np.int16_t INT16_t
ctypedef np.int32_t INT32_t
ctypedef np.float32_t FLOAT32_t
ctypedef np.float64_t FLOAT64_t
#-------------------------------------------------------------------------------
# Utility functions for IplImage creation, array validation, etc...
#-------------------------------------------------------------------------------
cdef void populate_iplimage(np.ndarray arr, IplImage* img)
cdef CvMat* cvmat_ptr_from_iplimage(IplImage* arr)
cdef int validate_array(np.ndarray arr) except -1
cdef int assert_dtype(np.ndarray arr, dtypes) except -1
cdef int assert_ndims(np.ndarray arr, dims) except -1
cdef int assert_nchannels(np.ndarray arr, channels) except -1
cdef int assert_same_dtype(np.ndarray arr1, np.ndarray arr2) except -1
cdef int assert_same_shape(np.ndarray arr1, np.ndarray arr2) except -1
cdef int assert_same_width_and_height(np.ndarray arr1, np.ndarray arr2) except -1
cdef int assert_like(np.ndarray arr1, np.ndarray arr2) except -1
cdef int assert_not_sharing_data(np.ndarray arr1, np.ndarray arr2) except -1
#-------------------------------------------------------------------------------
# NumPy convienences
#-------------------------------------------------------------------------------
cdef np.ndarray new_array(int ndim, np.npy_intp* shape, dtype)
cdef np.ndarray new_array_like(np.ndarray arr)
cdef np.ndarray new_array_like_diff_dtype(np.ndarray arr, dtype)
cdef np.npy_intp get_array_nbytes(np.ndarray arr)
cdef np.npy_intp* clone_array_shape(np.ndarray arr)
#-------------------------------------------------------------------------------
# OpenCV convienences
#-------------------------------------------------------------------------------
cdef CvPoint2D32f* array_as_cvPoint2D32f_ptr(np.ndarray arr)
cdef CvTermCriteria get_cvTermCriteria(int, double)
cdef IplConvKernel* get_IplConvKernel_ptr_from_array(np.ndarray arr, anchor) except NULL
cdef void free_IplConvKernel(IplConvKernel* iplkernel)
#-------------------------------------------------------------------------------
# Other convienences
#-------------------------------------------------------------------------------
-298
View File
@@ -1,298 +0,0 @@
import ctypes
import numpy as np
cimport numpy as np
from cpython cimport *
from opencv_constants import *
from opencv_type cimport *
from _libimport import cv, cxcore
if cv is None:
raise RuntimeError("Could not load libcv")
if cxcore is None:
raise RuntimeError("Could not load libcxcore")
# setup numpy tables for this module
np.import_array()
#-----------------------------------------------------------------------------
# Data Type Handling
#-----------------------------------------------------------------------------
# for some reason these have to declared as dtype objects rather than just the
# dtype itself....
UINT8 = np.dtype('uint8')
INT8 = np.dtype('int8')
UINT16 = np.dtype('uint16')
INT16 = np.dtype('int16')
INT32 = np.dtype('int32')
FLOAT32 = np.dtype('float32')
FLOAT64 = np.dtype('float64')
cdef int IPL_DEPTH_SIGN = 0x80000000
cdef int IPL_DEPTH_8U = 8
cdef int IPL_DEPTH_8S = (IPL_DEPTH_SIGN | 8)
cdef int IPL_DEPTH_16U = 16
cdef int IPL_DEPTH_16S = (IPL_DEPTH_SIGN | 16)
cdef int IPL_DEPTH_32S = (IPL_DEPTH_SIGN | 32)
cdef int IPL_DEPTH_32F = 32
cdef int IPL_DEPTH_64F = 64
# I'd like a better to associate the IPL data type flag to the proper numpy
# types without using a dictionary.
_ipltypes = {UINT8: IPL_DEPTH_8U, INT8: IPL_DEPTH_8S, UINT16: IPL_DEPTH_16U,
INT16: IPL_DEPTH_16S, INT32: IPL_DEPTH_32S, FLOAT32: IPL_DEPTH_32F,
FLOAT64: IPL_DEPTH_64F}
#-----------------------------------------------------------------------------
# Utility functions for IplImage creation, array validation, etc...
#-----------------------------------------------------------------------------
cdef int IPLIMAGE_SIZE = sizeof(IplImage)
# a function to convert from IplImage to cvMat
# this eliminates the need for a second populate function
# for CvMat
ctypedef CvMat* (*cvGetMatPtr)(IplImage*, CvMat*, int*, int)
cdef cvGetMatPtr c_cvGetMat
c_cvGetMat = (<cvGetMatPtr*><size_t>ctypes.addressof(cxcore.cvGetMat))[0]
cdef void populate_iplimage(np.ndarray arr, IplImage* img):
# The numpy array should be validated with the validate_array
# function before using this function.
# This function assumes that the array has successfully passed
# validation
# everything that will never change
img.nSize = IPLIMAGE_SIZE
img.ID = 0
img.dataOrder = 0
img.origin = 0
img.roi = NULL
img.maskROI = NULL
img.imageId = NULL
img.tileInfo = NULL
cdef int ndim = arr.ndim
cdef np.npy_intp* shape = arr.shape
cdef np.npy_intp* strides = arr.strides
# nChannels is essentially the value of np.shape[2] of a 3D numpy array
# for a 2D array, nChannels is 1
if ndim == 1:
# Might happen for a 1D vector
img.nChannels = 1
img.width = 1
else:
if ndim == 2:
img.nChannels = 1
else:
img.nChannels = shape[2]
img.width = shape[1]
img.height = shape[0]
img.widthStep = strides[0]
img.depth = _ipltypes[arr.dtype]
img.imageSize = arr.nbytes
img.imageData = <char*>arr.data
# really doesn't matter what this is set to, because opencv only uses it to
# deallocate images, but it will never attempt to deallocate images we
# create ourselves.
img.imageDataOrigin = <char*>NULL
cdef CvMat* cvmat_ptr_from_iplimage(IplImage* arr):
# this functions takes an IplImage* and returns a CvMat*
# it is designed so that we dont need a separate populate_cvmat
# function, or deal with OpenCV magic values. However, it needs to create a
# CvMat header to pass to the opencv conversion routine.
# This means that you have to call PyMem_Free on the CvMat* when you're
# done with it.
cdef CvMat* mat_hdr = <CvMat*>PyMem_Malloc(sizeof(CvMat))
mat_hdr = c_cvGetMat(arr, mat_hdr, NULL, 0)
return mat_hdr
cdef int validate_array(np.ndarray arr) except -1:
# this assertion prevents the use of slices, so
# we need to be more creative about how to deal
# with non-contiguous arrays
#assert PyArray_ISCONTIGUOUS(arr), 'Array must be contiguous'
if arr.ndim != 2 and arr.ndim != 3:
raise ValueError('Arrays must have either 2 or 3 dimensions')
if arr.ndim == 3:
if arr.shape[2] > 4:
raise ValueError('A 3D array must have 4 or less channels')
if arr.dtype not in _ipltypes:
raise ValueError('Arrays must have one of the following dtypes: '
'uint8, int8, int16, int32, float32, float64')
return 1
cdef int assert_dtype(np.ndarray arr, dtypes) except -1:
if arr.dtype not in dtypes:
raise ValueError('Unsupported dtype for this operation. \
Supported dtypes are %s' % str(dtypes))
return 1
cdef int assert_ndims(np.ndarray arr, dims) except -1:
if arr.ndim not in dims:
raise ValueError('Incorrect number of dimensions')
return 1
cdef int assert_nchannels(np.ndarray arr, channels) except -1:
cdef int nchannels
if arr.ndim == 2:
nchannels = 1
else:
nchannels = arr.shape[2]
if nchannels not in channels:
raise ValueError('Incorrect number of channels')
return 1
cdef int assert_same_dtype(np.ndarray arr1, np.ndarray arr2) except -1:
if arr1.dtype != arr2.dtype:
raise ValueError('dtypes not same')
return 1
cdef int assert_same_shape(np.ndarray arr1, np.ndarray arr2) except -1:
if not np.PyArray_SAMESHAPE(arr1, arr2):
raise ValueError('arrays not same shape')
return 1
cdef int assert_same_width_and_height(np.ndarray arr1, np.ndarray arr2) \
except -1:
cdef np.npy_intp* shape1 = arr1.shape
cdef np.npy_intp* shape2 = arr2.shape
if (shape1[0] != shape2[0]) or (shape1[1] != shape2[1]):
raise ValueError('Arrays must have same width and height')
return 1
cdef int assert_like(np.ndarray arr1, np.ndarray arr2) except -1:
assert_same_dtype(arr1, arr2)
assert_same_shape(arr1, arr2)
return 1
cdef int assert_not_sharing_data(np.ndarray arr1, np.ndarray arr2) except -1:
if arr1.data == arr2.data:
raise ValueError('In place operation not supported. Make sure \
the out array is not just a view of src array')
return 1
#-----------------------------------------------------------------------------
# NumPy array convienences
#-----------------------------------------------------------------------------
cdef np.ndarray new_array(int ndim, np.npy_intp* shape, dtype):
# need to incref because numpy will apprently steal a dtype reference
Py_INCREF(<object>dtype)
return PyArray_Empty(ndim, shape, dtype, 0)
cdef np.ndarray new_array_like(np.ndarray arr):
# need to incref because numpy will apprently steal a dtype reference
Py_INCREF(<object>arr.dtype)
return PyArray_Empty(arr.ndim, arr.shape, arr.dtype, 0)
cdef np.ndarray new_array_like_diff_dtype(np.ndarray arr, dtype):
# need to incref because numpy will apprently steal a dtype reference
Py_INCREF(<object>dtype)
return PyArray_Empty(arr.ndim, arr.shape, dtype, 0)
cdef np.npy_intp* clone_array_shape(np.ndarray arr):
# make sure you call PyMem_Free after you're done with the shape
cdef int ndim = arr.ndim
cdef np.npy_intp* shape = <np.npy_intp*>PyMem_Malloc(
ndim * sizeof(np.npy_intp))
cdef int i
for i in range(ndim):
shape[i] = arr.shape[i]
return shape
cdef np.npy_intp get_array_nbytes(np.ndarray arr):
cdef np.npy_intp nbytes = np.PyArray_NBYTES(arr)
return nbytes
#-------------------------------------------------------------------------------
# OpenCV convienences
#-------------------------------------------------------------------------------
cdef CvPoint2D32f* array_as_cvPoint2D32f_ptr(np.ndarray arr):
cdef CvPoint2D32f* point2Darr
point2Darr = <CvPoint2D32f*>arr.data
return point2Darr
cdef CvTermCriteria get_cvTermCriteria(int iterations, double epsilon):
cdef CvTermCriteria crit
if iterations and epsilon:
crit.type = <int>(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS)
crit.max_iter = iterations
crit.epsilon = epsilon
elif iterations and not epsilon:
crit.type = <int>CV_TERMCRIT_ITER
crit.max_iter = iterations
crit.epsilon = 0.
else:
crit.type = <int>CV_TERMCRIT_EPS
crit.max_iter = 0
crit.epsilon = epsilon
return crit
ctypedef IplConvKernel* (*cvCreateStructuringElementExPtr)(int, int, int, int,
int, int*)
cdef cvCreateStructuringElementExPtr c_cvCreateStructuringElementEx
c_cvCreateStructuringElementEx = (<cvCreateStructuringElementExPtr*><size_t>
ctypes.addressof(cv.cvCreateStructuringElementEx))[0]
ctypedef void (*cvReleaseStructuringElementPtr)(IplConvKernel**)
cdef cvReleaseStructuringElementPtr c_cvReleaseStructuringElement
c_cvReleaseStructuringElement = (<cvReleaseStructuringElementPtr*><size_t>
ctypes.addressof(cv.cvReleaseStructuringElement))[0]
cdef IplConvKernel* get_IplConvKernel_ptr_from_array(np.ndarray arr, anchor) \
except NULL:
# make sure you call free_IplConvKernel you're done with the kernel
validate_array(arr)
assert_ndims(arr, [2])
assert_dtype(arr, [INT32])
cdef int rows
cdef int cols
cdef int anchorx
cdef int anchory
if anchor is not None:
assert len(anchor) == 2, 'anchor must be (x, y) tuple'
anchorx = <int>anchor[0]
anchory = <int>anchor[1]
assert (anchorx < arr.shape[1]) and (anchorx >= 0) \
and (anchory < arr.shape[0]) and (anchory >= 0), \
'anchor point must be inside kernel'
else:
anchorx = <int>(arr.shape[1] / 2.)
anchory = <int>(arr.shape[0] / 2.)
rows = arr.shape[0]
cols = arr.shape[1]
cdef int* values = <int*>arr.data
# this function copies the data from the array into (i'm guessing)
# aligned memory. Since this is using opencv memory management
# the free_IplConvKernel function makes the appropriate calls to free it
cdef IplConvKernel* iplkernel = \
c_cvCreateStructuringElementEx(cols, rows, anchorx, anchory,
CV_SHAPE_CUSTOM, values)
return iplkernel
cdef void free_IplConvKernel(IplConvKernel* iplkernel):
c_cvReleaseStructuringElement(&iplkernel)
#-------------------------------------------------------------------------------
# Other convienences
#-------------------------------------------------------------------------------
-223
View File
@@ -1,223 +0,0 @@
#############################################
# Image Processing Constants
############################################
CV_BLUR_NO_SCALE = 0
CV_BLUR = 1
CV_GAUSSIAN = 2
CV_MEDIAN = 3
CV_BILATERAL = 4
CV_TERMCRIT_NUMBER = 1
CV_TERMCRIT_ITER = 1
CV_TERMCRIT_EPS = 2
CV_INTER_NN = 0
CV_INTER_LINEAR = 1
CV_INTER_CUBIC = 2
CV_INTER_AREA = 3
CV_WARP_FILL_OUTLIERS = 8
CV_WARP_INVERSE_MAP = 16
CV_SHAPE_RECT = 0
CV_SHAPE_CROSS = 1
CV_SHAPE_ELLIPSE = 2
CV_SHAPE_CUSTOM = 100
CV_THRESH_BINARY = 0
CV_THRESH_BINARY_INV = 1
CV_THRESH_TRUNC = 2
CV_THRESH_TOZERO = 3
CV_THRESH_TOZERO_INV = 4
CV_THRESH_MASK = 7
CV_ADAPTIVE_THRESH_MEAN_C = 0
CV_ADAPTIVE_THRESH_GAUSSIAN_C = 1
CV_MOP_OPEN = 2
CV_MOP_CLOSE = 3
CV_MOP_GRADIENT = 4
CV_MOP_TOPHAT = 5
CV_MOP_BLACKHAT = 6
#-------------------------------------------------------------------------------
# Color Conversion
#-------------------------------------------------------------------------------
CV_BGR2BGRA = 0
CV_RGB2RGBA = CV_BGR2BGRA
CV_BGRA2BGR = 1
CV_RGBA2RGB = CV_BGRA2BGR
CV_BGR2RGBA = 2
CV_RGB2BGRA = CV_BGR2RGBA
CV_RGBA2BGR = 3
CV_BGRA2RGB = CV_RGBA2BGR
CV_BGR2RGB = 4
CV_RGB2BGR = CV_BGR2RGB
CV_BGRA2RGBA = 5
CV_RGBA2BGRA = CV_BGRA2RGBA
CV_BGR2GRAY = 6
CV_RGB2GRAY = 7
CV_GRAY2BGR = 8
CV_GRAY2RGB = CV_GRAY2BGR
CV_GRAY2BGRA = 9
CV_GRAY2RGBA = CV_GRAY2BGRA
CV_BGRA2GRAY = 10
CV_RGBA2GRAY = 11
CV_BGR2BGR565 = 12
CV_RGB2BGR565 = 13
CV_BGR5652BGR = 14
CV_BGR5652RGB = 15
CV_BGRA2BGR565 = 16
CV_RGBA2BGR565 = 17
CV_BGR5652BGRA = 18
CV_BGR5652RGBA = 19
CV_GRAY2BGR565 = 20
CV_BGR5652GRAY = 21
CV_BGR2BGR555 = 22
CV_RGB2BGR555 = 23
CV_BGR5552BGR = 24
CV_BGR5552RGB = 25
CV_BGRA2BGR555 = 26
CV_RGBA2BGR555 = 27
CV_BGR5552BGRA = 28
CV_BGR5552RGBA = 29
CV_GRAY2BGR555 = 30
CV_BGR5552GRAY = 31
CV_BGR2XYZ = 32
CV_RGB2XYZ = 33
CV_XYZ2BGR = 34
CV_XYZ2RGB = 35
CV_BGR2YCrCb = 36
CV_RGB2YCrCb = 37
CV_YCrCb2BGR = 38
CV_YCrCb2RGB = 39
CV_BGR2HSV = 40
CV_RGB2HSV = 41
CV_BGR2Lab = 44
CV_RGB2Lab = 45
CV_BayerBG2BGR = 46
CV_BayerGB2BGR = 47
CV_BayerRG2BGR = 48
CV_BayerGR2BGR = 49
CV_BayerBG2RGB = CV_BayerRG2BGR
CV_BayerGB2RGB = CV_BayerGR2BGR
CV_BayerRG2RGB = CV_BayerBG2BGR
CV_BayerGR2RGB = CV_BayerGB2BGR
CV_BGR2Luv = 50
CV_RGB2Luv = 51
CV_BGR2HLS = 52
CV_RGB2HLS = 53
CV_HSV2BGR = 54
CV_HSV2RGB = 55
CV_Lab2BGR = 56
CV_Lab2RGB = 57
CV_Luv2BGR = 58
CV_Luv2RGB = 59
CV_HLS2BGR = 60
CV_HLS2RGB = 61
#########################
# Calibration Constants #
#########################
CV_CALIB_USE_INTRINSIC_GUESS = 1
CV_CALIB_FIX_ASPECT_RATIO = 2
CV_CALIB_FIX_PRINCIPAL_POINT = 4
CV_CALIB_ZERO_TANGENT_DIST = 8
CV_CALIB_CB_ADAPTIVE_THRESH = 1
CV_CALIB_CB_NORMALIZE_IMAGE = 2
CV_CALIB_CB_FILTER_QUADS = 4
################################
# Fundamental Matrix Constants #
################################
CV_FM_7POINT = 1
CV_FM_8POINT = 2
CV_FM_LMEDS = 4
CV_FM_RANSAC = 8
####################
# cvMat TypeValues #
####################
CV_CN_MAX = 4
CV_CN_SHIFT = 3
CV_DEPTH_MAX = (1 << CV_CN_SHIFT)
CV_8U = 0
CV_8S = 1
CV_16U = 2
CV_16S = 3
CV_32S = 4
CV_32F = 5
CV_64F = 6
CV_USRTYPE1 = 7
def _CV_MAKETYPE(depth,cn):
return ((depth) + (((cn)-1) << CV_CN_SHIFT))
CV_8UC1 = _CV_MAKETYPE(CV_8U,1)
CV_8UC2 = _CV_MAKETYPE(CV_8U,2)
CV_8UC3 = _CV_MAKETYPE(CV_8U,3)
CV_8UC4 = _CV_MAKETYPE(CV_8U,4)
CV_8SC1 = _CV_MAKETYPE(CV_8S,1)
CV_8SC2 = _CV_MAKETYPE(CV_8S,2)
CV_8SC3 = _CV_MAKETYPE(CV_8S,3)
CV_8SC4 = _CV_MAKETYPE(CV_8S,4)
CV_16UC1 = _CV_MAKETYPE(CV_16U,1)
CV_16UC2 = _CV_MAKETYPE(CV_16U,2)
CV_16UC3 = _CV_MAKETYPE(CV_16U,3)
CV_16UC4 = _CV_MAKETYPE(CV_16U,4)
CV_16SC1 = _CV_MAKETYPE(CV_16S,1)
CV_16SC2 = _CV_MAKETYPE(CV_16S,2)
CV_16SC3 = _CV_MAKETYPE(CV_16S,3)
CV_16SC4 = _CV_MAKETYPE(CV_16S,4)
CV_32SC1 = _CV_MAKETYPE(CV_32S,1)
CV_32SC2 = _CV_MAKETYPE(CV_32S,2)
CV_32SC3 = _CV_MAKETYPE(CV_32S,3)
CV_32SC4 = _CV_MAKETYPE(CV_32S,4)
CV_32FC1 = _CV_MAKETYPE(CV_32F,1)
CV_32FC2 = _CV_MAKETYPE(CV_32F,2)
CV_32FC3 = _CV_MAKETYPE(CV_32F,3)
CV_32FC4 = _CV_MAKETYPE(CV_32F,4)
CV_64FC1 = _CV_MAKETYPE(CV_64F,1)
CV_64FC2 = _CV_MAKETYPE(CV_64F,2)
CV_64FC3 = _CV_MAKETYPE(CV_64F,3)
CV_64FC4 = _CV_MAKETYPE(CV_64F,4)
#-------------------------------------------------------------------------------
# Template Matching
#-------------------------------------------------------------------------------
CV_TM_SQDIFF = 0
CV_TM_SQDIFF_NORMED = 1
CV_TM_CCORR = 2
CV_TM_CCORR_NORMED = 3
CV_TM_CCOEFF = 4
CV_TM_CCOEFF_NORMED = 5
File diff suppressed because it is too large Load Diff
-82
View File
@@ -1,82 +0,0 @@
# a reimplementation of the opencv types.
# so we dont have to worry about having the opencv headers
# available at build time.
cdef struct _IplImage:
int nSize # sizeof(_IplImage)
int ID # must be 0
int nChannels # number of channels 1, 2, 3 or 4
int alphaChannel # ignored by opencv
int depth # pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F
char colorModel[4] # ignored by opencv
char channelSeq[4] # ignored by opencv
int dataOrder # must be 0
int origin # should be 0 for top-left origin
int align # ignored by opencv
int width # width in pixels
int height # height in pixels
void *roi # must be NULL
void *maskROI # must be NULL
void *imageId # must be NULL
void *tileInfo # must be NULL
int imageSize # image size in bytes
char *imageData # pointer to the data
int widthStep # row size in bytes (first stride of numpy array)
int BorderMode[4] # ignored by opencv
int BorderConst[4] # ignored by opencv
char* imageDataOrigin # pointer to origin of data. Used for deallocation, but python will handle this so we'll set it to void*
ctypedef _IplImage IplImage
# you will never directly populate a CvMat.
cdef union CvMat_uProxy:
unsigned char* ptr
short* s
int* i
float* fl
double* db
cdef struct CvMat:
int type
int step
int* refcount
int hdr_refcount
CvMat_uProxy data
int rows
int cols
cdef struct CvPoint:
int x
int y
cdef struct CvPoint2D32f:
float x
float y
cdef struct CvSize:
int width
int height
cdef struct CvTermCriteria:
int type
int max_iter
double epsilon
cdef struct CvScalar:
double val[4]
cdef struct _IplConvKernel:
int nCols
int nRows
int anchorX
int anchorY
int *values
int nShiftR
ctypedef _IplConvKernel IplConvKernel
-39
View File
@@ -1,39 +0,0 @@
#!/usr/bin/env python
from scikits.image._build import cython
import os.path
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('opencv', parent_package, top_path)
config.add_data_dir('tests')
cython_files = ['opencv_backend.pyx', 'opencv_cv.pyx']
# This function tries to create C files from the given .pyx files. If
# it fails, we build the checked-in .c files.
cython(cython_files, working_path=base_path)
for pyxfile in cython_files:
c_file = pyxfile[:-4] + '.c'
config.add_extension(pyxfile[:-4],
sources=[c_file],
include_dirs=[get_numpy_include_dirs()])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer = 'Scikits.Image Developers',
author = 'Steven C. Colbert',
maintainer_email = 'scikits-image@googlegroups.com',
description = 'OpenCV wrapper for NumPy arrays',
url = 'https://github.com/scikits-image/scikits.image',
license = 'SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
@@ -1,411 +0,0 @@
# test for the opencv_cv extension module
from __future__ import with_statement
import os
import sys
import warnings
import numpy as np
from numpy.testing import *
from scikits.image import data_dir
if sys.version_info[0] < 3:
import cPickle
else:
import pickle as cPickle
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from scikits.image.opencv import *
opencv_skip = dec.skipif(not loaded, 'OpenCV libraries not found')
class OpenCVTest(object):
lena_RGB_U8 = np.load(os.path.join(data_dir, 'lena_RGB_U8.npz'))['arr_0']
lena_GRAY_U8 = np.load(os.path.join(data_dir, 'lena_GRAY_U8.npz'))['arr_0']
class TestSobel(OpenCVTest):
@opencv_skip
def test_cvSobel(self):
cvSobel(self.lena_GRAY_U8)
class TestLaplace(OpenCVTest):
@opencv_skip
def test_cvLaplace(self):
cvLaplace(self.lena_GRAY_U8)
class TestCanny(OpenCVTest):
@opencv_skip
def test_cvCanny(self):
cvCanny(self.lena_GRAY_U8)
class TestPreCornerDetect(OpenCVTest):
@opencv_skip
def test_cvPreCornerDetect(self):
cvPreCornerDetect(self.lena_GRAY_U8)
class TestCornerEigenValsAndVecs(OpenCVTest):
@opencv_skip
def test_cvCornerEigenValsAndVecs(self):
cvCornerEigenValsAndVecs(self.lena_GRAY_U8)
class TestCornerMinEigenVal(OpenCVTest):
@opencv_skip
def test_cvCornerMinEigenVal(self):
cvCornerMinEigenVal(self.lena_GRAY_U8)
class TestCornerHarris(OpenCVTest):
@opencv_skip
def test_cvCornerHarris(self):
cvCornerHarris(self.lena_GRAY_U8)
class TestFindCornerSubPix(object):
@opencv_skip
def test_cvFindCornersSubPix(self):
img = np.array([[1, 1, 1, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 1, 1]], dtype='uint8')
corners = np.array([[2, 2],
[2, 5],
[5, 2],
[5, 5]], dtype='float32')
cvFindCornerSubPix(img, corners, (2, 2))
class TestGoodFeaturesToTrack(OpenCVTest):
@opencv_skip
def test_cvGoodFeaturesToTrack(self):
cvGoodFeaturesToTrack(self.lena_GRAY_U8, 100, 0.1, 3)
class TestGetRectSubPix(OpenCVTest):
@opencv_skip
def test_cvGetRectSubPix(self):
cvGetRectSubPix(self.lena_RGB_U8, (20, 20), (48.6, 48.6))
class TestGetQuadrangleSubPix(OpenCVTest):
@opencv_skip
def test_cvGetQuadrangleSubPix(self):
warpmat = np.array([[0.5, 0.3, 0.4],
[-.4, .23, 0.4]], dtype='float32')
cvGetQuadrangleSubPix(self.lena_RGB_U8, warpmat)
class TestResize(OpenCVTest):
@opencv_skip
def test_cvResize(self):
cvResize(self.lena_RGB_U8, (50, 50), method=CV_INTER_LINEAR)
cvResize(self.lena_RGB_U8, (200, 200), method=CV_INTER_CUBIC)
class TestWarpAffine(OpenCVTest):
@opencv_skip
def test_cvWarpAffine(self):
warpmat = np.array([[0.5, 0.3, 0.4],
[-.4, .23, 0.4]], dtype='float32')
cvWarpAffine(self.lena_RGB_U8, warpmat)
class TestWarpPerspective(OpenCVTest):
@opencv_skip
def test_cvWarpPerspective(self):
warpmat = np.array([[0.5, 0.3, 0.4],
[-.4, .23, 0.4],
[0.0, 1.0, 1.0]], dtype='float32')
cvWarpPerspective(self.lena_RGB_U8, warpmat)
class TestLogPolar(OpenCVTest):
@opencv_skip
def test_cvLogPolar(self):
img = self.lena_RGB_U8
width = img.shape[1]
height = img.shape[0]
x = width / 2.
y = height / 2.
cvLogPolar(img, (x, y), 20)
class TestErode(OpenCVTest):
@opencv_skip
def test_cvErode(self):
kern = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype='int32')
cvErode(self.lena_RGB_U8, kern, in_place=True)
class TestDilate(OpenCVTest):
@opencv_skip
def test_cvDilate(self):
kern = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype='int32')
cvDilate(self.lena_RGB_U8, kern, in_place=True)
class TestMorphologyEx(OpenCVTest):
@opencv_skip
def test_cvMorphologyEx(self):
kern = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype='int32')
cvMorphologyEx(self.lena_RGB_U8, kern, CV_MOP_TOPHAT, in_place=True)
class TestSmooth(OpenCVTest):
@opencv_skip
def test_cvSmooth(self):
for st in (CV_BLUR_NO_SCALE, CV_BLUR, CV_GAUSSIAN, CV_MEDIAN,
CV_BILATERAL):
cvSmooth(self.lena_GRAY_U8, st, 3, 0, 0, 0, False)
class TestFilter2D(OpenCVTest):
@opencv_skip
def test_cvFilter2D(self):
kern = np.array([[0, 1.5, 0],
[1, 1, 2.6],
[0, .76, 0]], dtype='float32')
cvFilter2D(self.lena_RGB_U8, kern, in_place=True)
class TestIntegral(OpenCVTest):
@opencv_skip
def test_cvIntegral(self):
cvIntegral(self.lena_RGB_U8, True, True)
class TestCvtColor(OpenCVTest):
@opencv_skip
def test_cvCvtColor(self):
cvCvtColor(self.lena_RGB_U8, CV_RGB2BGR)
cvCvtColor(self.lena_RGB_U8, CV_RGB2BGRA)
cvCvtColor(self.lena_RGB_U8, CV_RGB2HSV)
cvCvtColor(self.lena_RGB_U8, CV_RGB2BGR565)
cvCvtColor(self.lena_RGB_U8, CV_RGB2BGR555)
cvCvtColor(self.lena_RGB_U8, CV_RGB2GRAY)
cvCvtColor(self.lena_GRAY_U8, CV_GRAY2BGR)
cvCvtColor(self.lena_GRAY_U8, CV_GRAY2BGR565)
cvCvtColor(self.lena_GRAY_U8, CV_GRAY2BGR555)
class TestThreshold(OpenCVTest):
@opencv_skip
def test_cvThreshold(self):
cvThreshold(self.lena_GRAY_U8, 100, 255, CV_THRESH_BINARY)
cvThreshold(self.lena_GRAY_U8, 100, 255, CV_THRESH_BINARY_INV)
cvThreshold(self.lena_GRAY_U8, 100, threshold_type=CV_THRESH_TRUNC)
cvThreshold(self.lena_GRAY_U8, 100, threshold_type=CV_THRESH_TOZERO)
cvThreshold(self.lena_GRAY_U8, 100, threshold_type=CV_THRESH_TOZERO_INV)
cvThreshold(self.lena_GRAY_U8, 100, 1, CV_THRESH_BINARY, use_otsu=True)
class TestAdaptiveThreshold(OpenCVTest):
@opencv_skip
def test_cvAdaptiveThreshold(self):
cvAdaptiveThreshold(self.lena_GRAY_U8, 100)
class TestPyrDown(OpenCVTest):
@opencv_skip
def test_cvPyrDown(self):
cvPyrDown(self.lena_RGB_U8)
class TestPyrUp(OpenCVTest):
@opencv_skip
def test_cvPyrUp(self):
cvPyrUp(self.lena_RGB_U8)
class TestFindChessboardCorners(object):
@opencv_skip
def test_cvFindChessboardCorners(self):
chessboard_GRAY_U8 = np.load(
os.path.join(data_dir, 'chessboard_GRAY_U8.npz')['arr_0'])
pts = cvFindChessboardCorners(chessboard_GRAY_U8, (7, 7))
class TestDrawChessboardCorners(object):
@opencv_skip
def test_cvDrawChessboardCorners(self):
chessboard_GRAY_U8 = np.load(
os.path.join(data_dir, 'chessboard_GRAY_U8.npz')['arr_0'])
chessboard_RGB_U8 = np.load(
os.path.join(data_dir, 'chessboard_RGB_U8.npz')['arr_0'])
corners = cvFindChessboardCorners(chessboard_GRAY_U8, (7, 7))
cvDrawChessboardCorners(chessboard_RGB_U8, (7, 7), corners)
class TestCalibrateCamera2(object):
@opencv_skip
def test_cvCalibrateCamera2_Identity(self):
ys = xs = range(4)
image_points = np.array( [(4 * x, 4 * y) for x in xs for y in ys ],
dtype=np.float64)
object_points = np.array( [(x, y, 0) for x in xs for y in ys ],
dtype=np.float64)
image_points = np.ascontiguousarray(np.vstack((image_points,) * 3))
object_points = np.ascontiguousarray(np.vstack((object_points,) * 3))
intrinsics, distortions = cvCalibrateCamera2(
object_points, image_points,
np.array([16, 16, 16], dtype=np.int32), (4, 4)
)
assert_almost_equal(distortions, np.array([0., 0., 0., 0., 0.]))
# The intrinsics will be strange, but we can at least check
# for known zeros and ones
assert_almost_equal( intrinsics[0,1], 0)
assert_almost_equal( intrinsics[1,0], 0)
assert_almost_equal( intrinsics[2,0], 0)
assert_almost_equal( intrinsics[2,1], 0)
assert_almost_equal( intrinsics[2,2], 1)
@opencv_skip
@dec.slow
def test_cvCalibrateCamera2_KnownData(self):
_, (object_points,points_count,image_points,intrinsics,distortions) = \
np.load(os.path.join(data_dir, "cvCalibrateCamera2TestData.npz"))
intrinsics_test, distortion_test = cvCalibrateCamera2(
object_points, image_points, points_count, (1024,1280)
)
class TestUndistort2(OpenCVTest):
@opencv_skip
def test_cvUndistort2(self):
intrinsics = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]], dtype='float64')
distortions = np.array([0., 0., 0., 0., 0.], dtype='float64')
undist = cvUndistort2(self.lena_RGB_U8, intrinsics, distortions)
undistg = cvUndistort2(self.lena_GRAY_U8, intrinsics, distortions)
assert_array_almost_equal(undist, self.lena_RGB_U8)
assert_array_almost_equal(undistg, self.lena_GRAY_U8)
@opencv_skip
def test_cvUndistort2_new_intrinsics(self):
intrinsics = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]], dtype='float64')
distortions = np.array([0., 0., 0., 0., 0.], dtype='float64')
undist = cvUndistort2(self.lena_RGB_U8, intrinsics, distortions,
intrinsics)
undistg = cvUndistort2(self.lena_GRAY_U8, intrinsics, distortions,
intrinsics)
assert_array_almost_equal(undist, self.lena_RGB_U8)
assert_array_almost_equal(undistg, self.lena_GRAY_U8)
@opencv_skip
def test_cvFindFundamentalMat():
#
# c2--->* * = Data Cloud
# ^
# | ^ z-direction
# c1 <--|
# x
#
# Experimental setup: camera 1 at the origin, random cube data set in front,
# camera two watching from the side (position [10, 0, 10])
# Set up projection matrices
def build_proj_mat(K, R, C):
"""
Construct a projection matrix.
Parameters
----------
K : ndarray, 3x3
Camera matrix, intrinsic parameters.
R : ndarray, 3x3
Rotation, world to camera.
C : ndarray, (3,)
Location of camera center in world coordinates.
"""
C = np.reshape(C, (3, 1))
KR = np.dot(K, R)
P = np.zeros((3, 4))
P[:3, :3] = KR
P[:, 3].flat = np.dot(KR, -C)
return P
def cross_matrix(v):
a = v[0]
b = v[1]
c = v[2]
return np.array([[ 0, -c, b],
[ c, 0, -a],
[-b, a, 0]])
# Camera one, at origin of world coordinates, looking down the z-axis
K = np.array([[100., 0, 100],
[0, 100, 100],
[0, 0, 1]])
R = np.eye(3)
C = np.zeros((3,))
P = build_proj_mat(K, R, C)
# Camera two
K_ = K
R_ = np.array([[0., 0, -1],
[0, 1, 0],
[1, 0, 0]]) # Rotation of 90 degrees around y-axis
C_ = np.array([[10., 0, 10]]).T
P_ = build_proj_mat(K_, R_, C_)
data = np.random.random((100, 4)) * 5 - 2.5
data[:, 2] += 10 # Offset data in the z direction
data[:, 3] = 1 # 4D homogeneous version of 3D coords
points1 = np.dot(data, P.T)
points2 = np.dot(data, P_.T)
# See Hartley & Zisserman, Multiple View Geometry (2nd ed), p. 244
t = -np.dot(R_, C_)
K_t = np.dot(K_, t)
# Under numpy >= 1.5, this would be:
#F = cross_matrix(K_t).dot(K_).dot(R).dot(np.linalg.inv(K))
F = np.dot(np.dot(np.dot(cross_matrix(K_t), K_), R_), np.linalg.inv(K))
F /= F[2, 2]
F_est, status = cvFindFundamentalMat(points1, points2)
# Compare
assert_array_almost_equal(F, F_est)
if __name__ == '__main__':
run_module_suite()
-1
View File
@@ -5,7 +5,6 @@ def configuration(parent_package='', top_path=None):
config = Configuration('image', parent_package, top_path)
config.add_subpackage('opencv')
config.add_subpackage('graph')
config.add_subpackage('io')
config.add_subpackage('morphology')