Merge remote branch 'colbert/master'

This commit is contained in:
Stefan van der Walt
2009-10-14 18:10:13 +02:00
17 changed files with 15713 additions and 0 deletions
+2
View File
@@ -5,3 +5,5 @@
doc/source/api
doc/build
source/api
scikits/image/opencv/*.so
scikits/image/opencv/*.bak
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+8
View File
@@ -0,0 +1,8 @@
Using the setup.py in this directory will work.
But the setup.py in the main scikits.image does not (it uses setuptools)
this will be changed in the future.
+28
View File
@@ -0,0 +1,28 @@
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.
+22
View File
@@ -0,0 +1,22 @@
import ctypes
# try to open the opencv libs
# raise an exception if the libs are not found
# linux
try:
ctypes.CDLL('libcv.so')
except:
# windows
try:
ctypes.CDLL('cv.dll')
except:
raise RuntimeError('The opencv libraries were not found. Please make sure they are installed and available on the system path.')
from opencv_constants import *
from opencv_cv import *
#def test(level=1, verbosity=1):
# from numpy.testing import Tester
# return Tester().test(level, verbosity)
File diff suppressed because it is too large Load Diff
+45
View File
@@ -0,0 +1,45 @@
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)
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 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)
+205
View File
@@ -0,0 +1,205 @@
import numpy as np
cimport numpy as np
from python cimport *
from opencv_constants import *
from opencv_type cimport *
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')
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_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, 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)
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 channels
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 == 2:
img.nChannels = 1
else:
img.nChannels = shape[2]
img.depth = _ipltypes[arr.dtype]
img.width = shape[1]
img.height = shape[0]
img.imageSize = arr.nbytes
img.imageData = <char*>arr.data
img.widthStep = strides[0]
# 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 int validate_array(np.ndarray arr) except -1:
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 your 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
+20
View File
@@ -0,0 +1,20 @@
#############################################
# Constants (need a better place for these)
############################################
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
File diff suppressed because it is too large Load Diff
+540
View File
@@ -0,0 +1,540 @@
import ctypes
import numpy as np
cimport numpy as np
from python cimport *
#from stdlib cimport *
from opencv_type cimport *
from opencv_backend import *
from opencv_backend cimport *
from opencv_constants import *
#one of these should work if the user imported the package properly
try:
cv = ctypes.CDLL('libcv.so')
except:
try:
cv = ctypes.CDLL('cv.dll')
except:
raise RuntimeError('The opencv libraries were not found. Please make sure they are installed and available on the system path.')
###################################
# opencv function declarations
###################################
# cvSobel
ctypedef void (*cvSobelPtr)(IplImage*, IplImage*, int, int, int)
cdef cvSobelPtr c_cvSobel
c_cvSobel = (<cvSobelPtr*><size_t>ctypes.addressof(cv.cvSobel))[0]
# cvLaplace
ctypedef void (*cvLaplacePtr)(IplImage*, IplImage*, int)
cdef cvLaplacePtr c_cvLaplace
c_cvLaplace = (<cvLaplacePtr*><size_t>ctypes.addressof(cv.cvLaplace))[0]
# cvCanny
ctypedef void (*cvCannyPtr)(IplImage*, IplImage*, double, double, int)
cdef cvCannyPtr c_cvCanny
c_cvCanny = (<cvCannyPtr*><size_t>ctypes.addressof(cv.cvCanny))[0]
# cvPreCornerDetect
ctypedef void (*cvPreCorneDetectPtr)(IplImage*, IplImage*, int)
cdef cvPreCorneDetectPtr c_cvPreCornerDetect
c_cvPreCornerDetect = (<cvPreCorneDetectPtr*><size_t>ctypes.addressof(cv.cvPreCornerDetect))[0]
# cvCornerEigenValsAndVecs
ctypedef void (*cvCornerEigenValsAndVecsPtr)(IplImage*, IplImage*, int, int)
cdef cvCornerEigenValsAndVecsPtr c_cvCornerEigenValsAndVecs
c_cvCornerEigenValsAndVecs = (<cvCornerEigenValsAndVecsPtr*><size_t>ctypes.addressof(cv.cvCornerEigenValsAndVecs))[0]
# cvCornerMinEigenVal
ctypedef void (*cvCornerMinEigenValPtr)(IplImage*, IplImage*, int, int)
cdef cvCornerMinEigenValPtr c_cvCornerMinEigenVal
c_cvCornerMinEigenVal = (<cvCornerMinEigenValPtr*><size_t>ctypes.addressof(cv.cvCornerMinEigenVal))[0]
# cvCornerHarris
ctypedef void (*cvCornerHarrisPtr)(IplImage*, IplImage*, int, int, double)
cdef cvCornerHarrisPtr c_cvCornerHarris
c_cvCornerHarris = (<cvCornerHarrisPtr*><size_t>ctypes.addressof(cv.cvCornerHarris))[0]
# cvFindCornerSubPix
ctypedef void (*cvFindCornerSubPixPtr)(IplImage*, CvPoint2D32f*, int, CvSize, CvSize, CvTermCriteria)
cdef cvFindCornerSubPixPtr c_cvFindCornerSubPix
c_cvFindCornerSubPix = (<cvFindCornerSubPixPtr*><size_t>ctypes.addressof(cv.cvFindCornerSubPix))[0]
# cvSmooth
ctypedef void (*cvSmoothPtr)(IplImage*, IplImage*, int, int, int, double, double)
cdef cvSmoothPtr c_cvSmooth
c_cvSmooth = (<cvSmoothPtr*><size_t>ctypes.addressof(cv.cvSmooth))[0]
# cvGoodFeaturesToTrack
ctypedef void (*cvGoodFeaturesToTrackPtr)(IplImage*, IplImage*, IplImage*,
CvPoint2D32f*, int*, double, double,
IplImage*, int, int, double)
cdef cvGoodFeaturesToTrackPtr c_cvGoodFeaturesToTrack
c_cvGoodFeaturesToTrack = (<cvGoodFeaturesToTrackPtr*><size_t>ctypes.addressof(cv.cvGoodFeaturesToTrack))[0]
# cvResize
ctypedef void (*cvResizePtr)(IplImage*, IplImage*, int)
cdef cvResizePtr c_cvResize
c_cvResize = (<cvResizePtr*><size_t>ctypes.addressof(cv.cvResize))[0]
####################################
# Function Implementations
####################################
def cvSobel(np.ndarray src, np.ndarray out=None, int xorder=1, int yorder=0,
int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
assert_dtype(src, [UINT8, INT8, FLOAT32])
assert_nchannels(src, [1])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
if out is not None:
validate_array(out)
assert_not_sharing_data(src, out)
assert_same_shape(src, out)
assert_nchannels(out, [1])
if src.dtype == UINT8 or src.dtype == INT8:
assert_dtype(out, [INT16])
else:
assert_dtype(out, [FLOAT32])
else:
if src.dtype == UINT8 or src.dtype == INT8:
out = new_array_like_diff_dtype(src, INT16)
else:
out = new_array_like(src)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvSobel(&srcimg, &outimg, xorder, yorder, aperture_size)
return out
def cvLaplace(np.ndarray src, np.ndarray out=None, int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
assert_dtype(src, [UINT8, INT8, FLOAT32])
assert_nchannels(src, [1])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
if out is not None:
validate_array(out)
assert_not_sharing_data(src, out)
assert_same_shape(src, out)
assert_nchannels(out, [1])
if src.dtype == UINT8 or src.dtype == INT8:
assert_dtype(out, [INT16])
else:
assert_dtype(out, [FLOAT32])
else:
if src.dtype == UINT8 or src.dtype == INT8:
out = new_array_like_diff_dtype(src, INT16)
else:
out = new_array_like(src)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvLaplace(&srcimg, &outimg, aperture_size)
return out
def cvCanny(np.ndarray src, np.ndarray out=None, double threshold1=10,
double threshold2=50, int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
assert_nchannels(src, [1])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
if out is not None:
validate_array(out)
assert_nchannels(out, [1])
assert_same_shape(src, out)
assert_not_sharing_data(src, out)
else:
out = new_array_like(src)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvCanny(&srcimg, &outimg, threshold1, threshold2, aperture_size)
return out
def cvPreCornerDetect(np.ndarray src, np.ndarray out=None, int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
assert_dtype(src, [UINT8, FLOAT32])
assert_nchannels(src, [1])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
if out is not None:
validate_array(out)
assert_same_shape(src, out)
assert_dtype(out, [FLOAT32])
assert_not_sharing_data(src, out)
else:
out = new_array_like_diff_dtype(src, FLOAT32)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvPreCornerDetect(&srcimg, &outimg, aperture_size)
return out
def cvCornerEigenValsAndVecs(np.ndarray src, int block_size=3,
int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
# no option for the out argument on this one. Its easier just
# to make it for them as there is only 1 valid out array for any
# given source array
validate_array(src)
assert_nchannels(src, [1])
assert_dtype(src, [UINT8, FLOAT32])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
cdef np.npy_intp outshape[2]
outshape[0] = src.shape[0]
outshape[1] = src.shape[1] * <np.npy_intp>6
out = new_array(2, outshape, FLOAT32)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvCornerEigenValsAndVecs(&srcimg, &outimg, block_size, aperture_size)
return out.reshape(out.shape[0], -1, 6)
def cvCornerMinEigenVal(np.ndarray src, int block_size=3,
int aperture_size=3):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
# no option for the out argument on this one. Its easier just
# to make it for them as there is only 1 valid out array for any
# given source array
validate_array(src)
assert_nchannels(src, [1])
assert_dtype(src, [UINT8, FLOAT32])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
out = new_array_like_diff_dtype(src, FLOAT32)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvCornerMinEigenVal(&srcimg, &outimg, block_size, aperture_size)
return out
def cvCornerHarris(np.ndarray src, int block_size=3, int aperture_size=3,
double k=0.04):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
# no option for the out argument on this one. Its easier just
# to make it for them as there is only 1 valid out array for any
# given source array
validate_array(src)
assert_nchannels(src, [1])
assert_dtype(src, [UINT8, FLOAT32])
if (aperture_size != 3 and aperture_size != 5 and aperture_size != 7):
raise ValueError('aperture_size must be 3, 5, or 7')
out = new_array_like_diff_dtype(src, FLOAT32)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvCornerHarris(&srcimg, &outimg, block_size, aperture_size, k)
return out
def cvFindCornerSubPix(np.ndarray src, np.ndarray corners, int count, win,
zero_zone=(-1, -1), int iterations=0,
double epsilon=1e-5):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
validate_array(corners)
assert_nchannels(src, [1])
assert_dtype(src, [UINT8])
assert_nchannels(corners, [1])
assert_dtype(corners, [FLOAT32])
# make sure the number of points
# jives with the elements in the array
# the shape of the array is irrelevant
# because opencv will index it as if it were
# flat anyway, but regardless, the validate_array function ensures
# that it is 2D
cdef int nbytes = <int> get_array_nbytes(corners)
if nbytes != (count * 2 * 4):
raise ValueError('the number of declared points is different than exists in the array')
cdef CvPoint2D32f* cvcorners = array_as_cvPoint2D32f_ptr(corners)
cdef CvSize cvwin
cvwin.height = <int> win[0]
cvwin.width = <int> win[1]
cdef CvSize cvzerozone
cvzerozone.height = <int> zero_zone[0]
cvzerozone.width = <int> zero_zone[1]
cdef IplImage srcimg
populate_iplimage(src, &srcimg)
cdef CvTermCriteria crit
crit = get_cvTermCriteria(iterations, epsilon)
c_cvFindCornerSubPix(&srcimg, cvcorners, count, cvwin, cvzerozone, crit)
return None
def cvSmooth(np.ndarray src, np.ndarray out=None, int smoothtype=CV_GAUSSIAN, int param1=3,
int param2=0, double param3=0, double param4=0, bool in_place=False):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
if out is not None:
validate_array(out)
# there are restrictions that must be placed on the data depending on
# the smoothing operation requested
# CV_BLUR_NO_SCALE
if smoothtype == CV_BLUR_NO_SCALE:
if in_place:
raise RuntimeError('In place operation not supported with this filter')
assert_dtype(src, [UINT8, INT8, FLOAT32])
assert_ndims(src, [2])
if out is not None:
if src.dtype == FLOAT32:
assert_dtype(out, [FLOAT32])
else:
assert_dtype(out, [INT16])
assert_same_shape(src, out)
else:
if src.dtype == FLOAT32:
out = new_array_like(src)
else:
out = new_array_like_diff_dtype(src, INT16)
# CV_BLUR and CV_GAUSSIAN
elif smoothtype == CV_BLUR or smoothtype == CV_GAUSSIAN:
assert_dtype(src, [UINT8, INT8, FLOAT32])
assert_nchannels(src, [1, 3])
if in_place:
out = src
elif out is not None:
assert_like(src, out)
else:
out = new_array_like(src)
# CV_MEDIAN and CV_BILATERAL
else:
assert_dtype(src, [UINT8, INT8])
assert_nchannels(src, [1, 3])
if in_place:
raise RuntimeError('In place operation not supported with this filter')
if out is not None:
assert_like(src, out)
else:
out = new_array_like(src)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvSmooth(&srcimg, &outimg, smoothtype, param1, param2, param3, param4)
return out
def cvGoodFeaturesToTrack(np.ndarray src, int corner_count, double quality_level,
double min_distance, np.ndarray mask=None,
int block_size=3, int use_harris=0, double k=0.04):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
assert_dtype(src, [UINT8, FLOAT32])
assert_nchannels(src, [1])
cdef np.ndarray eig = new_array_like_diff_dtype(src, FLOAT32)
cdef np.ndarray temp = new_array_like(eig)
cdef CvPoint2D32f* corners = (
<CvPoint2D32f*>PyMem_Malloc(corner_count * sizeof(CvPoint2D32f)))
cdef int out_corner_count
out_corner_count = corner_count
cdef IplImage srcimg
cdef IplImage eigimg
cdef IplImage tempimg
cdef IplImage *maskimg
populate_iplimage(src, &srcimg)
populate_iplimage(eig, &eigimg)
populate_iplimage(temp, &tempimg)
if mask is None:
maskimg = NULL
else:
validate_array(mask)
assert_nchannels(mask, [1])
populate_iplimage(mask, maskimg)
c_cvGoodFeaturesToTrack(&srcimg, &eigimg, &tempimg, corners, &out_corner_count,
quality_level, min_distance, maskimg, block_size,
use_harris, k)
# since the maximum allowed corners may not have been found
# the array might be too long, we create a new array and copy
# the the data into it
#
# It would be nice to use the numpy C-Api for this, but I couldn't quite
# get it to work
cdef np.npy_intp cornershape[2]
cornershape[0] = <np.npy_intp>out_corner_count
cornershape[1] = 2
cdef np.ndarray cornersarr = new_array(2, cornershape, FLOAT32)
cdef int i
for i in range(out_corner_count):
cornersarr[i,0] = corners[i].x
cornersarr[i,1] = corners[i].y
PyMem_Free(corners)
return cornersarr
def cvResize(np.ndarray src, height=None, width=None,
int method=CV_INTER_LINEAR):
"""
better doc string needed.
for now:
http://opencv.willowgarage.com/documentation/cvreference.html
"""
validate_array(src)
if not height or not width:
raise ValueError('width and height must not be none')
cdef int ndim = src.ndim
cdef np.npy_intp* shape = clone_array_shape(src)
shape[0] = height
shape[1] = width
cdef np.ndarray out = new_array(ndim, shape, src.dtype)
validate_array(out)
PyMem_Free(shape)
cdef IplImage srcimg
cdef IplImage outimg
populate_iplimage(src, &srcimg)
populate_iplimage(out, &outimg)
c_cvResize(&srcimg, &outimg, method)
return out
+50
View File
@@ -0,0 +1,50 @@
# 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
cdef struct CvPoint2D32f:
float x
float y
cdef struct CvSize:
int width
int height
cdef struct CvTermCriteria:
int type
int max_iter
double epsilon
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python
import os
import shutil
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')
# since distutils/cython has problems, we'll check to see if cython is
# installed and use that to rebuild the .c files, if not, we'll just build
# directly from the included .c files
cython_files = ['opencv_backend.pyx', 'opencv_cv.pyx']
try:
import Cython
for pyxfile in cython_files:
# make a backup of the good c files
c_file = pyxfile.rstrip('pyx') + 'c'
src = c_file
dst = c_file + '.bak'
shutil.copy(src, dst)
# run cython compiler
os.system('cython ' + pyxfile)
# if the file is small, cython compilation failed
size = os.path.getsize(c_file)
if size < 100:
print 'Cython compilation failed. Restoring from backup.'
# restore from backup
shutil.copy(dst, src)
except ImportError:
# if cython is not found, we just build from the include .c files
pass
for pyxfile in cython_files:
c_file = pyxfile.rstrip('pyx') + 'c'
config.add_extension(pyxfile.rstrip('.pyx'),
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 = 'http://stefanv.github.com/scikits.image/',
license = 'SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
@@ -0,0 +1,109 @@
# test for the opencv_cv extension module
import os
import numpy as np
from numpy.testing import *
try:
from scikits.image.opencv import *
OPENCV_LIBS_NOTFOUND = False
except:
OPENCV_LIBS_NOTFOUND = True
from scikits.image import data_dir
_opencv_skip = dec.skipif(OPENCV_LIBS_NOTFOUND,
'Skipping OpenCV test because OpenCV'
'libs were not found')
class OpenCVTest:
# setup only works as a module level function
def __init__(self):
self.lena_RGB_U8 = np.load(os.path.join(data_dir, 'lena_RGB_U8.npy'))
self.lena_GRAY_U8 = np.load(os.path.join(data_dir, 'lena_GRAY_U8.npy'))
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 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, None, st, 3, 0, 0, 0, False)
class TestFindCornerSubPix:
@_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, 4, (2, 2))
class TestGoodFeaturesToTrack(OpenCVTest):
@_opencv_skip
def test_cvGoodFeaturesToTrack(self):
cvGoodFeaturesToTrack(self.lena_GRAY_U8, 100, 0.1, 3)
class TestResize(OpenCVTest):
@_opencv_skip
def test_cvResize(self):
cvResize(self.lena_RGB_U8, height=50, width=50, method=CV_INTER_LINEAR)
cvResize(self.lena_RGB_U8, height=200, width=200, method=CV_INTER_CUBIC)
if __name__ == '__main__':
run_module_suite()