diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.pbxproj b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.pbxproj old mode 100755 new mode 100644 index 21eff4c..c719023 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.pbxproj +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.pbxproj @@ -15,6 +15,7 @@ 8A2051981510BCB900E80270 /* SimpleVisualizationController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8A2051971510BCB900E80270 /* SimpleVisualizationController.mm */; }; 8A279D1F150E3F88005F4854 /* MarkerDetector.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8A279D1E150E3F88005F4854 /* MarkerDetector.cpp */; }; 8A28CB2615249CEA0049925A /* TinyLA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8A28CB2515249CEA0049925A /* TinyLA.cpp */; }; + 8A8BD08D15E4DFE300B9E08E /* opencv2.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A8BD08C15E4DFE300B9E08E /* opencv2.framework */; }; 8ADAC4391504BC61008B5F2A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8ADAC4381504BC61008B5F2A /* UIKit.framework */; }; 8ADAC43B1504BC61008B5F2A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8ADAC43A1504BC61008B5F2A /* Foundation.framework */; }; 8ADAC43D1504BC61008B5F2A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8ADAC43C1504BC61008B5F2A /* CoreGraphics.framework */; }; @@ -38,18 +39,18 @@ 8A205171150F8D2000E80270 /* Marker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Marker.cpp; sourceTree = ""; }; 8A20518B1510A35F00E80270 /* EAGLView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EAGLView.h; sourceTree = ""; }; 8A20518C1510A35F00E80270 /* EAGLView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EAGLView.m; sourceTree = ""; }; - 8A20518E1510A58F00E80270 /* VisualizationController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = VisualizationController.h; sourceTree = ""; }; 8A20518F1510A6E300E80270 /* GeometryTypes.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = GeometryTypes.hpp; sourceTree = ""; }; 8A2051901510BB7B00E80270 /* GLKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GLKit.framework; path = System/Library/Frameworks/GLKit.framework; sourceTree = SDKROOT; }; 8A2051911510BB7B00E80270 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; 8A2051941510BB8C00E80270 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; 8A2051961510BCB900E80270 /* SimpleVisualizationController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleVisualizationController.h; sourceTree = ""; }; 8A2051971510BCB900E80270 /* SimpleVisualizationController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SimpleVisualizationController.mm; sourceTree = ""; }; - 8A2051A015112D3B00E80270 /* MarkerDetectionFacade.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = MarkerDetectionFacade.hpp; sourceTree = ""; }; 8A279D1C150E3F7E005F4854 /* MarkerDetector.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = MarkerDetector.hpp; sourceTree = ""; }; 8A279D1E150E3F88005F4854 /* MarkerDetector.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MarkerDetector.cpp; sourceTree = ""; }; 8A28CB2315249CDA0049925A /* TinyLA.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = TinyLA.hpp; sourceTree = ""; }; 8A28CB2515249CEA0049925A /* TinyLA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TinyLA.cpp; sourceTree = ""; }; + 8A8BD08C15E4DFE300B9E08E /* opencv2.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = opencv2.framework; sourceTree = ""; }; + 8AAEC1C815E6427300CBC28C /* DebugHelpers.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = DebugHelpers.hpp; sourceTree = ""; }; 8ADAC4341504BC61008B5F2A /* Example_MarkerBasedAR.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example_MarkerBasedAR.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8ADAC4381504BC61008B5F2A /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 8ADAC43A1504BC61008B5F2A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; @@ -79,6 +80,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8A8BD08D15E4DFE300B9E08E /* opencv2.framework in Frameworks */, 8A2051931510BB7B00E80270 /* OpenGLES.framework in Frameworks */, 8A2051951510BB8C00E80270 /* QuartzCore.framework in Frameworks */, 8A2051921510BB7B00E80270 /* GLKit.framework in Frameworks */, @@ -94,15 +96,6 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 8A20517D150FAE6600E80270 /* Interfaces */ = { - isa = PBXGroup; - children = ( - 8A2051A015112D3B00E80270 /* MarkerDetectionFacade.hpp */, - 8A20518E1510A58F00E80270 /* VisualizationController.h */, - ); - name = Interfaces; - sourceTree = ""; - }; 8A20517F1510A30800E80270 /* Rendering */ = { isa = PBXGroup; children = ( @@ -117,6 +110,7 @@ 8A279D20150E3F8C005F4854 /* MarkerDetector */ = { isa = PBXGroup; children = ( + 8AAEC1C815E6427300CBC28C /* DebugHelpers.hpp */, 8A279D1C150E3F7E005F4854 /* MarkerDetector.hpp */, 8A279D1E150E3F88005F4854 /* MarkerDetector.cpp */, 8A205170150F8D1800E80270 /* Marker.hpp */, @@ -147,6 +141,7 @@ 8ADAC4371504BC61008B5F2A /* Frameworks */ = { isa = PBXGroup; children = ( + 8A8BD08C15E4DFE300B9E08E /* opencv2.framework */, 8A2051941510BB8C00E80270 /* QuartzCore.framework */, 8A2051901510BB7B00E80270 /* GLKit.framework */, 8A2051911510BB7B00E80270 /* OpenGLES.framework */, @@ -163,9 +158,8 @@ 8ADAC43E1504BC61008B5F2A /* Example_MarkerBasedAR */ = { isa = PBXGroup; children = ( - 8A20517F1510A30800E80270 /* Rendering */, - 8A20517D150FAE6600E80270 /* Interfaces */, 8A279D20150E3F8C005F4854 /* MarkerDetector */, + 8A20517F1510A30800E80270 /* Rendering */, 8ADAC46A1504C9DE008B5F2A /* VideoSource */, 8ADAC4471504BC61008B5F2A /* AppDelegate.h */, 8ADAC4481504BC61008B5F2A /* AppDelegate.m */, @@ -229,7 +223,7 @@ 8ADAC42B1504BC61008B5F2A /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0430; + LastUpgradeCheck = 0440; }; buildConfigurationList = 8ADAC42E1504BC61008B5F2A /* Build configuration list for PBXProject "Example_MarkerBasedAR" */; compatibilityVersion = "Xcode 3.2"; @@ -318,6 +312,7 @@ CLANG_ENABLE_OBJC_ARC = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + FRAMEWORK_SEARCH_PATHS = "\"$(SRCROOT)\""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; @@ -330,9 +325,7 @@ GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = "$(SRCROOT)/opencv/include"; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = "$(SRCROOT)/opencv/lib/debug"; OTHER_LDFLAGS = ( "-lopencv_calib3d", "-lzlib", @@ -345,7 +338,6 @@ ); SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/opencv/include"; }; name = Debug; }; @@ -357,14 +349,14 @@ CLANG_ENABLE_OBJC_ARC = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; + FRAMEWORK_SEARCH_PATHS = "\"$(SRCROOT)\""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_VERSION = com.apple.compilers.llvm.clang.1_0; GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = "$(SRCROOT)/opencv/include"; IPHONEOS_DEPLOYMENT_TARGET = 5.0; - LIBRARY_SEARCH_PATHS = "$(SRCROOT)/opencv/lib/release"; + LIBRARY_SEARCH_PATHS = ""; OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; OTHER_LDFLAGS = ( "-lopencv_calib3d", @@ -378,7 +370,6 @@ ); SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/opencv/include"; VALIDATE_PRODUCT = YES; }; name = Release; @@ -386,10 +377,21 @@ 8ADAC4561504BC61008B5F2A /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_CXX_LIBRARY = "libc++"; + CODE_SIGN_IDENTITY = "iPhone Developer"; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)\"", + ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch"; + HEADER_SEARCH_PATHS = ""; INFOPLIST_FILE = "Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist"; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + USER_HEADER_SEARCH_PATHS = ""; WRAPPER_EXTENSION = app; }; name = Debug; @@ -397,10 +399,21 @@ 8ADAC4571504BC61008B5F2A /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + CLANG_CXX_LIBRARY = "libc++"; + CODE_SIGN_IDENTITY = "iPhone Developer"; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)\"", + ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch"; + HEADER_SEARCH_PATHS = ""; INFOPLIST_FILE = "Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist"; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + USER_HEADER_SEARCH_PATHS = ""; WRAPPER_EXTENSION = app; }; name = Release; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/WorkspaceSettings.xcsettings b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/WorkspaceSettings.xcsettings deleted file mode 100755 index 659c876..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,10 +0,0 @@ - - - - - HasAskedToTakeAutomaticSnapshotBeforeSignificantChanges - - SnapshotAutomaticallyBeforeSignificantChanges - - - diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/xcdebugger/Expressions.xcexplist b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/xcdebugger/Expressions.xcexplist deleted file mode 100755 index 6665fa0..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/project.xcworkspace/xcuserdata/bloodaxe.xcuserdatad/xcdebugger/Expressions.xcexplist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/xcuserdata/bloodaxe.xcuserdatad/xcschemes/Example_MarkerBasedAR - Release.xcscheme b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/xcuserdata/bloodaxe.xcuserdatad/xcschemes/Example_MarkerBasedAR - Release.xcscheme deleted file mode 100755 index 211e6e4..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR.xcodeproj/xcuserdata/bloodaxe.xcuserdatad/xcschemes/Example_MarkerBasedAR - Release.xcscheme +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.h old mode 100755 new mode 100644 index 2269fdc..8d3bc89 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.h @@ -1,19 +1,19 @@ -/***************************************************************************** -* AppDelegate.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import - -@interface AppDelegate : UIResponder - -@property (strong, nonatomic) UIWindow *window; - -@end +/***************************************************************************** +* AppDelegate.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +@interface AppDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.m b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.m old mode 100755 new mode 100644 index 77f2fcd..c9b31d1 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.m +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/AppDelegate.m @@ -1,64 +1,64 @@ -/***************************************************************************** -* AppDelegate.m -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import "AppDelegate.h" - -@implementation AppDelegate - -@synthesize window = _window; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions -{ - // Override point for customization after application launch. - return YES; -} - -- (void)applicationWillResignActive:(UIApplication *)application -{ - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ -} - -- (void)applicationDidEnterBackground:(UIApplication *)application -{ - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - */ -} - -- (void)applicationWillEnterForeground:(UIApplication *)application -{ - /* - Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. - */ -} - -- (void)applicationDidBecomeActive:(UIApplication *)application -{ - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ -} - -- (void)applicationWillTerminate:(UIApplication *)application -{ - /* - Called when the application is about to terminate. - Save data if appropriate. - See also applicationDidEnterBackground:. - */ -} - -@end +/***************************************************************************** +* AppDelegate.m +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import "AppDelegate.h" + +@implementation AppDelegate + +@synthesize window = _window; + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + // Override point for customization after application launch. + return YES; +} + +- (void)applicationWillResignActive:(UIApplication *)application +{ + /* + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + */ +} + +- (void)applicationDidEnterBackground:(UIApplication *)application +{ + /* + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + */ +} + +- (void)applicationWillEnterForeground:(UIApplication *)application +{ + /* + Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + */ +} + +- (void)applicationDidBecomeActive:(UIApplication *)application +{ + /* + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + */ +} + +- (void)applicationWillTerminate:(UIApplication *)application +{ + /* + Called when the application is about to terminate. + Save data if appropriate. + See also applicationDidEnterBackground:. + */ +} + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/BGRAVideoFrame.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/BGRAVideoFrame.h old mode 100755 new mode 100644 index e65f5f3..e183199 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/BGRAVideoFrame.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/BGRAVideoFrame.h @@ -1,27 +1,29 @@ -/***************************************************************************** -* BGRAVideoFrame.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_BGRAVideoFrame_h -#define Example_MarkerBasedAR_BGRAVideoFrame_h - -// A helper struct presenting interleaved BGRA image in memory. -struct BGRAVideoFrame -{ - size_t width; - size_t height; - size_t stride; - - uint8_t * data; -}; - - -#endif +/***************************************************************************** +* BGRAVideoFrame.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_BGRAVideoFrame_h +#define Example_MarkerBasedAR_BGRAVideoFrame_h + +#include + +// A helper struct presenting interleaved BGRA image in memory. +struct BGRAVideoFrame +{ + size_t width; + size_t height; + size_t stride; + + unsigned char * data; +}; + + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.cpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.cpp old mode 100755 new mode 100644 index c5dfc1d..fc45366 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.cpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.cpp @@ -1,69 +1,69 @@ -/***************************************************************************** -* CameraCalibration.cpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#include "CameraCalibration.hpp" - - -CameraCalibration::CameraCalibration() -{ - -} - -CameraCalibration::CameraCalibration(float fx, float fy, float cx, float cy) -{ - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - m_intrinsic.mat[i][j] = 0; - - m_intrinsic.mat[0][0] = fx; - m_intrinsic.mat[1][1] = fy; - m_intrinsic.mat[0][2] = cx; - m_intrinsic.mat[1][2] = cy; - - for (int i=0; i<4; i++) - m_distorsion.data[i] = 0; -} - -CameraCalibration::CameraCalibration(float fx, float fy, float cx, float cy, float distorsionCoeff[4]) -{ - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - m_intrinsic.mat[i][j] = 0; - - m_intrinsic.mat[0][0] = fx; - m_intrinsic.mat[1][1] = fy; - m_intrinsic.mat[0][2] = cx; - m_intrinsic.mat[1][2] = cy; - - for (int i=0; i<4; i++) - m_distorsion.data[i] = distorsionCoeff[i]; -} - -void CameraCalibration::getMatrix34(float cparam[3][4]) const -{ - for (int j=0; j<3; j++) - for (int i=0; i<3; i++) - cparam[i][j] = m_intrinsic.mat[i][j]; - - for (int i=0; i<4; i++) - cparam[3][i] = m_distorsion.data[i]; -} - -const Matrix33& CameraCalibration::getIntrinsic() const -{ - return m_intrinsic; -} - -const Vector4& CameraCalibration::getDistorsion() const -{ - return m_distorsion; +/***************************************************************************** +* CameraCalibration.cpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#include "CameraCalibration.hpp" + + +CameraCalibration::CameraCalibration() +{ + +} + +CameraCalibration::CameraCalibration(float fx, float fy, float cx, float cy) +{ + for (int i=0; i<3; i++) + for (int j=0; j<3; j++) + m_intrinsic.mat[i][j] = 0; + + m_intrinsic.mat[0][0] = fx; + m_intrinsic.mat[1][1] = fy; + m_intrinsic.mat[0][2] = cx; + m_intrinsic.mat[1][2] = cy; + + for (int i=0; i<4; i++) + m_distorsion.data[i] = 0; +} + +CameraCalibration::CameraCalibration(float fx, float fy, float cx, float cy, float distorsionCoeff[4]) +{ + for (int i=0; i<3; i++) + for (int j=0; j<3; j++) + m_intrinsic.mat[i][j] = 0; + + m_intrinsic.mat[0][0] = fx; + m_intrinsic.mat[1][1] = fy; + m_intrinsic.mat[0][2] = cx; + m_intrinsic.mat[1][2] = cy; + + for (int i=0; i<4; i++) + m_distorsion.data[i] = distorsionCoeff[i]; +} + +void CameraCalibration::getMatrix34(float cparam[3][4]) const +{ + for (int j=0; j<3; j++) + for (int i=0; i<3; i++) + cparam[i][j] = m_intrinsic.mat[i][j]; + + for (int i=0; i<4; i++) + cparam[3][i] = m_distorsion.data[i]; +} + +const Matrix33& CameraCalibration::getIntrinsic() const +{ + return m_intrinsic; +} + +const Vector4& CameraCalibration::getDistorsion() const +{ + return m_distorsion; } \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.hpp old mode 100755 new mode 100644 index 08317ad..e43b8d4 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/CameraCalibration.hpp @@ -1,40 +1,41 @@ -/***************************************************************************** -* CameraCalibration.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_CameraCalibration_hpp -#define Example_MarkerBasedAR_CameraCalibration_hpp - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "GeometryTypes.hpp" - -/** - * A camera calibraiton class that stores intrinsic matrix and distorsion coefficients. - */ -class CameraCalibration -{ -public: - CameraCalibration(); - CameraCalibration(float fx, float fy, float cx, float cy); - CameraCalibration(float fx, float fy, float cx, float cy, float distorsionCoeff[4]); - - void getMatrix34(float cparam[3][4]) const; - - const Matrix33& getIntrinsic() const; - const Vector4& getDistorsion() const; - -private: - Matrix33 m_intrinsic; - Vector4 m_distorsion; -}; - -#endif +/***************************************************************************** +* CameraCalibration.hpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_CameraCalibration_hpp +#define Example_MarkerBasedAR_CameraCalibration_hpp + +//////////////////////////////////////////////////////////////////// +// File includes: +#include "GeometryTypes.hpp" + +/** + * A camera calibraiton class that stores intrinsic matrix + * and distorsion vector. + */ +class CameraCalibration +{ +public: + CameraCalibration(); + CameraCalibration(float fx, float fy, float cx, float cy); + CameraCalibration(float fx, float fy, float cx, float cy, float distorsionCoeff[4]); + + void getMatrix34(float cparam[3][4]) const; + + const Matrix33& getIntrinsic() const; + const Vector4& getDistorsion() const; + +private: + Matrix33 m_intrinsic; + Vector4 m_distorsion; +}; + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/DebugHelpers.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/DebugHelpers.hpp new file mode 100644 index 0000000..534de37 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/DebugHelpers.hpp @@ -0,0 +1,24 @@ +#ifndef DEBUG_HELPERS_HPP +#define DEBUG_HELPERS_HPP + +#include +#include + +template +std::string ToString(const T& value) +{ + std::ostringstream stream; + stream << value; + return stream.str(); +} + +namespace cv +{ + inline void showAndSave(std::string name, const cv::Mat& m) + { + cv::imshow(name, m); + cv::imwrite(name + ".png", m); + } +} + +#endif \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.h old mode 100755 new mode 100644 index 289b60d..a54ed34 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.h @@ -1,40 +1,40 @@ -/***************************************************************************** -* EAGLView.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import - -#import -#import -#import -#import - -@class EAGLContext; - -// This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. -// The view content is basically an EAGL surface you render your OpenGL scene into. -// Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. -@interface EAGLView : UIView -{ -@private - // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view. - GLuint defaultFramebuffer, colorRenderbuffer; -} - -@property (nonatomic, retain) EAGLContext *context; -// The pixel dimensions of the CAEAGLLayer. -@property (readonly) GLint framebufferWidth; -@property (readonly) GLint framebufferHeight; - -- (void)setFramebuffer; -- (BOOL)presentFramebuffer; -- (void)initContext; -@end +/***************************************************************************** +* EAGLView.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +#import +#import +#import +#import + +@class EAGLContext; + +// This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass. +// The view content is basically an EAGL surface you render your OpenGL scene into. +// Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. +@interface EAGLView : UIView +{ +@private + // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view. + GLuint defaultFramebuffer, colorRenderbuffer, depthRenderbuffer; +} + +@property (nonatomic, retain) EAGLContext *context; +// The pixel dimensions of the CAEAGLLayer. +@property (readonly) GLint framebufferWidth; +@property (readonly) GLint framebufferHeight; + +- (void)setFramebuffer; +- (BOOL)presentFramebuffer; +- (void)initContext; +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.m b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.m old mode 100755 new mode 100644 index 54c1b3c..a3a3be0 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.m +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/EAGLView.m @@ -1,170 +1,180 @@ -/***************************************************************************** -* EAGLView.m -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import - -#import "EAGLView.h" - -@interface EAGLView (PrivateMethods) -- (void)createFramebuffer; -- (void)deleteFramebuffer; -@end - -@implementation EAGLView - -@synthesize context, framebufferWidth, framebufferHeight; - -// You must implement this method -+ (Class)layerClass -{ - return [CAEAGLLayer class]; -} - -//The EAGL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:. -- (id)initWithCoder:(NSCoder*)coder -{ - self = [super initWithCoder:coder]; - if (self) { - CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; - - eaglLayer.opaque = TRUE; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, - kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, - nil]; - - [self initContext]; - } - - return self; -} - -- (void)dealloc -{ - [self deleteFramebuffer]; - - if ([EAGLContext currentContext] == context) - [EAGLContext setCurrentContext:nil]; - -} - -- (void)setContext:(EAGLContext *)newContext -{ - if (context != newContext) - { - [self deleteFramebuffer]; - - context = newContext; - - [EAGLContext setCurrentContext:nil]; - } -} - -- (void)createFramebuffer -{ - if (context && !defaultFramebuffer) { - [EAGLContext setCurrentContext:context]; - - // Create default framebuffer object. - glGenFramebuffers(1, &defaultFramebuffer); - glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer); - - // Create color render buffer and allocate backing store. - glGenRenderbuffers(1, &colorRenderbuffer); - glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); - [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer]; - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth); - glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight); - - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer); - - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); - - //glClearColor(0, 0, 0, 0); - NSLog(@"Framebuffer created"); - } -} - -- (void)deleteFramebuffer -{ - if (context) - { - [EAGLContext setCurrentContext:context]; - - if (defaultFramebuffer) { - glDeleteFramebuffers(1, &defaultFramebuffer); - defaultFramebuffer = 0; - } - - if (colorRenderbuffer) { - glDeleteRenderbuffers(1, &colorRenderbuffer); - colorRenderbuffer = 0; - } - - NSLog(@"Framebuffer deleted"); - - } -} - -- (void)setFramebuffer -{ - if (context) { - [EAGLContext setCurrentContext:context]; - - if (!defaultFramebuffer) - [self createFramebuffer]; - - glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer); - glViewport(0, 0, framebufferWidth, framebufferHeight); - - glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - - } -} - -- (BOOL)presentFramebuffer -{ - BOOL success = FALSE; - - if (context) { - [EAGLContext setCurrentContext:context]; - - glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); - - success = [context presentRenderbuffer:GL_RENDERBUFFER]; - } - - return success; -} - -- (void)layoutSubviews -{ - // The framebuffer will be re-created at the beginning of the next setFramebuffer method call. - [self deleteFramebuffer]; -} - -- (void)initContext -{ - EAGLContext *aContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; - - if (!aContext) - NSLog(@"Failed to create ES context"); - else if (![EAGLContext setCurrentContext:aContext]) - NSLog(@"Failed to set ES context current"); - - [self setContext:aContext]; - [self setFramebuffer]; -} - - -@end +/***************************************************************************** +* EAGLView.m +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +#import "EAGLView.h" + +@interface EAGLView (PrivateMethods) +- (void)createFramebuffer; +- (void)deleteFramebuffer; +@end + +@implementation EAGLView + +@synthesize context, framebufferWidth, framebufferHeight; + +// You must implement this method ++ (Class)layerClass +{ + return [CAEAGLLayer class]; +} + +//The EAGL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:. +- (id)initWithCoder:(NSCoder*)coder +{ + self = [super initWithCoder:coder]; + if (self) { + CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; + + eaglLayer.opaque = TRUE; + eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, + kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, + nil]; + + [self initContext]; + } + + return self; +} + +- (void)dealloc +{ + [self deleteFramebuffer]; + + if ([EAGLContext currentContext] == context) + [EAGLContext setCurrentContext:nil]; + +} + +- (void)setContext:(EAGLContext *)newContext +{ + if (context != newContext) + { + [self deleteFramebuffer]; + + context = newContext; + + [EAGLContext setCurrentContext:nil]; + } +} + +- (void)createFramebuffer +{ + if (context && !defaultFramebuffer) + { + [EAGLContext setCurrentContext:context]; + + // Create default framebuffer object. + glGenFramebuffers(1, &defaultFramebuffer); + glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer); + + // Create color render buffer and allocate backing store. + glGenRenderbuffers(1, &colorRenderbuffer); + glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); + [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer]; + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth); + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer); + + // Create depth render buffer and allocate backing store. + glGenRenderbuffers(1, &depthRenderbuffer); + glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer); + + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, framebufferWidth, framebufferHeight); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer); + + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); + } +} + +- (void)deleteFramebuffer +{ + if (context) + { + [EAGLContext setCurrentContext:context]; + + if (defaultFramebuffer) { + glDeleteFramebuffers(1, &defaultFramebuffer); + defaultFramebuffer = 0; + } + + if (colorRenderbuffer) { + glDeleteRenderbuffers(1, &colorRenderbuffer); + colorRenderbuffer = 0; + } + + if (depthRenderbuffer) { + glDeleteRenderbuffers(1, &depthRenderbuffer); + depthRenderbuffer = 0; + } + NSLog(@"Framebuffer deleted"); + + } +} + +- (void)setFramebuffer +{ + if (context) { + [EAGLContext setCurrentContext:context]; + + if (!defaultFramebuffer) + [self createFramebuffer]; + + glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer); + glViewport(0, 0, framebufferWidth, framebufferHeight); + + glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); + + } +} + +- (BOOL)presentFramebuffer +{ + BOOL success = FALSE; + + if (context) { + [EAGLContext setCurrentContext:context]; + + glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); + + success = [context presentRenderbuffer:GL_RENDERBUFFER]; + } + + return success; +} + +- (void)layoutSubviews +{ + // The framebuffer will be re-created at the beginning of the next setFramebuffer method call. + [self deleteFramebuffer]; +} + +- (void)initContext +{ + EAGLContext *aContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; + + if (!aContext) + NSLog(@"Failed to create ES context"); + else if (![EAGLContext setCurrentContext:aContext]) + NSLog(@"Failed to set ES context current"); + + [self setContext:aContext]; + [self setFramebuffer]; +} + + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist old mode 100755 new mode 100644 index 7d567c9..23e138f --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Info.plist @@ -36,8 +36,6 @@ UISupportedInterfaceOrientations - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch old mode 100755 new mode 100644 index fffa1a6..6c13844 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Example_MarkerBasedAR-Prefix.pch @@ -8,6 +8,10 @@ #warning "This project uses features only available in iOS SDK 5.0 and later." #endif +#ifdef __cplusplus + #include +#endif + #ifdef __OBJC__ #import #import diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.cpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.cpp old mode 100755 new mode 100644 index fa1ba43..84b2ccf --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.cpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.cpp @@ -1,145 +1,145 @@ -/***************************************************************************** -* GeometryTypes.cpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#include "GeometryTypes.hpp" - -Matrix44 Matrix44::getTransposed() const -{ - Matrix44 t; - - for (int i=0;i<4; i++) - for (int j=0;j<4;j++) - t.mat[i][j] = mat[j][i]; - - return t; -} - -Matrix44 Matrix44::identity() -{ - Matrix44 eye; - - for (int i=0;i<4; i++) - for (int j=0;j<4;j++) - eye.mat[i][j] = i == j ? 1 : 0; - - return eye; -} - -Matrix44 Matrix44::getInvertedRT() const -{ - Matrix44 t = identity(); - - for (int col=0;col<3; col++) - { - for (int row=0;row<3;row++) - { - // Transpose rotation component (inversion) - t.mat[row][col] = mat[col][row]; - } - - // Inverse translation component - t.mat[3][col] = - mat[3][col]; - } - return t; -} - -Matrix33 Matrix33::identity() -{ - Matrix33 eye; - - for (int i=0;i<3; i++) - for (int j=0;j<3;j++) - eye.mat[i][j] = i == j ? 1 : 0; - - return eye; -} - -Matrix33 Matrix33::getTransposed() const -{ - Matrix33 t; - - for (int i=0;i<3; i++) - for (int j=0;j<3;j++) - t.mat[i][j] = mat[j][i]; - - return t; -} - -Vector3 Vector3::zero() -{ - Vector3 v = { 0,0,0 }; - return v; -} - -Vector3 Vector3::operator-() const -{ - Vector3 v = { -data[0],-data[1],-data[2] }; - return v; -} - -Transformation::Transformation() -: m_rotation(Matrix33::identity()) -, m_translation(Vector3::zero()) -{ - -} - -Transformation::Transformation(const Matrix33& r, const Vector3& t) -: m_rotation(r) -, m_translation(t) -{ - -} - -Matrix33& Transformation::r() -{ - return m_rotation; -} - -Vector3& Transformation::t() -{ - return m_translation; -} - -const Matrix33& Transformation::r() const -{ - return m_rotation; -} - -const Vector3& Transformation::t() const -{ - return m_translation; -} - -Matrix44 Transformation::getMat44() const -{ - Matrix44 res = Matrix44::identity(); - - for (int col=0;col<3;col++) - { - for (int row=0;row<3;row++) - { - // Copy rotation component - res.mat[row][col] = m_rotation.mat[row][col]; - } - - // Copy translation component - res.mat[3][col] = m_translation.data[col]; - } - - return res; -} - -Transformation Transformation::getInverted() const -{ - return Transformation(m_rotation.getTransposed(), -m_translation); +/***************************************************************************** +* GeometryTypes.cpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#include "GeometryTypes.hpp" + +Matrix44 Matrix44::getTransposed() const +{ + Matrix44 t; + + for (int i=0;i<4; i++) + for (int j=0;j<4;j++) + t.mat[i][j] = mat[j][i]; + + return t; +} + +Matrix44 Matrix44::identity() +{ + Matrix44 eye; + + for (int i=0;i<4; i++) + for (int j=0;j<4;j++) + eye.mat[i][j] = i == j ? 1 : 0; + + return eye; +} + +Matrix44 Matrix44::getInvertedRT() const +{ + Matrix44 t = identity(); + + for (int col=0;col<3; col++) + { + for (int row=0;row<3;row++) + { + // Transpose rotation component (inversion) + t.mat[row][col] = mat[col][row]; + } + + // Inverse translation component + t.mat[3][col] = - mat[3][col]; + } + return t; +} + +Matrix33 Matrix33::identity() +{ + Matrix33 eye; + + for (int i=0;i<3; i++) + for (int j=0;j<3;j++) + eye.mat[i][j] = i == j ? 1 : 0; + + return eye; +} + +Matrix33 Matrix33::getTransposed() const +{ + Matrix33 t; + + for (int i=0;i<3; i++) + for (int j=0;j<3;j++) + t.mat[i][j] = mat[j][i]; + + return t; +} + +Vector3 Vector3::zero() +{ + Vector3 v = { 0,0,0 }; + return v; +} + +Vector3 Vector3::operator-() const +{ + Vector3 v = { -data[0],-data[1],-data[2] }; + return v; +} + +Transformation::Transformation() +: m_rotation(Matrix33::identity()) +, m_translation(Vector3::zero()) +{ + +} + +Transformation::Transformation(const Matrix33& r, const Vector3& t) +: m_rotation(r) +, m_translation(t) +{ + +} + +Matrix33& Transformation::r() +{ + return m_rotation; +} + +Vector3& Transformation::t() +{ + return m_translation; +} + +const Matrix33& Transformation::r() const +{ + return m_rotation; +} + +const Vector3& Transformation::t() const +{ + return m_translation; +} + +Matrix44 Transformation::getMat44() const +{ + Matrix44 res = Matrix44::identity(); + + for (int col=0;col<3;col++) + { + for (int row=0;row<3;row++) + { + // Copy rotation component + res.mat[row][col] = m_rotation.mat[row][col]; + } + + // Copy translation component + res.mat[3][col] = m_translation.data[col]; + } + + return res; +} + +Transformation Transformation::getInverted() const +{ + return Transformation(m_rotation.getTransposed(), -m_translation); } \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.hpp old mode 100755 new mode 100644 index 80ae376..b76006f --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/GeometryTypes.hpp @@ -1,73 +1,73 @@ -/***************************************************************************** -* GeometryTypes.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_GeometryTypes_hpp -#define Example_MarkerBasedAR_GeometryTypes_hpp - -struct Matrix44 -{ - union - { - float data[16]; - float mat[4][4]; - }; - - Matrix44 getTransposed() const; - Matrix44 getInvertedRT() const; - static Matrix44 identity(); -}; - -struct Matrix33 -{ - union - { - float data[9]; - float mat[3][3]; - }; - - static Matrix33 identity(); - Matrix33 getTransposed() const; -}; - -struct Vector4 -{ - float data[4]; -}; - -struct Vector3 -{ - float data[3]; - - static Vector3 zero(); - Vector3 operator-() const; -}; - -struct Transformation -{ - Transformation(); - Transformation(const Matrix33& r, const Vector3& t); - - Matrix33& r(); - Vector3& t(); - - const Matrix33& r() const; - const Vector3& t() const; - - Matrix44 getMat44() const; - - Transformation getInverted() const; -private: - Matrix33 m_rotation; - Vector3 m_translation; -}; - -#endif +/***************************************************************************** +* GeometryTypes.hpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_GeometryTypes_hpp +#define Example_MarkerBasedAR_GeometryTypes_hpp + +struct Matrix44 +{ + union + { + float data[16]; + float mat[4][4]; + }; + + Matrix44 getTransposed() const; + Matrix44 getInvertedRT() const; + static Matrix44 identity(); +}; + +struct Matrix33 +{ + union + { + float data[9]; + float mat[3][3]; + }; + + static Matrix33 identity(); + Matrix33 getTransposed() const; +}; + +struct Vector4 +{ + float data[4]; +}; + +struct Vector3 +{ + float data[3]; + + static Vector3 zero(); + Vector3 operator-() const; +}; + +struct Transformation +{ + Transformation(); + Transformation(const Matrix33& r, const Vector3& t); + + Matrix33& r(); + Vector3& t(); + + const Matrix33& r() const; + const Vector3& t() const; + + Matrix44 getMat44() const; + + Transformation getInverted() const; +private: + Matrix33 m_rotation; + Vector3 m_translation; +}; + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.cpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.cpp old mode 100755 new mode 100644 index e672538..84d7cd2 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.cpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.cpp @@ -1,169 +1,185 @@ -/***************************************************************************** -* Marker.cpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#include "Marker.hpp" - -Marker::Marker() -: id(-1) -{ -} - -bool operator<(const Marker &M1,const Marker&M2) -{ - return M1.id(i,j)=in.at(in.cols-j-1,i); - } - } - return out; -} - -int Marker::hammDistMarker(cv::Mat bits) -{ - int ids[4][5]= - { - {1,0,0,0,0}, - {1,0,1,1,1}, - {0,1,0,0,1}, - {0,1,1,1,0} - }; - - int dist=0; - - for (int y=0;y<5;y++) - { - int minSum=1e5; //hamming distance to each possible word - - for (int p=0;p<4;p++) - { - int sum=0; - //now, count - for (int x=0;x<5;x++) - { - sum += bits.at(y,x) == ids[p][x] ? 0 : 1; - } - - if (minSum>sum) - minSum=sum; - } - - //do the and - dist += minSum; - } - - return dist; -} - -int Marker::mat2id(const cv::Mat &bits) -{ - int val=0; - for (int y=0;y<5;y++) - { - val<<=1; - if ( bits.at(y,1)) val|=1; - val<<=1; - if ( bits.at(y,3)) val|=1; - } - return val; -} - -int Marker::getMarkerId(cv::Mat &markerImage,int &nRotations) -{ - assert(markerImage.rows == markerImage.cols); - assert(markerImage.type() == CV_8UC1); - - cv::Mat grey = markerImage; - //threshold image - cv::threshold(grey, grey, 125, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); - - //Markers are divided in 7x7 regions, of which the inner 5x5 belongs to marker info - //the external border should be entirely black - - int cellSize = markerImage.rows / 7; - - for (int y=0;y<7;y++) - { - int inc=6; - - if (y==0 || y==6) inc=1; //for first and last row, check the whole border - - for (int x=0;x<7;x+=inc) - { - int cellX = x * cellSize; - int cellY = y * cellSize; - cv::Mat cell = grey(cv::Rect(cellX,cellY,cellSize,cellSize)); - - int nZ = cv::countNonZero(cell); - - if (nZ > (cellSize*cellSize) / 2) - { - return -1;//can not be a marker because the border element is not black! - } - } - } - - cv::Mat bitMatrix = cv::Mat::zeros(5,5,CV_8UC1); - - //get information(for each inner square, determine if it is black or white) - for (int y=0;y<5;y++) - { - for (int x=0;x<5;x++) - { - int cellX = (x+1)*cellSize; - int cellY = (y+1)*cellSize; - cv::Mat cell = grey(cv::Rect(cellX,cellY,cellSize,cellSize)); - - int nZ = cv::countNonZero(cell); - if (nZ> (cellSize*cellSize) /2) - bitMatrix.at(y,x) = 1; - } - } - - //check all possible rotations - cv::Mat rotations[4]; - int distances[4]; - - rotations[0] = bitMatrix; - distances[0] = hammDistMarker(rotations[0]); - - std::pair minDist(distances[0],0); - - for (int i=1; i<4; i++) - { - //get the hamming distance to the nearest possible word - rotations[i] = rotate(rotations[i-1]); - distances[i] = hammDistMarker(rotations[i]); - - if (distances[i] < minDist.first) - { - minDist.first = distances[i]; - minDist.second = i; - } - } - - nRotations = minDist.second; - if (minDist.first == 0) - { - return mat2id(rotations[minDist.second]); - } - - return -1; -} \ No newline at end of file +/***************************************************************************** +* Marker.cpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#include "Marker.hpp" +#include "DebugHelpers.hpp" + +Marker::Marker() +: id(-1) +{ +} + +bool operator<(const Marker &M1,const Marker&M2) +{ + return M1.id(i,j)=in.at(in.cols-j-1,i); + } + } + return out; +} + +int Marker::hammDistMarker(cv::Mat bits) +{ + int ids[4][5]= + { + {1,0,0,0,0}, + {1,0,1,1,1}, + {0,1,0,0,1}, + {0,1,1,1,0} + }; + + int dist=0; + + for (int y=0;y<5;y++) + { + int minSum=1e5; //hamming distance to each possible word + + for (int p=0;p<4;p++) + { + int sum=0; + //now, count + for (int x=0;x<5;x++) + { + sum += bits.at(y,x) == ids[p][x] ? 0 : 1; + } + + if (minSum>sum) + minSum=sum; + } + + //do the and + dist += minSum; + } + + return dist; +} + +int Marker::mat2id(const cv::Mat &bits) +{ + int val=0; + for (int y=0;y<5;y++) + { + val<<=1; + if ( bits.at(y,1)) val|=1; + val<<=1; + if ( bits.at(y,3)) val|=1; + } + return val; +} + +int Marker::getMarkerId(cv::Mat &markerImage,int &nRotations) +{ + assert(markerImage.rows == markerImage.cols); + assert(markerImage.type() == CV_8UC1); + + cv::Mat grey = markerImage; + + // Threshold image + cv::threshold(grey, grey, 125, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); + +#ifdef SHOW_DEBUG_IMAGES + cv::showAndSave("Binary marker", grey); +#endif + + //Markers are divided in 7x7 regions, of which the inner 5x5 belongs to marker info + //the external border should be entirely black + + int cellSize = markerImage.rows / 7; + + for (int y=0;y<7;y++) + { + int inc=6; + + if (y==0 || y==6) inc=1; //for first and last row, check the whole border + + for (int x=0;x<7;x+=inc) + { + int cellX = x * cellSize; + int cellY = y * cellSize; + cv::Mat cell = grey(cv::Rect(cellX,cellY,cellSize,cellSize)); + + int nZ = cv::countNonZero(cell); + + if (nZ > (cellSize*cellSize) / 2) + { + return -1;//can not be a marker because the border element is not black! + } + } + } + + cv::Mat bitMatrix = cv::Mat::zeros(5,5,CV_8UC1); + + //get information(for each inner square, determine if it is black or white) + for (int y=0;y<5;y++) + { + for (int x=0;x<5;x++) + { + int cellX = (x+1)*cellSize; + int cellY = (y+1)*cellSize; + cv::Mat cell = grey(cv::Rect(cellX,cellY,cellSize,cellSize)); + + int nZ = cv::countNonZero(cell); + if (nZ> (cellSize*cellSize) /2) + bitMatrix.at(y,x) = 1; + } + } + + //check all possible rotations + cv::Mat rotations[4]; + int distances[4]; + + rotations[0] = bitMatrix; + distances[0] = hammDistMarker(rotations[0]); + + std::pair minDist(distances[0],0); + + for (int i=1; i<4; i++) + { + //get the hamming distance to the nearest possible word + rotations[i] = rotate(rotations[i-1]); + distances[i] = hammDistMarker(rotations[i]); + + if (distances[i] < minDist.first) + { + minDist.first = distances[i]; + minDist.second = i; + } + } + + nRotations = minDist.second; + if (minDist.first == 0) + { + return mat2id(rotations[minDist.second]); + } + + return -1; +} + +void Marker::drawContour(cv::Mat& image, cv::Scalar color) const +{ + float thickness = 2; + + cv::line(image, points[0], points[1], color, thickness, CV_AA); + cv::line(image, points[1], points[2], color, thickness, CV_AA); + cv::line(image, points[2], points[3], color, thickness, CV_AA); + cv::line(image, points[3], points[0], color, thickness, CV_AA); +} diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.hpp old mode 100755 new mode 100644 index ccbe4fb..8b8abf4 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/Marker.hpp @@ -1,53 +1,56 @@ -/***************************************************************************** -* Marker.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_Marker_hpp -#define Example_MarkerBasedAR_Marker_hpp - -//////////////////////////////////////////////////////////////////// -// Standard includes: -#include -#include -#include - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "GeometryTypes.hpp" - -/** - * This class represents a marker - */ -class Marker -{ -public: - Marker(); - - friend bool operator<(const Marker &M1,const Marker&M2); - friend std::ostream & operator<<(std::ostream &str,const Marker &M); - - static cv::Mat rotate(cv::Mat in); - static int hammDistMarker(cv::Mat bits); - static int mat2id(const cv::Mat &bits); - static int getMarkerId(cv::Mat &in,int &nRotations); - -public: - - //id of the marker - int id; - - //marker transformation wrt to the camera - Transformation transformation; - - std::vector points; -}; - -#endif +/***************************************************************************** +* Marker.hpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_Marker_hpp +#define Example_MarkerBasedAR_Marker_hpp + +//////////////////////////////////////////////////////////////////// +// Standard includes: +#include +#include +#include + +//////////////////////////////////////////////////////////////////// +// File includes: +#include "GeometryTypes.hpp" + +/** + * This class represents a marker + */ +class Marker +{ +public: + Marker(); + + friend bool operator<(const Marker &M1,const Marker&M2); + friend std::ostream & operator<<(std::ostream &str,const Marker &M); + + static cv::Mat rotate(cv::Mat in); + static int hammDistMarker(cv::Mat bits); + static int mat2id(const cv::Mat &bits); + static int getMarkerId(cv::Mat &in,int &nRotations); + +public: + + // Id of the marker + int id; + + // Marker transformation with regards to the camera + Transformation transformation; + + std::vector points; + + // Helper function to draw the marker contour over the image + void drawContour(cv::Mat& image, cv::Scalar color = CV_RGB(0,250,0)) const; +}; + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetectionFacade.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetectionFacade.hpp deleted file mode 100755 index 7bda29e..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetectionFacade.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/***************************************************************************** -* MarkerDetectionNativeImpl.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_MarkerDetectionNativeImpl_hpp -#define Example_MarkerBasedAR_MarkerDetectionNativeImpl_hpp - -//////////////////////////////////////////////////////////////////// -// Standard includes: -#include -#include - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "BGRAVideoFrame.h" -#include "GeometryTypes.hpp" - -class MarkerDetectionFacade -{ -public: - virtual void processFrame(const BGRAVideoFrame& frame) = 0; - virtual const std::vector& getTransformations() const = 0; - virtual ~MarkerDetectionFacade() {} -}; - -std::auto_ptr createMarkerDetection(CameraCalibration calibration); - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.cpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.cpp old mode 100755 new mode 100644 index d4fb011..7255ddf --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.cpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.cpp @@ -1,348 +1,379 @@ -/***************************************************************************** -* MarkerDetector.cpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -//////////////////////////////////////////////////////////////////// -// Standard includes: -#include - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "MarkerDetector.hpp" -#include "Marker.hpp" -#include "TinyLA.hpp" - -std::auto_ptr createMarkerDetection(CameraCalibration calibration) -{ - return std::auto_ptr(new MarkerDetector(calibration)); -} - -MarkerDetector::MarkerDetector(CameraCalibration calibration) -: m_minContourLengthAllowed(100) -, markerSize(100,100) -{ - cv::Mat(3,3, CV_32F, const_cast(&calibration.getIntrinsic().data[0])).copyTo(camMatrix); - cv::Mat(4,1, CV_32F, const_cast(&calibration.getDistorsion().data[0])).copyTo(distCoeff); - - bool centerOrigin = true; - if (centerOrigin) - { - m_markerCorners3d.push_back(cv::Point3f(-0.5f,-0.5f,0)); - m_markerCorners3d.push_back(cv::Point3f(+0.5f,-0.5f,0)); - m_markerCorners3d.push_back(cv::Point3f(+0.5f,+0.5f,0)); - m_markerCorners3d.push_back(cv::Point3f(-0.5f,+0.5f,0)); - } - else - { - m_markerCorners3d.push_back(cv::Point3f(0,0,0)); - m_markerCorners3d.push_back(cv::Point3f(1,0,0)); - m_markerCorners3d.push_back(cv::Point3f(1,1,0)); - m_markerCorners3d.push_back(cv::Point3f(0,1,0)); - } - - m_markerCorners2d.push_back(cv::Point2f(0,0)); - m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,0)); - m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,markerSize.height-1)); - m_markerCorners2d.push_back(cv::Point2f(0,markerSize.height-1)); -} - -void MarkerDetector::processFrame(const BGRAVideoFrame& frame) -{ - std::vector markers; - findMarkers(frame, markers); - - m_transformations.clear(); - for (size_t i=0; i& MarkerDetector::getTransformations() const -{ - return m_transformations; -} - - -bool MarkerDetector::findMarkers(const BGRAVideoFrame& frame, std::vector& detectedMarkers) -{ - cv::Mat bgraMat(frame.height, frame.width, CV_8UC4, frame.data, frame.stride); - - // Convert the image to grayscale - prepareImage(bgraMat, m_grayscaleImage); - - // Make it binary - performThreshold(m_grayscaleImage, m_thresholdImg); - - // Detect contours - findContours(m_thresholdImg, m_contours, m_grayscaleImage.cols / 5); - - // Find closed contours that can be approximated with 4 points - findMarkerCandidates(m_contours, detectedMarkers); - - // Find is them are markers - detectMarkers(m_grayscaleImage, detectedMarkers); - - // Calcualte their poses - estimatePosition(detectedMarkers); - - //sort by id - std::sort(detectedMarkers.begin(), detectedMarkers.end()); - return false; -} - -void MarkerDetector::prepareImage(const cv::Mat& bgraMat, cv::Mat& grayscale) -{ - // Convert to grayscale - cv::cvtColor(bgraMat, grayscale, CV_BGRA2GRAY); -} - -void MarkerDetector::performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg) -{ - cv::adaptiveThreshold(grayscale, // Input image - thresholdImg,// Result binary image - 255, // - cv::ADAPTIVE_THRESH_GAUSSIAN_C, // - cv::THRESH_BINARY_INV, // - 7, // - 7 // - ); -} - -void MarkerDetector::findContours(const cv::Mat& thresholdImg, std::vector >& contours, int minContourPointsAllowed) -{ - cv::Mat thresholdImgCopy; - thresholdImg.copyTo(thresholdImgCopy); - - std::vector > allContours; - cv::findContours(thresholdImgCopy, allContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); - - contours.clear(); - for (size_t i=0;i minContourPointsAllowed) - { - contours.push_back(allContours[i]); - } - } -} - -void MarkerDetector::findMarkerCandidates(const std::vector >& contours, - std::vector& detectedMarkers) -{ - std::vector approxCurve; - - std::vector possibleMarkers; - - // For each contour, analyze if it is a paralelepiped likely to be the marker - for (size_t i=0; i m_minContourLengthAllowed) - { - Marker m; - for(int i=0;i<4;i++) - { - m.points.push_back( cv::Point2f(approxCurve[i].x,approxCurve[i].y) ); - } - possibleMarkers.push_back(m); - } - } - - //sort the points in anti-clockwise order - for (size_t i=0; i > tooNearCandidates; - for (size_t i=0;i(i,j)); - } - } - } - - //mark for removal the element of the pair with smaller perimeter - std::vector removalMask (possibleMarkers.size(), false); - - for (size_t i=0;i p2) - removalIndex = tooNearCandidates[i].second; - else - removalIndex = tooNearCandidates[i].first; - - removalMask[removalIndex] = true; - } - - // Return candidates - detectedMarkers.clear(); - for (size_t i=0;i& detectedMarkers) -{ - cv::Mat canonicalMarker; - - std::vector goodMarkers; - - // Identify the markers - for (size_t i=0;i 0) - { - std::vector preciseCorners(4 * goodMarkers.size()); - - for (size_t i=0; i& detectedMarkers) -{ - for (size_t i=0; i Tvec; - cv::Mat raux,taux; - cv::solvePnP(m_markerCorners3d, m.points, camMatrix, distCoeff,raux,taux); - raux.convertTo(Rvec,CV_32F); - taux.convertTo(Tvec ,CV_32F); - - cv::Mat_ rotMat(3,3); - cv::Rodrigues(Rvec, rotMat); - - // Copy to transformation matrix - m.transformation = Transformation(); - - for (int col=0; col<3; col++) - { - for (int row=0; row<3; row++) - { - m.transformation.r().mat[row][col] = rotMat(row,col); // Copy rotation component - } - m.transformation.t().data[col] = Tvec(col); // Copy translation component - } - - // Since solvePnP finds camera location, w.r.t to marker pose, to get marker pose w.r.t to the camera we invert it. - m.transformation = m.transformation.getInverted(); - } -} - - +/***************************************************************************** +* MarkerDetector.cpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +//////////////////////////////////////////////////////////////////// +// Standard includes: +#include +#include + +//////////////////////////////////////////////////////////////////// +// File includes: +#include "MarkerDetector.hpp" +#include "Marker.hpp" +#include "TinyLA.hpp" +#include "DebugHelpers.hpp" + +MarkerDetector::MarkerDetector(CameraCalibration calibration) + : m_minContourLengthAllowed(100) + , markerSize(100,100) +{ + cv::Mat(3,3, CV_32F, const_cast(&calibration.getIntrinsic().data[0])).copyTo(camMatrix); + cv::Mat(4,1, CV_32F, const_cast(&calibration.getDistorsion().data[0])).copyTo(distCoeff); + + bool centerOrigin = true; + if (centerOrigin) + { + m_markerCorners3d.push_back(cv::Point3f(-0.5f,-0.5f,0)); + m_markerCorners3d.push_back(cv::Point3f(+0.5f,-0.5f,0)); + m_markerCorners3d.push_back(cv::Point3f(+0.5f,+0.5f,0)); + m_markerCorners3d.push_back(cv::Point3f(-0.5f,+0.5f,0)); + } + else + { + m_markerCorners3d.push_back(cv::Point3f(0,0,0)); + m_markerCorners3d.push_back(cv::Point3f(1,0,0)); + m_markerCorners3d.push_back(cv::Point3f(1,1,0)); + m_markerCorners3d.push_back(cv::Point3f(0,1,0)); + } + + m_markerCorners2d.push_back(cv::Point2f(0,0)); + m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,0)); + m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,markerSize.height-1)); + m_markerCorners2d.push_back(cv::Point2f(0,markerSize.height-1)); +} + +void MarkerDetector::processFrame(const BGRAVideoFrame& frame) +{ + std::vector markers; + findMarkers(frame, markers); + + m_transformations.clear(); + for (size_t i=0; i& MarkerDetector::getTransformations() const +{ + return m_transformations; +} + + +bool MarkerDetector::findMarkers(const BGRAVideoFrame& frame, std::vector& detectedMarkers) +{ + cv::Mat bgraMat(frame.height, frame.width, CV_8UC4, frame.data, frame.stride); + + // Convert the image to grayscale + prepareImage(bgraMat, m_grayscaleImage); + + // Make it binary + performThreshold(m_grayscaleImage, m_thresholdImg); + + // Detect contours + findContours(m_thresholdImg, m_contours, m_grayscaleImage.cols / 5); + + // Find closed contours that can be approximated with 4 points + findCandidates(m_contours, detectedMarkers); + + // Find is them are markers + recognizeMarkers(m_grayscaleImage, detectedMarkers); + + // Calculate their poses + estimatePosition(detectedMarkers); + + //sort by id + std::sort(detectedMarkers.begin(), detectedMarkers.end()); + return false; +} + +void MarkerDetector::prepareImage(const cv::Mat& bgraMat, cv::Mat& grayscale) const +{ + // Convert to grayscale + cv::cvtColor(bgraMat, grayscale, CV_BGRA2GRAY); +} + +void MarkerDetector::performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg) const +{ + cv::threshold(grayscale, thresholdImg, 127, 255, cv::THRESH_BINARY_INV); + + /* + cv::adaptiveThreshold(grayscale, // Input image + thresholdImg,// Result binary image + 255, // + cv::ADAPTIVE_THRESH_GAUSSIAN_C, // + cv::THRESH_BINARY_INV, // + 7, // + 7 // + ); + */ + +#ifdef SHOW_DEBUG_IMAGES + cv::showAndSave("Threshold image", thresholdImg); +#endif +} + +void MarkerDetector::findContours(cv::Mat& thresholdImg, ContoursVector& contours, int minContourPointsAllowed) const +{ + ContoursVector allContours; + cv::findContours(thresholdImg, allContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); + + contours.clear(); + for (size_t i=0; i minContourPointsAllowed) + { + contours.push_back(allContours[i]); + } + } + +#ifdef SHOW_DEBUG_IMAGES + { + cv::Mat contoursImage(thresholdImg.size(), CV_8UC1); + contoursImage = cv::Scalar(0); + cv::drawContours(contoursImage, contours, -1, cv::Scalar(255), 2, CV_AA); + cv::showAndSave("Contours", contoursImage); + } +#endif +} + +void MarkerDetector::findCandidates +( + const ContoursVector& contours, + std::vector& detectedMarkers +) +{ + std::vector approxCurve; + std::vector possibleMarkers; + + // For each contour, analyze if it is a parallelepiped likely to be the marker + for (size_t i=0; i::max(); + + for (int i = 0; i < 4; i++) + { + cv::Point side = approxCurve[i] - approxCurve[(i+1)%4]; + float squaredSideLength = side.dot(side); + minDist = std::min(minDist, squaredSideLength); + } + + // Check that distance is not very small + if (minDist < m_minContourLengthAllowed) + continue; + + // All tests are passed. Save marker candidate: + Marker m; + + for (int i = 0; i<4; i++) + m.points.push_back( cv::Point2f(approxCurve[i].x,approxCurve[i].y) ); + + // Sort the points in anti-clockwise order + // Trace a line between the first and second point. + // If the third point is at the right side, then the points are anti-clockwise + cv::Point v1 = m.points[1] - m.points[0]; + cv::Point v2 = m.points[2] - m.points[0]; + + double o = (v1.x * v2.y) - (v1.y * v2.x); + + if (o < 0.0) //if the third point is in the left side, then sort in anti-clockwise order + std::swap(m.points[1], m.points[3]); + + possibleMarkers.push_back(m); + } + + + // Remove these elements which corners are too close to each other. + // First detect candidates for removal: + std::vector< std::pair > tooNearCandidates; + for (size_t i=0;i(i,j)); + } + } + } + + // Mark for removal the element of the pair with smaller perimeter + std::vector removalMask (possibleMarkers.size(), false); + + for (size_t i=0; i p2) + removalIndex = tooNearCandidates[i].second; + else + removalIndex = tooNearCandidates[i].first; + + removalMask[removalIndex] = true; + } + + // Return candidates + detectedMarkers.clear(); + for (size_t i=0;i& detectedMarkers) +{ + std::vector goodMarkers; + + // Identify the markers + for (size_t i=0;i 0) + { + std::vector preciseCorners(4 * goodMarkers.size()); + + for (size_t i=0; i& detectedMarkers) +{ + for (size_t i=0; i Tvec; + cv::Mat raux,taux; + cv::solvePnP(m_markerCorners3d, m.points, camMatrix, distCoeff,raux,taux); + raux.convertTo(Rvec,CV_32F); + taux.convertTo(Tvec ,CV_32F); + + cv::Mat_ rotMat(3,3); + cv::Rodrigues(Rvec, rotMat); + + // Copy to transformation matrix + for (int col=0; col<3; col++) + { + for (int row=0; row<3; row++) + { + m.transformation.r().mat[row][col] = rotMat(row,col); // Copy rotation component + } + m.transformation.t().data[col] = Tvec(col); // Copy translation component + } + + // Since solvePnP finds camera location, w.r.t to marker pose, to get marker pose w.r.t to the camera we invert it. + m.transformation = m.transformation.getInverted(); + } +} diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.hpp old mode 100755 new mode 100644 index a2b884d..0b908f4 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/MarkerDetector.hpp @@ -1,74 +1,91 @@ -/***************************************************************************** -* MarkerDetector.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_MarkerDetector_hpp -#define Example_MarkerBasedAR_MarkerDetector_hpp - -//////////////////////////////////////////////////////////////////// -// Standard includes: -#include -#include - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "BGRAVideoFrame.h" -#include "CameraCalibration.hpp" -#include "MarkerDetectionFacade.hpp" - -//////////////////////////////////////////////////////////////////// -// Forward declaration: -class Marker; - -/** - * A top-level class incapsulating marker detector algorithm - */ -class MarkerDetector : public MarkerDetectionFacade -{ -public: - - /** - * Initialize a new instance of marker detector object - * @calibration[in] - Camera calibration (intrinsic and distorsion components) necessary for pose estimation. - */ - MarkerDetector(CameraCalibration calibration); - - void processFrame(const BGRAVideoFrame& frame); - - - const std::vector& getTransformations() const; - -protected: - bool findMarkers(const BGRAVideoFrame& frame, std::vector& detectedMarkers); - - void prepareImage(const cv::Mat& bgraMat, cv::Mat& grayscale); - void performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg); - void findContours(const cv::Mat& thresholdImg, std::vector >& contours,int minContourPointsAllowed); - void findMarkerCandidates(const std::vector >& contours, std::vector& detectedMarkers); - void detectMarkers(const cv::Mat& grayscale, std::vector& detectedMarkers); - void estimatePosition(std::vector& detectedMarkers); - -private: - float m_minContourLengthAllowed; - - cv::Size markerSize; - cv::Mat camMatrix; - cv::Mat distCoeff; - std::vector m_transformations; - - cv::Mat m_grayscaleImage; - cv::Mat m_thresholdImg; - std::vector > m_contours; - std::vector m_markerCorners3d; - std::vector m_markerCorners2d; -}; - -#endif +/***************************************************************************** +* MarkerDetector.hpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_MarkerDetector_hpp +#define Example_MarkerBasedAR_MarkerDetector_hpp + +//////////////////////////////////////////////////////////////////// +// Standard includes: +#include +#include + +//////////////////////////////////////////////////////////////////// +// File includes: +#include "BGRAVideoFrame.h" +#include "CameraCalibration.hpp" + +//////////////////////////////////////////////////////////////////// +// Forward declaration: +class Marker; + +/** + * A top-level class that encapsulate marker detector algorithm + */ +class MarkerDetector +{ +public: + typedef std::vector PointsVector; + typedef std::vector ContoursVector; + + + /** + * Initialize a new instance of marker detector object + * @calibration[in] - Camera calibration (intrinsic and distortion components) necessary for pose estimation. + */ + MarkerDetector(CameraCalibration calibration); + + //! Searches for markes and fills the list of transformation for found markers + void processFrame(const BGRAVideoFrame& frame); + + const std::vector& getTransformations() const; + +protected: + + //! Main marker detection routine + bool findMarkers(const BGRAVideoFrame& frame, std::vector& detectedMarkers); + + //! Converts image to grayscale + void prepareImage(const cv::Mat& bgraMat, cv::Mat& grayscale) const; + + //! Performs binary threshold + void performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg) const; + + //! Detects appropriate contours + void findContours(cv::Mat& thresholdImg, ContoursVector& contours, int minContourPointsAllowed) const; + + //! Finds marker candidates among all contours + void findCandidates(const ContoursVector& contours, std::vector& detectedMarkers); + + //! Tries to recognize markers by detecting marker code + void recognizeMarkers(const cv::Mat& grayscale, std::vector& detectedMarkers); + + //! Calculates marker poses in 3D + void estimatePosition(std::vector& detectedMarkers); + +private: + float m_minContourLengthAllowed; + + cv::Size markerSize; + cv::Mat camMatrix; + cv::Mat distCoeff; + std::vector m_transformations; + + cv::Mat m_grayscaleImage; + cv::Mat m_thresholdImg; + cv::Mat canonicalMarkerImage; + + ContoursVector m_contours; + std::vector m_markerCorners3d; + std::vector m_markerCorners2d; +}; + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.h old mode 100755 new mode 100644 index 0c77684..a39e5ed --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.h @@ -1,35 +1,36 @@ -/***************************************************************************** -* SimpleVisualizationController.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import -#import "VisualizationController.h" - -//////////////////////////////////////////////////////////////////// -// File includes: -#import "EAGLView.h" - -@interface SimpleVisualizationController : NSObject -{ - EAGLView * m_glview; - GLuint m_backgroundTextureId; - std::vector m_transformations; - CameraCalibration m_calibration; - CGSize m_frameSize; -} - --(id) initWithGLView:(EAGLView*)view calibration:(CameraCalibration) calibration frameSize:(CGSize) size; - --(void) drawFrame; --(void) updateBackground:(BGRAVideoFrame) frame; --(void) setTransformationList:(const std::vector&) transformations; - -@end +/***************************************************************************** +* SimpleVisualizationController.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +//////////////////////////////////////////////////////////////////// +// File includes: +#import "EAGLView.h" +#import "CameraCalibration.hpp" +#import "BGRAVideoFrame.h" + +@interface SimpleVisualizationController : NSObject +{ + EAGLView * m_glview; + GLuint m_backgroundTextureId; + std::vector m_transformations; + CameraCalibration m_calibration; + CGSize m_frameSize; +} + +-(id) initWithGLView:(EAGLView*)view calibration:(CameraCalibration) calibration frameSize:(CGSize) size; + +-(void) drawFrame; +-(void) updateBackground:(BGRAVideoFrame) frame; +-(void) setTransformationList:(const std::vector&) transformations; + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.mm b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.mm old mode 100755 new mode 100644 index 6a67965..2da0544 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.mm +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/SimpleVisualizationController.mm @@ -1,248 +1,252 @@ -/***************************************************************************** -* SimpleVisualizationController.mm -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import "SimpleVisualizationController.h" -#import -#import -#import -#import -#import - -@implementation SimpleVisualizationController - --(id) initWithGLView:(EAGLView*)view calibration:(CameraCalibration) calibration frameSize:(CGSize) size; -{ - if ((self = [super init])) - { - m_glview = view; - - glGenTextures(1, &m_backgroundTextureId); - glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - // This is necessary for non-power-of-two textures - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glEnable(GL_DEPTH_TEST); - m_calibration = calibration; - m_frameSize = size; - } - - return self; -} - --(void) updateBackground:(BGRAVideoFrame) frame -{ - [m_glview setFramebuffer]; - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, frame.width, frame.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, frame.data); - - int glErCode = glGetError(); - if (glErCode != GL_NO_ERROR) - { - std::cout << glErCode << std::endl; - } -} - --(void) setTransformationList:(const std::vector&) transformations -{ - m_transformations = transformations; -} - -- (void)buildProjectionMatrix:(Matrix33)cameraMatrix: (int)screen_width: (int)screen_height: (Matrix44&) projectionMatrix -{ - float near = 0.01; // Near clipping distance - float far = 100; // Far clipping distance - - // Camera parameters - float f_x = cameraMatrix.data[0]; // Focal length in x axis - float f_y = cameraMatrix.data[4]; // Focal length in y axis (usually the same?) - float c_x = cameraMatrix.data[2]; // Camera primary point x - float c_y = cameraMatrix.data[5]; // Camera primary point y - - projectionMatrix.data[0] = - 2.0 * f_x / screen_width; - projectionMatrix.data[1] = 0.0; - projectionMatrix.data[2] = 0.0; - projectionMatrix.data[3] = 0.0; - - projectionMatrix.data[4] = 0.0; - projectionMatrix.data[5] = 2.0 * f_y / screen_height; - projectionMatrix.data[6] = 0.0; - projectionMatrix.data[7] = 0.0; - - projectionMatrix.data[8] = 2.0 * c_x / screen_width - 1.0; - projectionMatrix.data[9] = 2.0 * c_y / screen_height - 1.0; - projectionMatrix.data[10] = -( far+near ) / ( far - near ); - projectionMatrix.data[11] = -1.0; - - projectionMatrix.data[12] = 0.0; - projectionMatrix.data[13] = 0.0; - projectionMatrix.data[14] = -2.0 * far * near / ( far - near ); - projectionMatrix.data[15] = 0.0; -} - -- (void) drawBackground -{ - GLfloat w = m_glview.bounds.size.width; - GLfloat h = m_glview.bounds.size.height; - - const GLfloat squareVertices[] = - { - 0, 0, - w, 0, - 0, h, - w, h - }; - - static const GLfloat textureVertices[] = - { - 1, 0, - 1, 1, - 0, 0, - 0, 1 - }; - - static const GLfloat proj[] = - { - 0, -2.f/w, 0, 0, - -2.f/h, 0, 0, 0, - 0, 0, 1, 0, - 1, 1, 0, 1 - }; - - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(proj); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - glDisable(GL_COLOR_MATERIAL); - - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); - - // Update attribute values. - glVertexPointer(2, GL_FLOAT, 0, squareVertices); - glEnableClientState(GL_VERTEX_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0, textureVertices); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glColor4f(1,1,1,1); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); -} - -- (void) drawAR -{ - Matrix44 projectionMatrix; - [self buildProjectionMatrix:m_calibration.getIntrinsic():m_frameSize.width :m_frameSize.height :projectionMatrix]; - - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(projectionMatrix.data); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - glPushMatrix(); - glLineWidth(3.0f); - - float lineX[] = {0,0,0,1,0,0}; - float lineY[] = {0,0,0,0,1,0}; - float lineZ[] = {0,0,0,0,0,1}; - - const GLfloat squareVertices[] = { - -0.5f, -0.5f, - 0.5f, -0.5f, - -0.5f, 0.5f, - 0.5f, 0.5f, - }; - const GLubyte squareColors[] = { - 255, 255, 0, 255, - 0, 255, 255, 255, - 0, 0, 0, 0, - 255, 0, 255, 255, - }; - - for (size_t transformationIndex=0; transformationIndex(&glMatrix.data[0])); - - // draw data - glVertexPointer(2, GL_FLOAT, 0, squareVertices); - glEnableClientState(GL_VERTEX_ARRAY); - glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); - glEnableClientState(GL_COLOR_ARRAY); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glDisableClientState(GL_COLOR_ARRAY); - - float scale = 0.5; - glScalef(scale, scale, scale); - - glColor4f(1.0f, 0.0f, 0.0f, 1.0f); - glVertexPointer(3, GL_FLOAT, 0, lineX); - glDrawArrays(GL_LINES, 0, 2); - - glColor4f(0.0f, 1.0f, 0.0f, 1.0f); - glVertexPointer(3, GL_FLOAT, 0, lineY); - glDrawArrays(GL_LINES, 0, 2); - - glColor4f(0.0f, 0.0f, 1.0f, 1.0f); - glVertexPointer(3, GL_FLOAT, 0, lineZ); - glDrawArrays(GL_LINES, 0, 2); - } - - glPopMatrix(); - glDisableClientState(GL_VERTEX_ARRAY); -} - -- (void)drawFrame -{ - // Set the active framebuffer - [m_glview setFramebuffer]; - - // Draw a video on the background - [self drawBackground]; - - // Draw 3D objects on the position of the detected markers - [self drawAR]; - - // Present framebuffer - bool ok = [m_glview presentFramebuffer]; - - int glErCode = glGetError(); - if (!ok || glErCode != GL_NO_ERROR) - { - std::cerr << "GL error detected. Error code:" << glErCode << std::endl; - } -} - -@end - -id createVisualizationController(EAGLView * view, CameraCalibration c, CGSize size) -{ - return [[SimpleVisualizationController alloc] initWithGLView:view calibration:c frameSize:size]; -} \ No newline at end of file +/***************************************************************************** + * SimpleVisualizationController.mm + * Example_MarkerBasedAR + ****************************************************************************** + * by Khvedchenia Ievgen, 5th Dec 2012 + * http://computer-vision-talks.com + ****************************************************************************** + * Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" + * Copyright Packt Publishing 2012. + * http://www.packtpub.com/cool-projects-with-opencv/book + *****************************************************************************/ + +#import "SimpleVisualizationController.h" +#import +#import +#import +#import +#import + +@implementation SimpleVisualizationController + +-(id) initWithGLView:(EAGLView*)view calibration:(CameraCalibration) calibration frameSize:(CGSize) size; +{ + if ((self = [super init])) + { + m_glview = view; + + glGenTextures(1, &m_backgroundTextureId); + glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + // This is necessary for non-power-of-two textures + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glEnable(GL_DEPTH_TEST); + m_calibration = calibration; + m_frameSize = size; + } + + return self; +} + +-(void) updateBackground:(BGRAVideoFrame) frame +{ + [m_glview setFramebuffer]; + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, frame.width, frame.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, frame.data); + + int glErCode = glGetError(); + if (glErCode != GL_NO_ERROR) + { + std::cout << glErCode << std::endl; + } +} + +-(void) setTransformationList:(const std::vector&) transformations +{ + m_transformations = transformations; +} + +- (void)buildProjectionMatrix:(Matrix33)cameraMatrix: (int)screen_width: (int)screen_height: (Matrix44&) projectionMatrix +{ + float near = 0.01; // Near clipping distance + float far = 100; // Far clipping distance + + // Camera parameters + float f_x = cameraMatrix.data[0]; // Focal length in x axis + float f_y = cameraMatrix.data[4]; // Focal length in y axis (usually the same?) + float c_x = cameraMatrix.data[2]; // Camera primary point x + float c_y = cameraMatrix.data[5]; // Camera primary point y + + projectionMatrix.data[0] = - 2.0 * f_x / screen_width; + projectionMatrix.data[1] = 0.0; + projectionMatrix.data[2] = 0.0; + projectionMatrix.data[3] = 0.0; + + projectionMatrix.data[4] = 0.0; + projectionMatrix.data[5] = 2.0 * f_y / screen_height; + projectionMatrix.data[6] = 0.0; + projectionMatrix.data[7] = 0.0; + + projectionMatrix.data[8] = 2.0 * c_x / screen_width - 1.0; + projectionMatrix.data[9] = 2.0 * c_y / screen_height - 1.0; + projectionMatrix.data[10] = -( far+near ) / ( far - near ); + projectionMatrix.data[11] = -1.0; + + projectionMatrix.data[12] = 0.0; + projectionMatrix.data[13] = 0.0; + projectionMatrix.data[14] = -2.0 * far * near / ( far - near ); + projectionMatrix.data[15] = 0.0; +} + +- (void) drawBackground +{ + GLfloat w = m_glview.bounds.size.width; + GLfloat h = m_glview.bounds.size.height; + + const GLfloat squareVertices[] = + { + 0, 0, + w, 0, + 0, h, + w, h + }; + + static const GLfloat textureVertices[] = + { + 1, 0, + 1, 1, + 0, 0, + 0, 1 + }; + + static const GLfloat proj[] = + { + 0, -2.f/w, 0, 0, + -2.f/h, 0, 0, 0, + 0, 0, 1, 0, + 1, 1, 0, 1 + }; + + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(proj); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glDepthMask(FALSE); + glDisable(GL_COLOR_MATERIAL); + + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, m_backgroundTextureId); + + // Update attribute values. + glVertexPointer(2, GL_FLOAT, 0, squareVertices); + glEnableClientState(GL_VERTEX_ARRAY); + glTexCoordPointer(2, GL_FLOAT, 0, textureVertices); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + + glColor4f(1,1,1,1); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisable(GL_TEXTURE_2D); +} + +- (void) drawAR +{ + Matrix44 projectionMatrix; + [self buildProjectionMatrix:m_calibration.getIntrinsic():m_frameSize.width :m_frameSize.height :projectionMatrix]; + + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(projectionMatrix.data); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glDepthMask(TRUE); + glEnable(GL_DEPTH_TEST); + //glDepthFunc(GL_LESS); + //glDepthFunc(GL_GREATER); + + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + + glPushMatrix(); + glLineWidth(3.0f); + + float lineX[] = {0,0,0,1,0,0}; + float lineY[] = {0,0,0,0,1,0}; + float lineZ[] = {0,0,0,0,0,1}; + + const GLfloat squareVertices[] = { + -0.5f, -0.5f, + 0.5f, -0.5f, + -0.5f, 0.5f, + 0.5f, 0.5f, + }; + const GLubyte squareColors[] = { + 255, 255, 0, 255, + 0, 255, 255, 255, + 0, 0, 0, 0, + 255, 0, 255, 255, + }; + + for (size_t transformationIndex=0; transformationIndex(&glMatrix.data[0])); + + // draw data + glVertexPointer(2, GL_FLOAT, 0, squareVertices); + glEnableClientState(GL_VERTEX_ARRAY); + glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); + glEnableClientState(GL_COLOR_ARRAY); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glDisableClientState(GL_COLOR_ARRAY); + + float scale = 0.5; + glScalef(scale, scale, scale); + + glTranslatef(0, 0, 0.1f); + + glColor4f(1.0f, 0.0f, 0.0f, 1.0f); + glVertexPointer(3, GL_FLOAT, 0, lineX); + glDrawArrays(GL_LINES, 0, 2); + + glColor4f(0.0f, 1.0f, 0.0f, 1.0f); + glVertexPointer(3, GL_FLOAT, 0, lineY); + glDrawArrays(GL_LINES, 0, 2); + + glColor4f(0.0f, 0.0f, 1.0f, 1.0f); + glVertexPointer(3, GL_FLOAT, 0, lineZ); + glDrawArrays(GL_LINES, 0, 2); + } + + glPopMatrix(); + glDisableClientState(GL_VERTEX_ARRAY); +} + +- (void)drawFrame +{ + // Set the active framebuffer + [m_glview setFramebuffer]; + + // Draw a video on the background + [self drawBackground]; + + // Draw 3D objects on the position of the detected markers + [self drawAR]; + + // Present framebuffer + bool ok = [m_glview presentFramebuffer]; + + int glErCode = glGetError(); + if (!ok || glErCode != GL_NO_ERROR) + { + std::cerr << "GL error detected. Error code:" << glErCode << std::endl; + } +} + +@end + diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.cpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.cpp old mode 100755 new mode 100644 index 645f7a0..3b7c31f --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.cpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.cpp @@ -1,40 +1,40 @@ -/***************************************************************************** -* TinyLA.cpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#include "TinyLA.hpp" - -float perimeter(const std::vector &a) -{ - float sum=0, dx, dy; - - for (size_t i=0;i &b) -{ - for (size_t i=0;i0) return true; - } - return false; -} +/***************************************************************************** +* TinyLA.cpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#include "TinyLA.hpp" + +float perimeter(const std::vector &a) +{ + float sum=0, dx, dy; + + for (size_t i=0;i &b) +{ + for (size_t i=0;i0) return true; + } + return false; +} diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.hpp old mode 100755 new mode 100644 index a8778b1..98880b3 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/TinyLA.hpp @@ -1,23 +1,23 @@ -/***************************************************************************** -* TinyLA.hpp -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#ifndef Example_MarkerBasedAR_TinyLA_hpp -#define Example_MarkerBasedAR_TinyLA_hpp - -#include -#include - -float perimeter(const std::vector &a); - -bool isInto(cv::Mat &contour, std::vector &b); - -#endif +/***************************************************************************** +* TinyLA.hpp +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#ifndef Example_MarkerBasedAR_TinyLA_hpp +#define Example_MarkerBasedAR_TinyLA_hpp + +#include +#include + +float perimeter(const std::vector &a); + +bool isInto(cv::Mat &contour, std::vector &b); + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.h old mode 100755 new mode 100644 index 7bf30c8..7e3d8f4 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.h @@ -1,41 +1,41 @@ -/***************************************************************************** -* VideoSource.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import -#import -#import - -//////////////////////////////////////////////////////////////////// -// File includes: -#include "BGRAVideoFrame.h" -#include "CameraCalibration.hpp" - -@protocol VideoSourceDelegate - --(void)frameReady:(BGRAVideoFrame) frame; - -@end - -@interface VideoSource : NSObject -{ - -} - -@property (nonatomic, retain) AVCaptureSession * captureSession; -@property (nonatomic, retain) AVCaptureDeviceInput * deviceInput; -@property (nonatomic, retain) id delegate; - -- (bool) startWithDevicePosition:(AVCaptureDevicePosition)devicePosition; -- (CameraCalibration) getCalibration; -- (CGSize) getFrameSize; - +/***************************************************************************** +* VideoSource.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import +#import +#import + +//////////////////////////////////////////////////////////////////// +// File includes: +#include "BGRAVideoFrame.h" +#include "CameraCalibration.hpp" + +@protocol VideoSourceDelegate + +-(void)frameReady:(BGRAVideoFrame) frame; + +@end + +@interface VideoSource : NSObject +{ + +} + +@property (nonatomic, retain) AVCaptureSession * captureSession; +@property (nonatomic, retain) AVCaptureDeviceInput * deviceInput; +@property (nonatomic, retain) id delegate; + +- (bool) startWithDevicePosition:(AVCaptureDevicePosition)devicePosition; +- (CameraCalibration) getCalibration; +- (CGSize) getFrameSize; + @end \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.mm b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.mm old mode 100755 new mode 100644 index d476fc9..2fe6b1a --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.mm +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VideoSource.mm @@ -1,196 +1,197 @@ -/***************************************************************************** -* VideoSource.mm -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import -#import -#import - -//////////////////////////////////////////////////////////////////// -// File includes: -#import "VideoSource.h" - -@implementation VideoSource - -@synthesize captureSession; -@synthesize delegate; -@synthesize deviceInput; - -#pragma mark - Memory management - -- (id)init -{ - if ((self = [super init])) - { - AVCaptureSession * capSession = [[AVCaptureSession alloc] init]; - - if ([capSession canSetSessionPreset:AVCaptureSessionPreset640x480]) - { - [capSession setSessionPreset:AVCaptureSessionPreset640x480]; - NSLog(@"Set capture session preset AVCaptureSessionPreset640x480"); - } - else if ([capSession canSetSessionPreset:AVCaptureSessionPresetLow]) - { - [capSession setSessionPreset:AVCaptureSessionPresetLow]; - NSLog(@"Set capture session preset AVCaptureSessionPresetLow"); - } - - self.captureSession = capSession; - } - return self; -} - -- (CameraCalibration) getCalibration -{ - return CameraCalibration(6.24860291e+02 * (640./352.), 6.24860291e+02 * (480./288.), 640 * 0.5f, 480 * 0.5f); - //return CameraCalibration(6.24860291e+02, 6.24860291e+02, 352 * 0.5f, 288 * 0.5f); -} - -- (CGSize) getFrameSize -{ - if (![captureSession isRunning]) - NSLog(@"Capture session is not running, getFrameSize will return invalid valies"); - - NSArray *ports = [deviceInput ports]; - AVCaptureInputPort *usePort = nil; - for ( AVCaptureInputPort *port in ports ) - { - if ( usePort == nil || [port.mediaType isEqualToString:AVMediaTypeVideo] ) - { - usePort = port; - } - } - - if ( usePort == nil ) return CGSizeZero; - - CMFormatDescriptionRef format = [usePort formatDescription]; - CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(format); - - CGSize cameraSize = CGSizeMake(dim.width, dim.height); - - return cameraSize; -} - -- (void)dealloc -{ - [self.captureSession stopRunning]; - - self.captureSession = nil; -} - -#pragma mark Capture Session Configuration - -- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position -{ - NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; - for (AVCaptureDevice *device in devices) - { - if ([device position] == position) - { - return device; - } - } - return nil; -} - -- (void) addRawViewOutput -{ - /*We setupt the output*/ - AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init]; - - /*While a frame is processes in -captureOutput:didOutputSampleBuffer:fromConnection: delegate methods no other frames are added in the queue. - If you don't want this behaviour set the property to NO */ - captureOutput.alwaysDiscardsLateVideoFrames = YES; - - /*We specify a minimum duration for each frame (play with this settings to avoid having too many frames waiting - in the queue because it can cause memory issues). It is similar to the inverse of the maximum framerate. - In this example we set a min frame duration of 1/10 seconds so a maximum framerate of 10fps. We say that - we are not able to process more than 10 frames per second.*/ - //captureOutput.minFrameDuration = CMTimeMake(1, 10); - - /*We create a serial queue to handle the processing of our frames*/ - dispatch_queue_t queue; - queue = dispatch_queue_create("com.Example_MarkerBasedAR.cameraQueue", NULL); - [captureOutput setSampleBufferDelegate:self queue:queue]; - dispatch_release(queue); - - // Set the video output to store frame in BGRA (It is supposed to be faster) - NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; - NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; - NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; - [captureOutput setVideoSettings:videoSettings]; - - // Register an output - [self.captureSession addOutput:captureOutput]; -} - -- (bool) startWithDevicePosition:(AVCaptureDevicePosition)devicePosition -{ - AVCaptureDevice *videoDevice = [self cameraWithPosition:devicePosition]; - - if (!videoDevice) - return FALSE; - - { - NSError *error; - - AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error]; - self.deviceInput = videoIn; - - if (!error) - { - if ([[self captureSession] canAddInput:videoIn]) - { - [[self captureSession] addInput:videoIn]; - } - else - { - NSLog(@"Couldn't add video input"); - return FALSE; - } - } - else - { - NSLog(@"Couldn't create video input"); - return FALSE; - } - } - - [self addRawViewOutput]; - [captureSession startRunning]; - return TRUE; -} - -#pragma mark - -#pragma mark AVCaptureSession delegate -- (void)captureOutput:(AVCaptureOutput *)captureOutput -didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection -{ - CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); - - /*Lock the image buffer*/ - CVPixelBufferLockBaseAddress(imageBuffer,0); - - /*Get information about the image*/ - uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); - size_t width = CVPixelBufferGetWidth(imageBuffer); - size_t height = CVPixelBufferGetHeight(imageBuffer); - size_t stride = CVPixelBufferGetBytesPerRow(imageBuffer); - - BGRAVideoFrame frame = {width, height, stride, baseAddress}; - [delegate frameReady:frame]; - - /*We unlock the image buffer*/ - CVPixelBufferUnlockBaseAddress(imageBuffer,0); -} - +/***************************************************************************** +* VideoSource.mm +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import +#import +#import + +//////////////////////////////////////////////////////////////////// +// File includes: +#import "VideoSource.h" + +@implementation VideoSource + +@synthesize captureSession; +@synthesize delegate; +@synthesize deviceInput; + +#pragma mark - Memory management + +- (id)init +{ + if ((self = [super init])) + { + AVCaptureSession * capSession = [[AVCaptureSession alloc] init]; + + if ([capSession canSetSessionPreset:AVCaptureSessionPreset640x480]) + { + [capSession setSessionPreset:AVCaptureSessionPreset640x480]; + NSLog(@"Set capture session preset AVCaptureSessionPreset640x480"); + } + else if ([capSession canSetSessionPreset:AVCaptureSessionPresetLow]) + { + [capSession setSessionPreset:AVCaptureSessionPresetLow]; + NSLog(@"Set capture session preset AVCaptureSessionPresetLow"); + } + + self.captureSession = capSession; + } + return self; +} + +- (CameraCalibration) getCalibration +{ + // Returns calibratoin data for iPad 2 + // Todo: Add parameters for the rest + return CameraCalibration(6.24860291e+02 * (640./352.), 6.24860291e+02 * (480./288.), 640 * 0.5f, 480 * 0.5f); +} + +- (CGSize) getFrameSize +{ + if (![captureSession isRunning]) + NSLog(@"Capture session is not running, getFrameSize will return invalid valies"); + + NSArray *ports = [deviceInput ports]; + AVCaptureInputPort *usePort = nil; + for ( AVCaptureInputPort *port in ports ) + { + if ( usePort == nil || [port.mediaType isEqualToString:AVMediaTypeVideo] ) + { + usePort = port; + } + } + + if ( usePort == nil ) return CGSizeZero; + + CMFormatDescriptionRef format = [usePort formatDescription]; + CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(format); + + CGSize cameraSize = CGSizeMake(dim.width, dim.height); + + return cameraSize; +} + +- (void)dealloc +{ + [self.captureSession stopRunning]; + + self.captureSession = nil; +} + +#pragma mark Capture Session Configuration + +- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position +{ + NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; + for (AVCaptureDevice *device in devices) + { + if ([device position] == position) + { + return device; + } + } + return nil; +} + +- (void) addRawViewOutput +{ + /*We setupt the output*/ + AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init]; + + /*While a frame is processes in -captureOutput:didOutputSampleBuffer:fromConnection: delegate methods no other frames are added in the queue. + If you don't want this behaviour set the property to NO */ + captureOutput.alwaysDiscardsLateVideoFrames = YES; + + /*We specify a minimum duration for each frame (play with this settings to avoid having too many frames waiting + in the queue because it can cause memory issues). It is similar to the inverse of the maximum framerate. + In this example we set a min frame duration of 1/10 seconds so a maximum framerate of 10fps. We say that + we are not able to process more than 10 frames per second.*/ + //captureOutput.minFrameDuration = CMTimeMake(1, 10); + + /*We create a serial queue to handle the processing of our frames*/ + dispatch_queue_t queue; + queue = dispatch_queue_create("com.Example_MarkerBasedAR.cameraQueue", NULL); + [captureOutput setSampleBufferDelegate:self queue:queue]; + dispatch_release(queue); + + // Set the video output to store frame in BGRA (It is supposed to be faster) + NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; + NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; + NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; + [captureOutput setVideoSettings:videoSettings]; + + // Register an output + [self.captureSession addOutput:captureOutput]; +} + +- (bool) startWithDevicePosition:(AVCaptureDevicePosition)devicePosition +{ + AVCaptureDevice *videoDevice = [self cameraWithPosition:devicePosition]; + + if (!videoDevice) + return FALSE; + + { + NSError *error; + + AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error]; + self.deviceInput = videoIn; + + if (nil != videoIn) + { + if ([[self captureSession] canAddInput:videoIn]) + { + [[self captureSession] addInput:videoIn]; + } + else + { + NSLog(@"Couldn't add video input"); + return FALSE; + } + } + else + { + NSLog(@"Couldn't create video input: %@", [error localizedDescription]); + return FALSE; + } + } + + [self addRawViewOutput]; + [captureSession startRunning]; + return TRUE; +} + +#pragma mark - +#pragma mark AVCaptureSession delegate +- (void)captureOutput:(AVCaptureOutput *)captureOutput +didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection +{ + CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); + + /*Lock the image buffer*/ + CVPixelBufferLockBaseAddress(imageBuffer,0); + + /*Get information about the image*/ + uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); + size_t width = CVPixelBufferGetWidth(imageBuffer); + size_t height = CVPixelBufferGetHeight(imageBuffer); + size_t stride = CVPixelBufferGetBytesPerRow(imageBuffer); + + BGRAVideoFrame frame = {width, height, stride, baseAddress}; + [delegate frameReady:frame]; + + /*We unlock the image buffer*/ + CVPixelBufferUnlockBaseAddress(imageBuffer,0); +} + @end \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.h old mode 100755 new mode 100644 index d3ae416..1d36a7a --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.h @@ -1,29 +1,24 @@ -/***************************************************************************** -* ViewController.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import - -//////////////////////////////////////////////////////////////////// -// File includes: -#import "EAGLView.h" -#import "VideoSource.h" -#import "MarkerDetectionFacade.hpp" -#import "VisualizationController.h" - -@interface ViewController : UIViewController -{ - VideoSource * m_videoSource; - std::auto_ptr m_pipeline; - id m_renderer; -} -@property (weak, nonatomic) IBOutlet EAGLView *m_glview; -@end +/***************************************************************************** +* ViewController.h +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +//////////////////////////////////////////////////////////////////// +// File includes: +#import "EAGLView.h" + +@interface ViewController : UIViewController +{ +} + +@property (weak, nonatomic) IBOutlet EAGLView *glview; +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.mm b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.mm old mode 100755 new mode 100644 index d16b057..9f58ba9 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.mm +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/ViewController.mm @@ -1,75 +1,99 @@ -/***************************************************************************** -* ViewController.mm -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -// File includes: -#import "ViewController.h" - -@implementation ViewController -@synthesize m_glview; - -#pragma mark - View lifecycle - -- (void)viewDidLoad -{ - [super viewDidLoad]; - - // Do any additional setup after loading the view, typically from a nib. - m_videoSource = [[VideoSource alloc]init]; - m_videoSource.delegate = self; - - m_pipeline = createMarkerDetection([m_videoSource getCalibration]); - [m_videoSource startWithDevicePosition:AVCaptureDevicePositionBack]; -} - -- (void)viewDidUnload -{ - [self setM_glview:nil]; - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - -- (void)viewWillAppear:(BOOL)animated -{ - [m_glview initContext]; - - CGSize frameSize = [m_videoSource getFrameSize]; - m_renderer = createVisualizationController(m_glview, [m_videoSource getCalibration], frameSize); - - [super viewWillAppear:animated]; -} - -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation -{ - return interfaceOrientation == UIInterfaceOrientationLandscapeRight; - //return interfaceOrientation == UIInterfaceOrientationPortrait; -} - -#pragma mark - VideoSourceDelegate --(void)frameReady:(BGRAVideoFrame) frame -{ - // Start upload new frame to video memory in main thread - dispatch_async( dispatch_get_main_queue(), ^{ - [m_renderer updateBackground:frame]; - }); - - // And perform processing in current thread - m_pipeline->processFrame(frame); - - // When it's done we query rendering from main thread - dispatch_async( dispatch_get_main_queue(), ^{ - [m_renderer setTransformationList:(m_pipeline->getTransformations)()]; - [m_renderer drawFrame]; - }); -} - -@end +/***************************************************************************** + * ViewController.mm + * Example_MarkerBasedAR + ****************************************************************************** + * by Khvedchenia Ievgen, 5th Dec 2012 + * http://computer-vision-talks.com + ****************************************************************************** + * Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" + * Copyright Packt Publishing 2012. + * http://www.packtpub.com/cool-projects-with-opencv/book + *****************************************************************************/ + +//////////////////////////////////////////////////////////////////// +// File includes: +#import "ViewController.h" +#import "VideoSource.h" +#import "MarkerDetector.hpp" +#import "SimpleVisualizationController.h" + +@interface ViewController() + +@property (strong, nonatomic) VideoSource * videoSource; +@property (nonatomic) MarkerDetector * markerDetector; +@property (strong, nonatomic) SimpleVisualizationController * visualizationController; + +@end + +@implementation ViewController +@synthesize glview, videoSource, markerDetector, visualizationController; + +#pragma mark - View lifecycle + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + // Do any additional setup after loading the view, typically from a nib. + self.videoSource = [[VideoSource alloc] init]; + self.videoSource.delegate = self; + + self.markerDetector = new MarkerDetector([self.videoSource getCalibration]); + [self.videoSource startWithDevicePosition:AVCaptureDevicePositionBack]; +} + +- (void)viewDidUnload +{ + // Release any retained subviews of the main view. + [self setGlview:nil]; + [super viewDidUnload]; +} + +- (void)viewWillAppear:(BOOL)animated +{ + [self.glview initContext]; + + CGSize frameSize = [self.videoSource getFrameSize]; + CameraCalibration camCalib = [self.videoSource getCalibration]; + + self.visualizationController = [[SimpleVisualizationController alloc] initWithGLView:self.glview + calibration:camCalib + frameSize:frameSize]; + + [super viewWillAppear:animated]; +} + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation +{ + // Important notice: + // Since the logical interface orientation differs from coordinate system of video frame + // We force the interface orientation to landscape right for simplicity. + // This orientation has one-to-one coordinates mapping from frame buffer to view. + // So we don't have to worry about inconsistent AR. + return interfaceOrientation == UIInterfaceOrientationLandscapeRight; +} + +- (void) dealloc +{ + delete self.markerDetector; +} + +#pragma mark - VideoSourceDelegate +-(void)frameReady:(BGRAVideoFrame) frame +{ + // Start upload new frame to video memory in main thread + dispatch_sync( dispatch_get_main_queue(), ^{ + [self.visualizationController updateBackground:frame]; + }); + + // And perform processing in current thread + self.markerDetector->processFrame(frame); + + // When it's done we query rendering from main thread + dispatch_async( dispatch_get_main_queue(), ^{ + [self.visualizationController setTransformationList:(self.markerDetector->getTransformations)()]; + [self.visualizationController drawFrame]; + }); +} + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VisualizationController.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VisualizationController.h deleted file mode 100755 index 5db7495..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/VisualizationController.h +++ /dev/null @@ -1,30 +0,0 @@ -/***************************************************************************** -* VisualizationController.h -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -//////////////////////////////////////////////////////////////////// -// Standard includes: -#import -#import - -//////////////////////////////////////////////////////////////////// -// File includes: -#import "VideoSource.h" -#import "GeometryTypes.hpp" -#import "EAGLView.h" - -@protocol VisualizationController --(void) drawFrame; --(void) updateBackground:(BGRAVideoFrame) frame; --(void) setTransformationList:(const std::vector&) transformations; -@end - -id createVisualizationController(EAGLView * view, CameraCalibration calibration, CGSize size); \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/cube.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/cube.h old mode 100755 new mode 100644 diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/InfoPlist.strings b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/InfoPlist.strings old mode 100755 new mode 100644 diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPad.storyboard b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPad.storyboard old mode 100755 new mode 100644 index 2ac2457..9ca9b91 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPad.storyboard +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPad.storyboard @@ -1,8 +1,8 @@ - + - - + + @@ -11,21 +11,33 @@ - + + - + + + + + + + + + + + + - + \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPhone.storyboard b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPhone.storyboard old mode 100755 new mode 100644 index 4d3f944..cf139df --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPhone.storyboard +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/en.lproj/MainStoryboard_iPhone.storyboard @@ -1,8 +1,8 @@ - + - - + + @@ -16,7 +16,7 @@ - + @@ -29,7 +29,7 @@ - + diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/main.m b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/main.m old mode 100755 new mode 100644 index f9152e2..bd9d48b --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/main.m +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/Example_MarkerBasedAR/main.m @@ -1,22 +1,22 @@ -/***************************************************************************** -* main.mm -* Example_MarkerBasedAR -****************************************************************************** -* by Khvedchenia Ievgen, 5th Dec 2012 -* http://computer-vision-talks.com -****************************************************************************** -* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" -* Copyright Packt Publishing 2012. -* http://www.packtpub.com/cool-projects-with-opencv/book -*****************************************************************************/ - -#import - -#import "AppDelegate.h" - -int main(int argc, char *argv[]) -{ - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} +/***************************************************************************** +* main.mm +* Example_MarkerBasedAR +****************************************************************************** +* by Khvedchenia Ievgen, 5th Dec 2012 +* http://computer-vision-talks.com +****************************************************************************** +* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects" +* Copyright Packt Publishing 2012. +* http://www.packtpub.com/cool-projects-with-opencv/book +*****************************************************************************/ + +#import + +#import "AppDelegate.h" + +int main(int argc, char *argv[]) +{ + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/marker.png b/Chapter2_iPhoneAR/Example_MarkerBasedAR/marker.png new file mode 100644 index 0000000..0b75bb5 Binary files /dev/null and b/Chapter2_iPhoneAR/Example_MarkerBasedAR/marker.png differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.h deleted file mode 100755 index b15d068..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.h +++ /dev/null @@ -1,65 +0,0 @@ -/*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 __OPENCV_OLD_AUX_H__ -#define __OPENCV_OLD_AUX_H__ - -//#if defined(__GNUC__) -//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" -//#endif - -#include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" -#include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/video/tracking.hpp" -#include "opencv2/video/background_segm.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/objdetect/objdetect.hpp" -#include "opencv2/legacy/legacy.hpp" -#include "opencv2/legacy/compat.hpp" -#include "opencv2/legacy/blobtrack.hpp" -#include "opencv2/contrib/contrib.hpp" - -#endif - -/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.hpp deleted file mode 100755 index 952210b..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvaux.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/*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 __OPENCV_OLD_AUX_HPP__ -#define __OPENCV_OLD_AUX_HPP__ - -//#if defined(__GNUC__) -//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" -//#endif - -#include - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvwimage.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvwimage.h deleted file mode 100755 index f27cfc2..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cvwimage.h +++ /dev/null @@ -1,46 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// 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. -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2008, Google, 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 or contributors 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. - - -#ifndef __OPENCV_OLD_WIMAGE_HPP__ -#define __OPENCV_OLD_WIMAGE_HPP__ - -#include "opencv2/core/wimage.hpp" - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxmisc.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxmisc.h deleted file mode 100755 index 6446944..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxmisc.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef __OPENCV_OLD_CXMISC_H__ -#define __OPENCV_OLD_CXMISC_H__ - -#include "opencv2/core/internal.hpp" - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/highgui.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/highgui.h deleted file mode 100755 index 9725c9f..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/highgui.h +++ /dev/null @@ -1,50 +0,0 @@ -/*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 __OPENCV_OLD_HIGHGUI_H__ -#define __OPENCV_OLD_HIGHGUI_H__ - -#include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" -#include "opencv2/highgui/highgui_c.h" -#include "opencv2/highgui/highgui.hpp" - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/ml.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/ml.h deleted file mode 100755 index 0383a2f..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/ml.h +++ /dev/null @@ -1,48 +0,0 @@ -/*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 -// -// 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 __OPENCV_OLD_ML_H__ -#define __OPENCV_OLD_ML_H__ - -#include "opencv2/core/core_c.h" -#include "opencv2/core/core.hpp" -#include "opencv2/ml/ml.hpp" - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/retina.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/retina.hpp deleted file mode 100755 index 6d626c5..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/retina.hpp +++ /dev/null @@ -1,276 +0,0 @@ -/*#****************************************************************************** - ** 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. - ** - ** - ** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. - ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. - ** - ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) - ** - ** Creation - enhancement process 2007-2011 - ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France - ** - ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). - ** Refer to the following research paper for more information: - ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 - ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: - ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. - ** - ** The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : - ** _take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: - ** ====> B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 - ** _take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. - ** ====> more informations in the above cited Jeanny Heraults's book. - ** - ** License Agreement - ** For Open Source Computer Vision Library - ** - ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. - ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. - ** - ** For Human Visual System tools (hvstools) - ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, 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: - ** - ** * Redistributions of source code must retain the above copyright notice, - ** this list of conditions and the following disclaimer. - ** - ** * 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. - ** - ** * The name of the copyright holders 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. - *******************************************************************************/ - -#ifndef __OPENCV_CONTRIB_RETINA_HPP__ -#define __OPENCV_CONTRIB_RETINA_HPP__ - -/* - * Retina.hpp - * - * Created on: Jul 19, 2011 - * Author: Alexandre Benoit - */ - -#include "opencv2/core/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support -#include - -namespace cv -{ - -enum RETINA_COLORSAMPLINGMETHOD -{ - RETINA_COLOR_RANDOM, //!< each pixel position is either R, G or B in a random choice - RETINA_COLOR_DIAGONAL,//!< color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... - RETINA_COLOR_BAYER//!< standard bayer sampling -}; - -class RetinaFilter; - -/** - * @class Retina a wrapper class which allows the Gipsa/Listic Labs model to be used. - * This retina model allows spatio-temporal image processing (applied on still images, video sequences). - * As a summary, these are the retina model properties: - * => It applies a spectral whithening (mid-frequency details enhancement) - * => high frequency spatio-temporal noise reduction - * => low frequency luminance to be reduced (luminance range compression) - * => local logarithmic luminance compression allows details to be enhanced in low light conditions - * - * USE : this model can be used basically for spatio-temporal video effects but also for : - * _using the getParvo method output matrix : texture analysiswith enhanced signal to noise ratio and enhanced details robust against input images luminance ranges - * _using the getMagno method output matrix : motion analysis also with the previously cited properties - * - * for more information, reer to the following papers : - * Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 - * Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. - * - * The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : - * _take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: - * ====> B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 - * _take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. - * ====> more informations in the above cited Jeanny Heraults's book. - */ -class CV_EXPORTS Retina { - -public: - - /** - * Main constructor with most commun use setup : create an instance of color ready retina model - * @param inputSize : the input frame size - * @param parametersSaveFile : the filename of the xml file that records the default retina parameters setup, if empty, then, no default parameter file will be written - */ - Retina(Size inputSize, const std::string parametersSaveFile=""); - - /** - * Complete Retina filter constructor which allows all basic structural parameters definition - * @param inputSize : the input frame size - * @param parametersSaveFile : the filename of the xml file that records the default retina parameters setup, if empty, then, no default parameter file will be written - * @param colorMode : the chosen processing mode : with or without color processing - * @param colorSamplingMethod: specifies which kind of color sampling will be used - * @param useRetinaLogSampling: activate retina log sampling, if true, the 2 following parameters can be used - * @param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak - * @param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied - */ - Retina(Size inputSize, const std::string parametersSaveFile, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); - - virtual ~Retina(); - - /** - * try to open an XML retina parameters file to adjust current retina instance setup - * => if the xml file does not exist, then default setup is applied - * => warning, Exceptions are thrown if read XML file is not valid - * @param retinaParameterFile : the parameters filename - * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error - */ - void setup(std::string retinaParameterFile="", const bool applyDefaultSetupOnFailure=true); - - /** - * parameters setup display method - * @return a string which contains formatted parameters information - */ - const std::string printSetup(); - - /** - * setup the OPL and IPL parvo channels (see biologocal model) - * OPL is referred as Outer Plexiform Layer of the retina, it allows the spatio-temporal filtering which withens the spectrum and reduces spatio-temporal noise while attenuating global luminance (low frequency energy) - * IPL parvo is the OPL next processing stage, it refers to Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision. - * for more informations, please have a look at the paper Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 - * @param colorMode : specifies if (true) color is processed of not (false) to then processing gray level image - * @param normaliseOutput : specifies if (true) output is rescaled between 0 and 255 of not (false) - * @param photoreceptorsLocalAdaptationSensitivity: the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases) - * @param photoreceptorsTemporalConstant: the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame - * @param photoreceptorsSpatialConstant: the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel - * @param horizontalCellsGain: gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0 - * @param HcellsTemporalConstant: the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors - * @param HcellsSpatialConstant: the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model) - * @param ganglionCellsSensitivity: the compression strengh of the ganglion cells local adaptation output, set a value between 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 230 - */ - void setupOPLandIPLParvoChannel(const bool colorMode=true, const bool normaliseOutput = true, const float photoreceptorsLocalAdaptationSensitivity=0.7, const float photoreceptorsTemporalConstant=0.5, const float photoreceptorsSpatialConstant=0.53, const float horizontalCellsGain=0, const float HcellsTemporalConstant=1, const float HcellsSpatialConstant=7, const float ganglionCellsSensitivity=0.7); - - /** - * set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel - * this channel processes signals outpint from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference paper for more details. - * @param normaliseOutput : specifies if (true) output is rescaled between 0 and 255 of not (false) - * @param parasolCells_beta: the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0 - * @param parasolCells_tau: the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response) - * @param parasolCells_k: the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5 - * @param amacrinCellsTemporalCutFrequency: the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, tipicall value is 5 - * @param V0CompressionParameter: the compression strengh of the ganglion cells local adaptation output, set a value between 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 200 - * @param localAdaptintegration_tau: specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation - * @param localAdaptintegration_k: specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation - */ - void setupIPLMagnoChannel(const bool normaliseOutput = true, const float parasolCells_beta=0, const float parasolCells_tau=0, const float parasolCells_k=7, const float amacrinCellsTemporalCutFrequency=1.2, const float V0CompressionParameter=0.95, const float localAdaptintegration_tau=0, const float localAdaptintegration_k=7); - - /** - * method which allows retina to be applied on an input image, after run, encapsulated retina module is ready to deliver its outputs using dedicated acccessors, see getParvo and getMagno methods - * @param inputImage : the input cv::Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits) - */ - void run(const Mat &inputImage); - - /** - * accessor of the details channel of the retina (models foveal vision) - * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV - */ - void getParvo(Mat &retinaOutput_parvo); - - /** - * accessor of the details channel of the retina (models foveal vision) - * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is the original retina filter model output, without any quantification or rescaling - */ - void getParvo(std::valarray &retinaOutput_parvo); - - /** - * accessor of the motion channel of the retina (models peripheral vision) - * @param retinaOutput_magno : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV - */ - void getMagno(Mat &retinaOutput_magno); - - /** - * accessor of the motion channel of the retina (models peripheral vision) - * @param retinaOutput_magno : the output buffer (reallocated if necessary), this output is the original retina filter model output, without any quantification or rescaling - */ - void getMagno(std::valarray &retinaOutput_magno); - - /** - * activate color saturation as the final step of the color demultiplexing process - * -> this saturation is a sigmoide function applied to each channel of the demultiplexed image. - * @param saturateColors: boolean that activates color saturation (if true) or desactivate (if false) - * @param colorSaturationValue: the saturation factor - */ - void setColorSaturation(const bool saturateColors=true, const float colorSaturationValue=4.0); - - /** - * clear all retina buffers (equivalent to opening the eyes after a long period of eye close ;o) - */ - void clearBuffers(); - - /** - * Activate/desactivate the Magnocellular pathway processing (motion information extraction), by default, it is activated - * @param activate: true if Magnocellular output should be activated, false if not - */ - void activateMovingContoursProcessing(const bool activate); - - /** - * Activate/desactivate the Parvocellular pathway processing (contours information extraction), by default, it is activated - * @param activate: true if Parvocellular (contours information extraction) output should be activated, false if not - */ - void activateContoursProcessing(const bool activate); - -protected: - // Parameteres setup members - FileStorage _parametersSaveFile; //!< parameters file ... saved on instance delete - std::string _parametersSaveFileName; //!< parameters file name - - // Retina model related modules - std::valarray _inputBuffer; //!< buffer used to convert input cv::Mat to internal retina buffers format (valarrays) - - // pointer to retina model - RetinaFilter* _retinaFilter; //!< the pointer to the retina module, allocated with instance construction - - /** - * exports a valarray buffer outing from HVStools objects to a cv::Mat in CV_8UC1 (gray level picture) or CV_8UC3 (color) format - * @param grayMatrixToConvert the valarray to export to OpenCV - * @param nbRows : the number of rows of the valarray flatten matrix - * @param nbColumns : the number of rows of the valarray flatten matrix - * @param colorMode : a flag which mentions if matrix is color (true) or graylevel (false) - * @param outBuffer : the output matrix which is reallocated to satisfy Retina output buffer dimensions - */ - void _convertValarrayBuffer2cvMat(const std::valarray &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, Mat &outBuffer); - - /** - * - * @param inputMatToConvert : the OpenCV cv::Mat that has to be converted to gray or RGB valarray buffer that will be processed by the retina model - * @param outputValarrayMatrix : the output valarray - * @return the input image color mode (color=true, gray levels=false) - */ - const bool _convertCvMat2ValarrayBuffer(const cv::Mat inputMatToConvert, std::valarray &outputValarrayMatrix); - - //! private method called by constructors, gathers their parameters and use them in a unified way - void _init(const std::string parametersSaveFileName, Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); - - -}; - -} -#endif /* __OPENCV_CONTRIB_RETINA_HPP__ */ - diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/features2d/features2d.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/features2d/features2d.hpp deleted file mode 100755 index 82c5c48..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/features2d/features2d.hpp +++ /dev/null @@ -1,3049 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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 __OPENCV_FEATURES_2D_HPP__ -#define __OPENCV_FEATURES_2D_HPP__ - -#include "opencv2/core/core.hpp" -#include "opencv2/flann/miniflann.hpp" - -#ifdef __cplusplus -#include - -extern "C" { -#endif - -typedef struct CvSURFPoint -{ - CvPoint2D32f pt; - - int laplacian; - int size; - float dir; - float hessian; - -} CvSURFPoint; - -CV_INLINE CvSURFPoint cvSURFPoint( CvPoint2D32f pt, int laplacian, - int size, float dir CV_DEFAULT(0), - float hessian CV_DEFAULT(0)) -{ - CvSURFPoint kp; - - kp.pt = pt; - kp.laplacian = laplacian; - kp.size = size; - kp.dir = dir; - kp.hessian = hessian; - - return kp; -} - -typedef struct CvSURFParams -{ - int extended; - int upright; - double hessianThreshold; - - int nOctaves; - int nOctaveLayers; - -} CvSURFParams; - -CVAPI(CvSURFParams) cvSURFParams( double hessianThreshold, int extended CV_DEFAULT(0) ); - -// If useProvidedKeyPts!=0, keypoints are not detected, but descriptors are computed -// at the locations provided in keypoints (a CvSeq of CvSURFPoint). -CVAPI(void) cvExtractSURF( const CvArr* img, const CvArr* mask, - CvSeq** keypoints, CvSeq** descriptors, - CvMemStorage* storage, CvSURFParams params, int useProvidedKeyPts CV_DEFAULT(0) ); - -/*! - Maximal Stable Regions Parameters -*/ -typedef struct CvMSERParams -{ - //! delta, in the code, it compares (size_{i}-size_{i-delta})/size_{i-delta} - int delta; - //! prune the area which bigger than maxArea - int maxArea; - //! prune the area which smaller than minArea - int minArea; - //! prune the area have simliar size to its children - float maxVariation; - //! trace back to cut off mser with diversity < min_diversity - float minDiversity; - - /////// the next few params for MSER of color image - - //! for color image, the evolution steps - int maxEvolution; - //! the area threshold to cause re-initialize - double areaThreshold; - //! ignore too small margin - double minMargin; - //! the aperture size for edge blur - int edgeBlurSize; -} CvMSERParams; - -CVAPI(CvMSERParams) cvMSERParams( int delta CV_DEFAULT(5), int min_area CV_DEFAULT(60), - int max_area CV_DEFAULT(14400), float max_variation CV_DEFAULT(.25f), - float min_diversity CV_DEFAULT(.2f), int max_evolution CV_DEFAULT(200), - double area_threshold CV_DEFAULT(1.01), - double min_margin CV_DEFAULT(.003), - int edge_blur_size CV_DEFAULT(5) ); - -// Extracts the contours of Maximally Stable Extremal Regions -CVAPI(void) cvExtractMSER( CvArr* _img, CvArr* _mask, CvSeq** contours, CvMemStorage* storage, CvMSERParams params ); - - -typedef struct CvStarKeypoint -{ - CvPoint pt; - int size; - float response; -} CvStarKeypoint; - -CV_INLINE CvStarKeypoint cvStarKeypoint(CvPoint pt, int size, float response) -{ - CvStarKeypoint kpt; - kpt.pt = pt; - kpt.size = size; - kpt.response = response; - return kpt; -} - -typedef struct CvStarDetectorParams -{ - int maxSize; - int responseThreshold; - int lineThresholdProjected; - int lineThresholdBinarized; - int suppressNonmaxSize; -} CvStarDetectorParams; - -CV_INLINE CvStarDetectorParams cvStarDetectorParams( - int maxSize CV_DEFAULT(45), - int responseThreshold CV_DEFAULT(30), - int lineThresholdProjected CV_DEFAULT(10), - int lineThresholdBinarized CV_DEFAULT(8), - int suppressNonmaxSize CV_DEFAULT(5)) -{ - CvStarDetectorParams params; - params.maxSize = maxSize; - params.responseThreshold = responseThreshold; - params.lineThresholdProjected = lineThresholdProjected; - params.lineThresholdBinarized = lineThresholdBinarized; - params.suppressNonmaxSize = suppressNonmaxSize; - - return params; -} - -CVAPI(CvSeq*) cvGetStarKeypoints( const CvArr* img, CvMemStorage* storage, - CvStarDetectorParams params CV_DEFAULT(cvStarDetectorParams())); - -#ifdef __cplusplus -} - -namespace cv -{ - struct CV_EXPORTS DefaultRngAuto - { - const uint64 old_state; - - DefaultRngAuto() : old_state(theRNG().state) { theRNG().state = (uint64)-1; } - ~DefaultRngAuto() { theRNG().state = old_state; } - - DefaultRngAuto& operator=(const DefaultRngAuto&); - }; - - -// CvAffinePose: defines a parameterized affine transformation of an image patch. -// An image patch is rotated on angle phi (in degrees), then scaled lambda1 times -// along horizontal and lambda2 times along vertical direction, and then rotated again -// on angle (theta - phi). -class CV_EXPORTS CvAffinePose -{ -public: - float phi; - float theta; - float lambda1; - float lambda2; -}; - -/*! - The Keypoint Class - - The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint detectors, such as - Harris corner detector, cv::FAST, cv::StarDetector, cv::SURF, cv::SIFT, cv::LDetector etc. - - The keypoint is characterized by the 2D position, scale - (proportional to the diameter of the neighborhood that needs to be taken into account), - orientation and some other parameters. The keypoint neighborhood is then analyzed by another algorithm that builds a descriptor - (usually represented as a feature vector). The keypoints representing the same object in different images can then be matched using - cv::KDTree or another method. -*/ -class CV_EXPORTS_W_SIMPLE KeyPoint -{ -public: - //! the default constructor - CV_WRAP KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} - //! the full constructor - KeyPoint(Point2f _pt, float _size, float _angle=-1, - float _response=0, int _octave=0, int _class_id=-1) - : pt(_pt), size(_size), angle(_angle), - response(_response), octave(_octave), class_id(_class_id) {} - //! another form of the full constructor - CV_WRAP KeyPoint(float x, float y, float _size, float _angle=-1, - float _response=0, int _octave=0, int _class_id=-1) - : pt(x, y), size(_size), angle(_angle), - response(_response), octave(_octave), class_id(_class_id) {} - - size_t hash() const; - - //! converts vector of keypoints to vector of points - static void convert(const std::vector& keypoints, - CV_OUT std::vector& points2f, - const std::vector& keypointIndexes=std::vector()); - //! converts vector of points to the vector of keypoints, where each keypoint is assigned the same size and the same orientation - static void convert(const std::vector& points2f, - CV_OUT std::vector& keypoints, - float size=1, float response=1, int octave=0, int class_id=-1); - - //! computes overlap for pair of keypoints; - //! overlap is a ratio between area of keypoint regions intersection and - //! area of keypoint regions union (now keypoint region is circle) - static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); - - CV_PROP_RW Point2f pt; //!< coordinates of the keypoints - CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood - CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable) - CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling - CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted - CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) -}; - -//! writes vector of keypoints to the file storage -CV_EXPORTS void write(FileStorage& fs, const string& name, const vector& keypoints); -//! reads vector of keypoints from the specified file storage node -CV_EXPORTS void read(const FileNode& node, CV_OUT vector& keypoints); - -/* - * A class filters a vector of keypoints. - * Because now it is difficult to provide a convenient interface for all usage scenarios of the keypoints filter class, - * it has only 4 needed by now static methods. - */ -class CV_EXPORTS KeyPointsFilter -{ -public: - KeyPointsFilter(){} - - /* - * Remove keypoints within borderPixels of an image edge. - */ - static void runByImageBorder( vector& keypoints, Size imageSize, int borderSize ); - /* - * Remove keypoints of sizes out of range. - */ - static void runByKeypointSize( vector& keypoints, float minSize, float maxSize=std::numeric_limits::max() ); - /* - * Remove keypoints from some image by mask for pixels of this image. - */ - static void runByPixelsMask( vector& keypoints, const Mat& mask ); - /* - * Remove duplicated keypoints. - */ - static void removeDuplicated( vector& keypoints ); -}; - -/*! - SIFT implementation. - - The class implements SIFT algorithm by D. Lowe. -*/ - -class CV_EXPORTS SIFT -{ -public: - struct CV_EXPORTS CommonParams - { - static const int DEFAULT_NOCTAVES = 4; - static const int DEFAULT_NOCTAVE_LAYERS = 3; - static const int DEFAULT_FIRST_OCTAVE = -1; - enum { FIRST_ANGLE = 0, AVERAGE_ANGLE = 1 }; - - CommonParams(); - CommonParams( int _nOctaves, int _nOctaveLayers, int /*_firstOctave*/, int /*_angleMode*/ ); - CommonParams( int _nOctaves, int _nOctaveLayers ); - int nOctaves, nOctaveLayers; - int firstOctave; // it is not used now (firstOctave == 0 always) - int angleMode; // it is not used now - }; - - struct CV_EXPORTS DetectorParams - { - static double GET_DEFAULT_THRESHOLD() { return 0.04; } - static double GET_DEFAULT_EDGE_THRESHOLD() { return 10.0; } - - DetectorParams(); - DetectorParams( double _threshold, double _edgeThreshold ); - double threshold, edgeThreshold; - }; - - struct CV_EXPORTS DescriptorParams - { - static double GET_DEFAULT_MAGNIFICATION() { return 3.0; } - static const bool DEFAULT_IS_NORMALIZE = true; - static const int DESCRIPTOR_SIZE = 128; - - DescriptorParams(); - DescriptorParams( double _magnification, bool /*_isNormalize*/, bool _recalculateAngles ); - DescriptorParams( bool _recalculateAngles ); - double magnification; - bool isNormalize; // it is not used now (true always) - bool recalculateAngles; - }; - - SIFT(); - //! sift-detector constructor - SIFT( double _threshold, double _edgeThreshold, - int _nOctaves=CommonParams::DEFAULT_NOCTAVES, - int _nOctaveLayers=CommonParams::DEFAULT_NOCTAVE_LAYERS, - int _firstOctave=CommonParams::DEFAULT_FIRST_OCTAVE, - int _angleMode=CommonParams::FIRST_ANGLE ); - //! sift-descriptor constructor - SIFT( double _magnification, bool _isNormalize=true, - bool _recalculateAngles = true, - int _nOctaves=CommonParams::DEFAULT_NOCTAVES, - int _nOctaveLayers=CommonParams::DEFAULT_NOCTAVE_LAYERS, - int _firstOctave=CommonParams::DEFAULT_FIRST_OCTAVE, - int _angleMode=CommonParams::FIRST_ANGLE ); - SIFT( const CommonParams& _commParams, - const DetectorParams& _detectorParams = DetectorParams(), - const DescriptorParams& _descriptorParams = DescriptorParams() ); - - //! returns the descriptor size in floats (128) - int descriptorSize() const; - //! finds the keypoints using SIFT algorithm - void operator()(const Mat& img, const Mat& mask, - vector& keypoints) const; - //! finds the keypoints and computes descriptors for them using SIFT algorithm. - //! Optionally it can compute descriptors for the user-provided keypoints - void operator()(const Mat& img, const Mat& mask, - vector& keypoints, - Mat& descriptors, - bool useProvidedKeypoints=false) const; - - CommonParams getCommonParams () const; - DetectorParams getDetectorParams () const; - DescriptorParams getDescriptorParams () const; - -protected: - CommonParams commParams; - DetectorParams detectorParams; - DescriptorParams descriptorParams; -}; - - -/*! - SURF implementation. - - The class implements SURF algorithm by H. Bay et al. - */ -class CV_EXPORTS_W SURF : public CvSURFParams -{ -public: - //! the default constructor - CV_WRAP SURF(); - //! the full constructor taking all the necessary parameters - CV_WRAP SURF(double _hessianThreshold, int _nOctaves=4, - int _nOctaveLayers=2, bool _extended=false, bool _upright=false); - - //! returns the descriptor size in float's (64 or 128) - CV_WRAP int descriptorSize() const; - //! finds the keypoints using fast hessian detector used in SURF - CV_WRAP_AS(detect) void operator()(const Mat& img, const Mat& mask, - CV_OUT vector& keypoints) const; - //! finds the keypoints and computes their descriptors. Optionally it can compute descriptors for the user-provided keypoints - CV_WRAP_AS(detect) void operator()(const Mat& img, const Mat& mask, - CV_OUT vector& keypoints, - CV_OUT vector& descriptors, - bool useProvidedKeypoints=false) const; -}; - -/*! - ORB implementation. -*/ -class CV_EXPORTS ORB -{ -public: - - /** the size of the signature in bytes */ - enum { kBytes = 32 }; - - struct CV_EXPORTS CommonParams - { - enum { DEFAULT_N_LEVELS = 3, DEFAULT_FIRST_LEVEL = 0}; - - /** default constructor */ - CommonParams(float scale_factor = 1.2f, unsigned n_levels = DEFAULT_N_LEVELS, int edge_threshold = 31, - unsigned first_level = DEFAULT_FIRST_LEVEL) : - scale_factor_(scale_factor), n_levels_(n_levels), first_level_(first_level >= n_levels ? 0 : first_level), - edge_threshold_(edge_threshold) - { - // No other patch size is supported right now - patch_size_ = 31; - } - void read(const FileNode& fn); - void write(FileStorage& fs) const; - - /** Coefficient by which we divide the dimensions from one scale pyramid level to the next */ - float scale_factor_; - /** The number of levels in the scale pyramid */ - unsigned n_levels_; - /** The level at which the image is given - * if 1, that means we will also look at the image scale_factor_ times bigger - */ - unsigned first_level_; - /** How far from the boundary the points should be */ - int edge_threshold_; - - friend class ORB; - protected: - /** The size of the patch that will be used for orientation and comparisons */ - int patch_size_; - }; - - /** Constructor - * @param n_features the number of desired features - * @param detector_params parameters to use - */ - ORB(size_t n_features = 500, const CommonParams & detector_params = CommonParams()); - - /** destructor to empty the patterns */ - ~ORB(); - - /** returns the descriptor size in bytes */ - int descriptorSize() const; - - /** Compute the ORB features and descriptors on an image - * @param img the image to compute the features and descriptors on - * @param mask the mask to apply - * @param keypoints the resulting keypoints - */ - void - operator()(const cv::Mat &image, const cv::Mat &mask, std::vector & keypoints); - - /** Compute the ORB features and descriptors on an image - * @param img the image to compute the features and descriptors on - * @param mask the mask to apply - * @param keypoints the resulting keypoints - * @param descriptors the resulting descriptors - * @param useProvidedKeypoints if true, the keypoints are used as an input - */ - void - operator()(const cv::Mat &image, const cv::Mat &mask, std::vector & keypoints, cv::Mat & descriptors, - bool useProvidedKeypoints = false); - -private: - /** The size of the patch used when comparing regions in the patterns */ - static const int kKernelWidth = 5; - - /** Compute the ORB features and descriptors on an image - * @param image the image to compute the features and descriptors on - * @param mask the mask to apply - * @param keypoints the resulting keypoints - * @param descriptors the resulting descriptors - * @param do_keypoints if true, the keypoints are computed, otherwise used as an input - * @param do_descriptors if true, also computes the descriptors - */ - void - operator()(const cv::Mat &image, const cv::Mat &mask, std::vector & keypoints, cv::Mat & descriptors, - bool do_keypoints, bool do_descriptors); - - /** Compute the ORB keypoints on an image - * @param image_pyramid the image pyramid to compute the features and descriptors on - * @param mask_pyramid the masks to apply at every level - * @param keypoints the resulting keypoints, clustered per level - */ - void computeKeyPoints(const std::vector& image_pyramid, const std::vector& mask_pyramid, - std::vector >& keypoints) const; - - /** Compute the ORB keypoint orientations - * @param image the image to compute the features and descriptors on - * @param integral_image the integral image of the image (can be empty, but the computation will be slower) - * @param level the scale at which we compute the orientation - * @param keypoints the resulting keypoints - */ - void - computeOrientation(const cv::Mat& image, const cv::Mat& integral_image, unsigned level, - std::vector& keypoints) const; - - /** Compute the ORB descriptors - * @param image the image to compute the features and descriptors on - * @param integral_image the integral image of the image (can be empty, but the computation will be slower) - * @param level the scale at which we compute the orientation - * @param keypoints the keypoints to use - * @param descriptors the resulting descriptors - */ - void - computeDescriptors(const cv::Mat& image, const cv::Mat& integral_image, unsigned level, - std::vector& keypoints, cv::Mat & descriptors) const; - - /** Compute the integral image and upadte the cached values - * @param image the image to compute the features and descriptors on - * @param level the scale at which we compute the orientation - * @param descriptors the resulting descriptors - */ - void computeIntegralImage(const cv::Mat & image, unsigned level, cv::Mat &integral_image); - - /** Parameters tuning ORB */ - CommonParams params_; - - /** size of the half patch used for orientation computation, see Rosin - 1999 - Measuring Corner Properties */ - int half_patch_size_; - - /** pre-computed offsets used for the Harris verification, one vector per scale */ - std::vector > orientation_horizontal_offsets_; - std::vector > orientation_vertical_offsets_; - - /** The steps of the integral images for each scale */ - std::vector integral_image_steps_; - - /** The number of desired features per scale */ - std::vector n_features_per_level_; - - /** The overall number of desired features */ - size_t n_features_; - - /** the end of a row in a circular patch */ - std::vector u_max_; - - /** The patterns for each level (the patterns are the same, but not their offset */ - class OrbPatterns; - std::vector patterns_; -}; - -/*! - Maximal Stable Extremal Regions class. - - The class implements MSER algorithm introduced by J. Matas. - Unlike SIFT, SURF and many other detectors in OpenCV, this is salient region detector, - not the salient point detector. - - It returns the regions, each of those is encoded as a contour. -*/ -class CV_EXPORTS_W MSER : public CvMSERParams -{ -public: - //! the default constructor - CV_WRAP MSER(); - //! the full constructor - CV_WRAP MSER( int _delta, int _min_area, int _max_area, - double _max_variation, double _min_diversity, - int _max_evolution, double _area_threshold, - double _min_margin, int _edge_blur_size ); - //! the operator that extracts the MSERs from the image or the specific part of it - CV_WRAP_AS(detect) void operator()( const Mat& image, - CV_OUT vector >& msers, const Mat& mask ) const; -}; - -/*! - The "Star" Detector. - - The class implements the keypoint detector introduced by K. Konolige. -*/ -class CV_EXPORTS_W StarDetector : public CvStarDetectorParams -{ -public: - //! the default constructor - CV_WRAP StarDetector(); - //! the full constructor - CV_WRAP StarDetector(int _maxSize, int _responseThreshold, - int _lineThresholdProjected, - int _lineThresholdBinarized, - int _suppressNonmaxSize); - //! finds the keypoints in the image - CV_WRAP_AS(detect) void operator()(const Mat& image, - CV_OUT vector& keypoints) const; -}; - -//! detects corners using FAST algorithm by E. Rosten -CV_EXPORTS void FAST( const Mat& image, CV_OUT vector& keypoints, - int threshold, bool nonmaxSupression=true ); - -/*! - The Patch Generator class -*/ -class CV_EXPORTS PatchGenerator -{ -public: - PatchGenerator(); - PatchGenerator(double _backgroundMin, double _backgroundMax, - double _noiseRange, bool _randomBlur=true, - double _lambdaMin=0.6, double _lambdaMax=1.5, - double _thetaMin=-CV_PI, double _thetaMax=CV_PI, - double _phiMin=-CV_PI, double _phiMax=CV_PI ); - void operator()(const Mat& image, Point2f pt, Mat& patch, Size patchSize, RNG& rng) const; - void operator()(const Mat& image, const Mat& transform, Mat& patch, - Size patchSize, RNG& rng) const; - void warpWholeImage(const Mat& image, Mat& matT, Mat& buf, - CV_OUT Mat& warped, int border, RNG& rng) const; - void generateRandomTransform(Point2f srcCenter, Point2f dstCenter, - CV_OUT Mat& transform, RNG& rng, - bool inverse=false) const; - void setAffineParam(double lambda, double theta, double phi); - - double backgroundMin, backgroundMax; - double noiseRange; - bool randomBlur; - double lambdaMin, lambdaMax; - double thetaMin, thetaMax; - double phiMin, phiMax; -}; - - -class CV_EXPORTS LDetector -{ -public: - LDetector(); - LDetector(int _radius, int _threshold, int _nOctaves, - int _nViews, double _baseFeatureSize, double _clusteringDistance); - void operator()(const Mat& image, - CV_OUT vector& keypoints, - int maxCount=0, bool scaleCoords=true) const; - void operator()(const vector& pyr, - CV_OUT vector& keypoints, - int maxCount=0, bool scaleCoords=true) const; - void getMostStable2D(const Mat& image, CV_OUT vector& keypoints, - int maxCount, const PatchGenerator& patchGenerator) const; - void setVerbose(bool verbose); - - void read(const FileNode& node); - void write(FileStorage& fs, const String& name=String()) const; - - int radius; - int threshold; - int nOctaves; - int nViews; - bool verbose; - - double baseFeatureSize; - double clusteringDistance; -}; - -typedef LDetector YAPE; - -class CV_EXPORTS FernClassifier -{ -public: - FernClassifier(); - FernClassifier(const FileNode& node); - FernClassifier(const vector >& points, - const vector& refimgs, - const vector >& labels=vector >(), - int _nclasses=0, int _patchSize=PATCH_SIZE, - int _signatureSize=DEFAULT_SIGNATURE_SIZE, - int _nstructs=DEFAULT_STRUCTS, - int _structSize=DEFAULT_STRUCT_SIZE, - int _nviews=DEFAULT_VIEWS, - int _compressionMethod=COMPRESSION_NONE, - const PatchGenerator& patchGenerator=PatchGenerator()); - virtual ~FernClassifier(); - virtual void read(const FileNode& n); - virtual void write(FileStorage& fs, const String& name=String()) const; - virtual void trainFromSingleView(const Mat& image, - const vector& keypoints, - int _patchSize=PATCH_SIZE, - int _signatureSize=DEFAULT_SIGNATURE_SIZE, - int _nstructs=DEFAULT_STRUCTS, - int _structSize=DEFAULT_STRUCT_SIZE, - int _nviews=DEFAULT_VIEWS, - int _compressionMethod=COMPRESSION_NONE, - const PatchGenerator& patchGenerator=PatchGenerator()); - virtual void train(const vector >& points, - const vector& refimgs, - const vector >& labels=vector >(), - int _nclasses=0, int _patchSize=PATCH_SIZE, - int _signatureSize=DEFAULT_SIGNATURE_SIZE, - int _nstructs=DEFAULT_STRUCTS, - int _structSize=DEFAULT_STRUCT_SIZE, - int _nviews=DEFAULT_VIEWS, - int _compressionMethod=COMPRESSION_NONE, - const PatchGenerator& patchGenerator=PatchGenerator()); - virtual int operator()(const Mat& img, Point2f kpt, vector& signature) const; - virtual int operator()(const Mat& patch, vector& signature) const; - virtual void clear(); - virtual bool empty() const; - void setVerbose(bool verbose); - - int getClassCount() const; - int getStructCount() const; - int getStructSize() const; - int getSignatureSize() const; - int getCompressionMethod() const; - Size getPatchSize() const; - - struct Feature - { - uchar x1, y1, x2, y2; - Feature() : x1(0), y1(0), x2(0), y2(0) {} - Feature(int _x1, int _y1, int _x2, int _y2) - : x1((uchar)_x1), y1((uchar)_y1), x2((uchar)_x2), y2((uchar)_y2) - {} - template bool operator ()(const Mat_<_Tp>& patch) const - { return patch(y1,x1) > patch(y2, x2); } - }; - - enum - { - PATCH_SIZE = 31, - DEFAULT_STRUCTS = 50, - DEFAULT_STRUCT_SIZE = 9, - DEFAULT_VIEWS = 5000, - DEFAULT_SIGNATURE_SIZE = 176, - COMPRESSION_NONE = 0, - COMPRESSION_RANDOM_PROJ = 1, - COMPRESSION_PCA = 2, - DEFAULT_COMPRESSION_METHOD = COMPRESSION_NONE - }; - -protected: - virtual void prepare(int _nclasses, int _patchSize, int _signatureSize, - int _nstructs, int _structSize, - int _nviews, int _compressionMethod); - virtual void finalize(RNG& rng); - virtual int getLeaf(int fidx, const Mat& patch) const; - - bool verbose; - int nstructs; - int structSize; - int nclasses; - int signatureSize; - int compressionMethod; - int leavesPerStruct; - Size patchSize; - vector features; - vector classCounters; - vector posteriors; -}; - - -/****************************************************************************************\ -* Calonder Classifier * -\****************************************************************************************/ - -struct RTreeNode; - -struct CV_EXPORTS BaseKeypoint -{ - int x; - int y; - IplImage* image; - - BaseKeypoint() - : x(0), y(0), image(NULL) - {} - - BaseKeypoint(int x, int y, IplImage* image) - : x(x), y(y), image(image) - {} -}; - -class CV_EXPORTS RandomizedTree -{ -public: - friend class RTreeClassifier; - - static const uchar PATCH_SIZE = 32; - static const int DEFAULT_DEPTH = 9; - static const int DEFAULT_VIEWS = 5000; - static const size_t DEFAULT_REDUCED_NUM_DIM = 176; - static float GET_LOWER_QUANT_PERC() { return .03f; } - static float GET_UPPER_QUANT_PERC() { return .92f; } - - RandomizedTree(); - ~RandomizedTree(); - - void train(std::vector const& base_set, RNG &rng, - int depth, int views, size_t reduced_num_dim, int num_quant_bits); - void train(std::vector const& base_set, RNG &rng, - PatchGenerator &make_patch, int depth, int views, size_t reduced_num_dim, - int num_quant_bits); - - // following two funcs are EXPERIMENTAL (do not use unless you know exactly what you do) - static void quantizeVector(float *vec, int dim, int N, float bnds[2], int clamp_mode=0); - static void quantizeVector(float *src, int dim, int N, float bnds[2], uchar *dst); - - // patch_data must be a 32x32 array (no row padding) - float* getPosterior(uchar* patch_data); - const float* getPosterior(uchar* patch_data) const; - uchar* getPosterior2(uchar* patch_data); - const uchar* getPosterior2(uchar* patch_data) const; - - void read(const char* file_name, int num_quant_bits); - void read(std::istream &is, int num_quant_bits); - void write(const char* file_name) const; - void write(std::ostream &os) const; - - int classes() { return classes_; } - int depth() { return depth_; } - - //void setKeepFloatPosteriors(bool b) { keep_float_posteriors_ = b; } - void discardFloatPosteriors() { freePosteriors(1); } - - inline void applyQuantization(int num_quant_bits) { makePosteriors2(num_quant_bits); } - - // debug - void savePosteriors(std::string url, bool append=false); - void savePosteriors2(std::string url, bool append=false); - -private: - int classes_; - int depth_; - int num_leaves_; - std::vector nodes_; - float **posteriors_; // 16-bytes aligned posteriors - uchar **posteriors2_; // 16-bytes aligned posteriors - std::vector leaf_counts_; - - void createNodes(int num_nodes, RNG &rng); - void allocPosteriorsAligned(int num_leaves, int num_classes); - void freePosteriors(int which); // which: 1=posteriors_, 2=posteriors2_, 3=both - void init(int classes, int depth, RNG &rng); - void addExample(int class_id, uchar* patch_data); - void finalize(size_t reduced_num_dim, int num_quant_bits); - int getIndex(uchar* patch_data) const; - inline float* getPosteriorByIndex(int index); - inline const float* getPosteriorByIndex(int index) const; - inline uchar* getPosteriorByIndex2(int index); - inline const uchar* getPosteriorByIndex2(int index) const; - //void makeRandomMeasMatrix(float *cs_phi, PHI_DISTR_TYPE dt, size_t reduced_num_dim); - void convertPosteriorsToChar(); - void makePosteriors2(int num_quant_bits); - void compressLeaves(size_t reduced_num_dim); - void estimateQuantPercForPosteriors(float perc[2]); -}; - - -inline uchar* getData(IplImage* image) -{ - return reinterpret_cast(image->imageData); -} - -inline float* RandomizedTree::getPosteriorByIndex(int index) -{ - return const_cast(const_cast(this)->getPosteriorByIndex(index)); -} - -inline const float* RandomizedTree::getPosteriorByIndex(int index) const -{ - return posteriors_[index]; -} - -inline uchar* RandomizedTree::getPosteriorByIndex2(int index) -{ - return const_cast(const_cast(this)->getPosteriorByIndex2(index)); -} - -inline const uchar* RandomizedTree::getPosteriorByIndex2(int index) const -{ - return posteriors2_[index]; -} - -struct CV_EXPORTS RTreeNode -{ - short offset1, offset2; - - RTreeNode() {} - RTreeNode(uchar x1, uchar y1, uchar x2, uchar y2) - : offset1(y1*RandomizedTree::PATCH_SIZE + x1), - offset2(y2*RandomizedTree::PATCH_SIZE + x2) - {} - - //! Left child on 0, right child on 1 - inline bool operator() (uchar* patch_data) const - { - return patch_data[offset1] > patch_data[offset2]; - } -}; - -class CV_EXPORTS RTreeClassifier -{ -public: - static const int DEFAULT_TREES = 48; - static const size_t DEFAULT_NUM_QUANT_BITS = 4; - - RTreeClassifier(); - void train(std::vector const& base_set, - RNG &rng, - int num_trees = RTreeClassifier::DEFAULT_TREES, - int depth = RandomizedTree::DEFAULT_DEPTH, - int views = RandomizedTree::DEFAULT_VIEWS, - size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM, - int num_quant_bits = DEFAULT_NUM_QUANT_BITS); - void train(std::vector const& base_set, - RNG &rng, - PatchGenerator &make_patch, - int num_trees = RTreeClassifier::DEFAULT_TREES, - int depth = RandomizedTree::DEFAULT_DEPTH, - int views = RandomizedTree::DEFAULT_VIEWS, - size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM, - int num_quant_bits = DEFAULT_NUM_QUANT_BITS); - - // sig must point to a memory block of at least classes()*sizeof(float|uchar) bytes - void getSignature(IplImage *patch, uchar *sig) const; - void getSignature(IplImage *patch, float *sig) const; - void getSparseSignature(IplImage *patch, float *sig, float thresh) const; - // TODO: deprecated in favor of getSignature overload, remove - void getFloatSignature(IplImage *patch, float *sig) const { getSignature(patch, sig); } - - static int countNonZeroElements(float *vec, int n, double tol=1e-10); - static inline void safeSignatureAlloc(uchar **sig, int num_sig=1, int sig_len=176); - static inline uchar* safeSignatureAlloc(int num_sig=1, int sig_len=176); - - inline int classes() const { return classes_; } - inline int original_num_classes() const { return original_num_classes_; } - - void setQuantization(int num_quant_bits); - void discardFloatPosteriors(); - - void read(const char* file_name); - void read(std::istream &is); - void write(const char* file_name) const; - void write(std::ostream &os) const; - - // experimental and debug - void saveAllFloatPosteriors(std::string file_url); - void saveAllBytePosteriors(std::string file_url); - void setFloatPosteriorsFromTextfile_176(std::string url); - float countZeroElements(); - - std::vector trees_; - -private: - int classes_; - int num_quant_bits_; - mutable uchar **posteriors_; - mutable unsigned short *ptemp_; - int original_num_classes_; - bool keep_floats_; -}; - -/****************************************************************************************\ -* One-Way Descriptor * -\****************************************************************************************/ - -class CV_EXPORTS OneWayDescriptor -{ -public: - OneWayDescriptor(); - ~OneWayDescriptor(); - - // allocates memory for given descriptor parameters - void Allocate(int pose_count, CvSize size, int nChannels); - - // GenerateSamples: generates affine transformed patches with averaging them over small transformation variations. - // If external poses and transforms were specified, uses them instead of generating random ones - // - pose_count: the number of poses to be generated - // - frontal: the input patch (can be a roi in a larger image) - // - norm: if nonzero, normalizes the output patch so that the sum of pixel intensities is 1 - void GenerateSamples(int pose_count, IplImage* frontal, int norm = 0); - - // GenerateSamplesFast: generates affine transformed patches with averaging them over small transformation variations. - // Uses precalculated transformed pca components. - // - frontal: the input patch (can be a roi in a larger image) - // - pca_hr_avg: pca average vector - // - pca_hr_eigenvectors: pca eigenvectors - // - pca_descriptors: an array of precomputed descriptors of pca components containing their affine transformations - // pca_descriptors[0] corresponds to the average, pca_descriptors[1]-pca_descriptors[pca_dim] correspond to eigenvectors - void GenerateSamplesFast(IplImage* frontal, CvMat* pca_hr_avg, - CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors); - - // sets the poses and corresponding transforms - void SetTransforms(CvAffinePose* poses, CvMat** transforms); - - // Initialize: builds a descriptor. - // - pose_count: the number of poses to build. If poses were set externally, uses them rather than generating random ones - // - frontal: input patch. Can be a roi in a larger image - // - feature_name: the feature name to be associated with the descriptor - // - norm: if 1, the affine transformed patches are normalized so that their sum is 1 - void Initialize(int pose_count, IplImage* frontal, const char* feature_name = 0, int norm = 0); - - // InitializeFast: builds a descriptor using precomputed descriptors of pca components - // - pose_count: the number of poses to build - // - frontal: input patch. Can be a roi in a larger image - // - feature_name: the feature name to be associated with the descriptor - // - pca_hr_avg: average vector for PCA - // - pca_hr_eigenvectors: PCA eigenvectors (one vector per row) - // - pca_descriptors: precomputed descriptors of PCA components, the first descriptor for the average vector - // followed by the descriptors for eigenvectors - void InitializeFast(int pose_count, IplImage* frontal, const char* feature_name, - CvMat* pca_hr_avg, CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors); - - // ProjectPCASample: unwarps an image patch into a vector and projects it into PCA space - // - patch: input image patch - // - avg: PCA average vector - // - eigenvectors: PCA eigenvectors, one per row - // - pca_coeffs: output PCA coefficients - void ProjectPCASample(IplImage* patch, CvMat* avg, CvMat* eigenvectors, CvMat* pca_coeffs) const; - - // InitializePCACoeffs: projects all warped patches into PCA space - // - avg: PCA average vector - // - eigenvectors: PCA eigenvectors, one per row - void InitializePCACoeffs(CvMat* avg, CvMat* eigenvectors); - - // EstimatePose: finds the closest match between an input patch and a set of patches with different poses - // - patch: input image patch - // - pose_idx: the output index of the closest pose - // - distance: the distance to the closest pose (L2 distance) - void EstimatePose(IplImage* patch, int& pose_idx, float& distance) const; - - // EstimatePosePCA: finds the closest match between an input patch and a set of patches with different poses. - // The distance between patches is computed in PCA space - // - patch: input image patch - // - pose_idx: the output index of the closest pose - // - distance: distance to the closest pose (L2 distance in PCA space) - // - avg: PCA average vector. If 0, matching without PCA is used - // - eigenvectors: PCA eigenvectors, one per row - void EstimatePosePCA(CvArr* patch, int& pose_idx, float& distance, CvMat* avg, CvMat* eigenvalues) const; - - // GetPatchSize: returns the size of each image patch after warping (2 times smaller than the input patch) - CvSize GetPatchSize() const - { - return m_patch_size; - } - - // GetInputPatchSize: returns the required size of the patch that the descriptor is built from - // (2 time larger than the patch after warping) - CvSize GetInputPatchSize() const - { - return cvSize(m_patch_size.width*2, m_patch_size.height*2); - } - - // GetPatch: returns a patch corresponding to specified pose index - // - index: pose index - // - return value: the patch corresponding to specified pose index - IplImage* GetPatch(int index); - - // GetPose: returns a pose corresponding to specified pose index - // - index: pose index - // - return value: the pose corresponding to specified pose index - CvAffinePose GetPose(int index) const; - - // Save: saves all patches with different poses to a specified path - void Save(const char* path); - - // ReadByName: reads a descriptor from a file storage - // - fs: file storage - // - parent: parent node - // - name: node name - // - return value: 1 if succeeded, 0 otherwise - int ReadByName(CvFileStorage* fs, CvFileNode* parent, const char* name); - - // ReadByName: reads a descriptor from a file node - // - parent: parent node - // - name: node name - // - return value: 1 if succeeded, 0 otherwise - int ReadByName(const FileNode &parent, const char* name); - - // Write: writes a descriptor into a file storage - // - fs: file storage - // - name: node name - void Write(CvFileStorage* fs, const char* name); - - // GetFeatureName: returns a name corresponding to a feature - const char* GetFeatureName() const; - - // GetCenter: returns the center of the feature - CvPoint GetCenter() const; - - void SetPCADimHigh(int pca_dim_high) {m_pca_dim_high = pca_dim_high;}; - void SetPCADimLow(int pca_dim_low) {m_pca_dim_low = pca_dim_low;}; - - int GetPCADimLow() const; - int GetPCADimHigh() const; - - CvMat** GetPCACoeffs() const {return m_pca_coeffs;} - -protected: - int m_pose_count; // the number of poses - CvSize m_patch_size; // size of each image - IplImage** m_samples; // an array of length m_pose_count containing the patch in different poses - IplImage* m_input_patch; - IplImage* m_train_patch; - CvMat** m_pca_coeffs; // an array of length m_pose_count containing pca decomposition of the patch in different poses - CvAffinePose* m_affine_poses; // an array of poses - CvMat** m_transforms; // an array of affine transforms corresponding to poses - - string m_feature_name; // the name of the feature associated with the descriptor - CvPoint m_center; // the coordinates of the feature (the center of the input image ROI) - - int m_pca_dim_high; // the number of descriptor pca components to use for generating affine poses - int m_pca_dim_low; // the number of pca components to use for comparison -}; - - -// OneWayDescriptorBase: encapsulates functionality for training/loading a set of one way descriptors -// and finding the nearest closest descriptor to an input feature -class CV_EXPORTS OneWayDescriptorBase -{ -public: - - // creates an instance of OneWayDescriptor from a set of training files - // - patch_size: size of the input (large) patch - // - pose_count: the number of poses to generate for each descriptor - // - train_path: path to training files - // - pca_config: the name of the file that contains PCA for small patches (2 times smaller - // than patch_size each dimension - // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size) - // - pca_desc_config: the name of the file that contains descriptors of PCA components - OneWayDescriptorBase(CvSize patch_size, int pose_count, const char* train_path = 0, const char* pca_config = 0, - const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1, - int pca_dim_high = 100, int pca_dim_low = 100); - - OneWayDescriptorBase(CvSize patch_size, int pose_count, const string &pca_filename, const string &train_path = string(), const string &images_list = string(), - float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1, - int pca_dim_high = 100, int pca_dim_low = 100); - - - virtual ~OneWayDescriptorBase(); - void clear (); - - - // Allocate: allocates memory for a given number of descriptors - void Allocate(int train_feature_count); - - // AllocatePCADescriptors: allocates memory for pca descriptors - void AllocatePCADescriptors(); - - // returns patch size - CvSize GetPatchSize() const {return m_patch_size;}; - // returns the number of poses for each descriptor - int GetPoseCount() const {return m_pose_count;}; - - // returns the number of pyramid levels - int GetPyrLevels() const {return m_pyr_levels;}; - - // returns the number of descriptors - int GetDescriptorCount() const {return m_train_feature_count;}; - - // CreateDescriptorsFromImage: creates descriptors for each of the input features - // - src: input image - // - features: input features - // - pyr_levels: the number of pyramid levels - void CreateDescriptorsFromImage(IplImage* src, const std::vector& features); - - // CreatePCADescriptors: generates descriptors for PCA components, needed for fast generation of feature descriptors - void CreatePCADescriptors(); - - // returns a feature descriptor by feature index - const OneWayDescriptor* GetDescriptor(int desc_idx) const {return &m_descriptors[desc_idx];}; - - // FindDescriptor: finds the closest descriptor - // - patch: input image patch - // - desc_idx: output index of the closest descriptor to the input patch - // - pose_idx: output index of the closest pose of the closest descriptor to the input patch - // - distance: distance from the input patch to the closest feature pose - // - _scales: scales of the input patch for each descriptor - // - scale_ranges: input scales variation (float[2]) - void FindDescriptor(IplImage* patch, int& desc_idx, int& pose_idx, float& distance, float* _scale = 0, float* scale_ranges = 0) const; - - // - patch: input image patch - // - n: number of the closest indexes - // - desc_idxs: output indexes of the closest descriptor to the input patch (n) - // - pose_idx: output indexes of the closest pose of the closest descriptor to the input patch (n) - // - distances: distance from the input patch to the closest feature pose (n) - // - _scales: scales of the input patch - // - scale_ranges: input scales variation (float[2]) - void FindDescriptor(IplImage* patch, int n, std::vector& desc_idxs, std::vector& pose_idxs, - std::vector& distances, std::vector& _scales, float* scale_ranges = 0) const; - - // FindDescriptor: finds the closest descriptor - // - src: input image - // - pt: center of the feature - // - desc_idx: output index of the closest descriptor to the input patch - // - pose_idx: output index of the closest pose of the closest descriptor to the input patch - // - distance: distance from the input patch to the closest feature pose - void FindDescriptor(IplImage* src, cv::Point2f pt, int& desc_idx, int& pose_idx, float& distance) const; - - // InitializePoses: generates random poses - void InitializePoses(); - - // InitializeTransformsFromPoses: generates 2x3 affine matrices from poses (initializes m_transforms) - void InitializeTransformsFromPoses(); - - // InitializePoseTransforms: subsequently calls InitializePoses and InitializeTransformsFromPoses - void InitializePoseTransforms(); - - // InitializeDescriptor: initializes a descriptor - // - desc_idx: descriptor index - // - train_image: image patch (ROI is supported) - // - feature_label: feature textual label - void InitializeDescriptor(int desc_idx, IplImage* train_image, const char* feature_label); - - void InitializeDescriptor(int desc_idx, IplImage* train_image, const cv::KeyPoint& keypoint, const char* feature_label); - - // InitializeDescriptors: load features from an image and create descriptors for each of them - void InitializeDescriptors(IplImage* train_image, const vector& features, - const char* feature_label = "", int desc_start_idx = 0); - - // Write: writes this object to a file storage - // - fs: output filestorage - void Write (FileStorage &fs) const; - - // Read: reads OneWayDescriptorBase object from a file node - // - fn: input file node - void Read (const FileNode &fn); - - // LoadPCADescriptors: loads PCA descriptors from a file - // - filename: input filename - int LoadPCADescriptors(const char* filename); - - // LoadPCADescriptors: loads PCA descriptors from a file node - // - fn: input file node - int LoadPCADescriptors(const FileNode &fn); - - // SavePCADescriptors: saves PCA descriptors to a file - // - filename: output filename - void SavePCADescriptors(const char* filename); - - // SavePCADescriptors: saves PCA descriptors to a file storage - // - fs: output file storage - void SavePCADescriptors(CvFileStorage* fs) const; - - // GeneratePCA: calculate and save PCA components and descriptors - // - img_path: path to training PCA images directory - // - images_list: filename with filenames of training PCA images - void GeneratePCA(const char* img_path, const char* images_list, int pose_count=500); - - // SetPCAHigh: sets the high resolution pca matrices (copied to internal structures) - void SetPCAHigh(CvMat* avg, CvMat* eigenvectors); - - // SetPCALow: sets the low resolution pca matrices (copied to internal structures) - void SetPCALow(CvMat* avg, CvMat* eigenvectors); - - int GetLowPCA(CvMat** avg, CvMat** eigenvectors) - { - *avg = m_pca_avg; - *eigenvectors = m_pca_eigenvectors; - return m_pca_dim_low; - }; - - int GetPCADimLow() const {return m_pca_dim_low;}; - int GetPCADimHigh() const {return m_pca_dim_high;}; - - void ConvertDescriptorsArrayToTree(); // Converting pca_descriptors array to KD tree - - // GetPCAFilename: get default PCA filename - static string GetPCAFilename () { return "pca.yml"; } - - virtual bool empty() const { return m_train_feature_count <= 0 ? true : false; } - -protected: - CvSize m_patch_size; // patch size - int m_pose_count; // the number of poses for each descriptor - int m_train_feature_count; // the number of the training features - OneWayDescriptor* m_descriptors; // array of train feature descriptors - CvMat* m_pca_avg; // PCA average Vector for small patches - CvMat* m_pca_eigenvectors; // PCA eigenvectors for small patches - CvMat* m_pca_hr_avg; // PCA average Vector for large patches - CvMat* m_pca_hr_eigenvectors; // PCA eigenvectors for large patches - OneWayDescriptor* m_pca_descriptors; // an array of PCA descriptors - - cv::flann::Index* m_pca_descriptors_tree; - CvMat* m_pca_descriptors_matrix; - - CvAffinePose* m_poses; // array of poses - CvMat** m_transforms; // array of affine transformations corresponding to poses - - int m_pca_dim_high; - int m_pca_dim_low; - - int m_pyr_levels; - float scale_min; - float scale_max; - float scale_step; - - // SavePCAall: saves PCA components and descriptors to a file storage - // - fs: output file storage - void SavePCAall (FileStorage &fs) const; - - // LoadPCAall: loads PCA components and descriptors from a file node - // - fn: input file node - void LoadPCAall (const FileNode &fn); -}; - -class CV_EXPORTS OneWayDescriptorObject : public OneWayDescriptorBase -{ -public: - // creates an instance of OneWayDescriptorObject from a set of training files - // - patch_size: size of the input (large) patch - // - pose_count: the number of poses to generate for each descriptor - // - train_path: path to training files - // - pca_config: the name of the file that contains PCA for small patches (2 times smaller - // than patch_size each dimension - // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size) - // - pca_desc_config: the name of the file that contains descriptors of PCA components - OneWayDescriptorObject(CvSize patch_size, int pose_count, const char* train_path, const char* pca_config, - const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1); - - OneWayDescriptorObject(CvSize patch_size, int pose_count, const string &pca_filename, - const string &train_path = string (), const string &images_list = string (), - float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1); - - - virtual ~OneWayDescriptorObject(); - - // Allocate: allocates memory for a given number of features - // - train_feature_count: the total number of features - // - object_feature_count: the number of features extracted from the object - void Allocate(int train_feature_count, int object_feature_count); - - - void SetLabeledFeatures(const vector& features) {m_train_features = features;}; - vector& GetLabeledFeatures() {return m_train_features;}; - const vector& GetLabeledFeatures() const {return m_train_features;}; - vector _GetLabeledFeatures() const; - - // IsDescriptorObject: returns 1 if descriptor with specified index is positive, otherwise 0 - int IsDescriptorObject(int desc_idx) const; - - // MatchPointToPart: returns the part number of a feature if it matches one of the object parts, otherwise -1 - int MatchPointToPart(CvPoint pt) const; - - // GetDescriptorPart: returns the part number of the feature corresponding to a specified descriptor - // - desc_idx: descriptor index - int GetDescriptorPart(int desc_idx) const; - - - void InitializeObjectDescriptors(IplImage* train_image, const vector& features, - const char* feature_label, int desc_start_idx = 0, float scale = 1.0f, - int is_background = 0); - - // GetObjectFeatureCount: returns the number of object features - int GetObjectFeatureCount() const {return m_object_feature_count;}; - -protected: - int* m_part_id; // contains part id for each of object descriptors - vector m_train_features; // train features - int m_object_feature_count; // the number of the positive features - -}; - - -/****************************************************************************************\ -* FeatureDetector * -\****************************************************************************************/ - -/* - * Abstract base class for 2D image feature detectors. - */ -class CV_EXPORTS_W FeatureDetector -{ -public: - virtual ~FeatureDetector(); - - /* - * Detect keypoints in an image. - * image The image. - * keypoints The detected keypoints. - * mask Mask specifying where to look for keypoints (optional). Must be a char - * matrix with non-zero values in the region of interest. - */ - CV_WRAP void detect( const Mat& image, CV_OUT vector& keypoints, const Mat& mask=Mat() ) const; - - /* - * Detect keypoints in an image set. - * images Image collection. - * keypoints Collection of keypoints detected in an input images. keypoints[i] is a set of keypoints detected in an images[i]. - * masks Masks for image set. masks[i] is a mask for images[i]. - */ - void detect( const vector& images, vector >& keypoints, const vector& masks=vector() ) const; - - // Read detector object from a file node. - virtual void read( const FileNode& ); - // Read detector object from a file node. - virtual void write( FileStorage& ) const; - - // Return true if detector object is empty - CV_WRAP virtual bool empty() const; - - // Create feature detector by detector name. - CV_WRAP static Ptr create( const string& detectorType ); - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const = 0; - - /* - * Remove keypoints that are not in the mask. - * Helper function, useful when wrapping a library call for keypoint detection that - * does not support a mask argument. - */ - static void removeInvalidPoints( const Mat& mask, vector& keypoints ); -}; - -class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector -{ -public: - CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - int threshold; - bool nonmaxSuppression; -}; - - -class CV_EXPORTS GoodFeaturesToTrackDetector : public FeatureDetector -{ -public: - class CV_EXPORTS Params - { - public: - Params( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1., - int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); - void read( const FileNode& fn ); - void write( FileStorage& fs ) const; - - int maxCorners; - double qualityLevel; - double minDistance; - int blockSize; - bool useHarrisDetector; - double k; - }; - - GoodFeaturesToTrackDetector( const GoodFeaturesToTrackDetector::Params& params=GoodFeaturesToTrackDetector::Params() ); - GoodFeaturesToTrackDetector( int maxCorners, double qualityLevel, double minDistance, - int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - Params params; -}; - -class CV_EXPORTS MserFeatureDetector : public FeatureDetector -{ -public: - MserFeatureDetector( CvMSERParams params=cvMSERParams() ); - MserFeatureDetector( int delta, int minArea, int maxArea, double maxVariation, double minDiversity, - int maxEvolution, double areaThreshold, double minMargin, int edgeBlurSize ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - MSER mser; -}; - -class CV_EXPORTS_W StarFeatureDetector : public FeatureDetector -{ -public: - StarFeatureDetector( const CvStarDetectorParams& params=cvStarDetectorParams() ); - CV_WRAP StarFeatureDetector( int maxSize, int responseThreshold=30, int lineThresholdProjected = 10, - int lineThresholdBinarized=8, int suppressNonmaxSize=5 ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - StarDetector star; -}; - -class CV_EXPORTS SiftFeatureDetector : public FeatureDetector -{ -public: - SiftFeatureDetector( const SIFT::DetectorParams& detectorParams=SIFT::DetectorParams(), - const SIFT::CommonParams& commonParams=SIFT::CommonParams() ); - SiftFeatureDetector( double threshold, double edgeThreshold, - int nOctaves=SIFT::CommonParams::DEFAULT_NOCTAVES, - int nOctaveLayers=SIFT::CommonParams::DEFAULT_NOCTAVE_LAYERS, - int firstOctave=SIFT::CommonParams::DEFAULT_FIRST_OCTAVE, - int angleMode=SIFT::CommonParams::FIRST_ANGLE ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - SIFT sift; -}; - -class CV_EXPORTS SurfFeatureDetector : public FeatureDetector -{ -public: - SurfFeatureDetector( double hessianThreshold=400., int octaves=3, int octaveLayers=4, bool upright=false ); - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - SURF surf; -}; - -/** Feature detector for the ORB feature - * Basically fast followed by a Harris check - */ -class CV_EXPORTS OrbFeatureDetector : public cv::FeatureDetector -{ -public: - /** Default constructor - * @param n_features the number of desired features - * @param params parameters to use - */ - OrbFeatureDetector(size_t n_features = 700, ORB::CommonParams params = ORB::CommonParams()); - - virtual void read(const cv::FileNode&); - virtual void write(cv::FileStorage&) const; - -protected: - virtual void - detectImpl(const cv::Mat& image, std::vector& keypoints, const cv::Mat& mask = cv::Mat()) const; -private: - /** the ORB object we use for the computations */ - mutable ORB orb_; - /** The parameters used */ - ORB::CommonParams params_; - /** the number of features that need to be retrieved */ - unsigned n_features_; -}; - -class CV_EXPORTS SimpleBlobDetector : public cv::FeatureDetector -{ -public: - struct CV_EXPORTS Params - { - Params(); - float thresholdStep; - float minThreshold; - float maxThreshold; - size_t minRepeatability; - float minDistBetweenBlobs; - - bool filterByColor; - uchar blobColor; - - bool filterByArea; - float minArea, maxArea; - - bool filterByCircularity; - float minCircularity, maxCircularity; - - bool filterByInertia; - float minInertiaRatio, maxInertiaRatio; - - bool filterByConvexity; - float minConvexity, maxConvexity; - - void read( const FileNode& fn ); - void write( FileStorage& fs ) const; - }; - - SimpleBlobDetector(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); - - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - struct CV_EXPORTS Center - { - Point2d location; - double radius; - double confidence; - }; - - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - virtual void findBlobs(const cv::Mat &image, const cv::Mat &binaryImage, std::vector
¢ers) const; - - Params params; -}; - -class CV_EXPORTS DenseFeatureDetector : public FeatureDetector -{ -public: - class CV_EXPORTS Params - { - public: - Params( float initFeatureScale=1.f, int featureScaleLevels=1, float featureScaleMul=0.1f, - int initXyStep=6, int initImgBound=0, bool varyXyStepWithScale=true, bool varyImgBoundWithScale=false ); - float initFeatureScale; - int featureScaleLevels; - float featureScaleMul; - - int initXyStep; - int initImgBound; - - bool varyXyStepWithScale; - bool varyImgBoundWithScale; - - void read( const FileNode& fn ); - void write( FileStorage& fs ) const; - }; - - DenseFeatureDetector( const DenseFeatureDetector::Params& params=DenseFeatureDetector::Params() ); - - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - Params params; -}; - -/* - * Adapts a detector to partition the source image into a grid and detect - * points in each cell. - */ -class CV_EXPORTS_W GridAdaptedFeatureDetector : public FeatureDetector -{ -public: - /* - * detector Detector that will be adapted. - * maxTotalKeypoints Maximum count of keypoints detected on the image. Only the strongest keypoints - * will be keeped. - * gridRows Grid rows count. - * gridCols Grid column count. - */ - CV_WRAP GridAdaptedFeatureDetector( const Ptr& detector, int maxTotalKeypoints=1000, - int gridRows=4, int gridCols=4 ); - - // TODO implement read/write - virtual bool empty() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - Ptr detector; - int maxTotalKeypoints; - int gridRows; - int gridCols; -}; - -/* - * Adapts a detector to detect points over multiple levels of a Gaussian - * pyramid. Useful for detectors that are not inherently scaled. - */ -class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector -{ -public: - // maxLevel - The 0-based index of the last pyramid layer - CV_WRAP PyramidAdaptedFeatureDetector( const Ptr& detector, int maxLevel=2 ); - - // TODO implement read/write - virtual bool empty() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - Ptr detector; - int maxLevel; -}; - -/** \brief A feature detector parameter adjuster, this is used by the DynamicAdaptedFeatureDetector - * and is a wrapper for FeatureDetector that allow them to be adjusted after a detection - */ -class CV_EXPORTS AdjusterAdapter: public FeatureDetector -{ -public: - /** pure virtual interface - */ - virtual ~AdjusterAdapter() {} - /** too few features were detected so, adjust the detector params accordingly - * \param min the minimum number of desired features - * \param n_detected the number previously detected - */ - virtual void tooFew(int min, int n_detected) = 0; - /** too many features were detected so, adjust the detector params accordingly - * \param max the maximum number of desired features - * \param n_detected the number previously detected - */ - virtual void tooMany(int max, int n_detected) = 0; - /** are params maxed out or still valid? - * \return false if the parameters can't be adjusted any more - */ - virtual bool good() const = 0; - - virtual Ptr clone() const = 0; - - static Ptr create( const string& detectorType ); -}; -/** \brief an adaptively adjusting detector that iteratively detects until the desired number - * of features are detected. - * Beware that this is not thread safe - as the adjustment of parameters breaks the const - * of the detection routine... - * /TODO Make this const correct and thread safe - * - * sample usage: - //will create a detector that attempts to find 100 - 110 FAST Keypoints, and will at most run - //FAST feature detection 10 times until that number of keypoints are found - Ptr detector(new DynamicAdaptedFeatureDetector(new FastAdjuster(20,true),100, 110, 10)); - - */ -class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector -{ -public: - - /** \param adjaster an AdjusterAdapter that will do the detection and parameter adjustment - * \param max_features the maximum desired number of features - * \param max_iters the maximum number of times to try to adjust the feature detector params - * for the FastAdjuster this can be high, but with Star or Surf this can get time consuming - * \param min_features the minimum desired features - */ - DynamicAdaptedFeatureDetector( const Ptr& adjaster, int min_features=400, int max_features=500, int max_iters=5 ); - - virtual bool empty() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - -private: - DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&); - DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&); - - int escape_iters_; - int min_features_, max_features_; - const Ptr adjuster_; -}; - -/**\brief an adjust for the FAST detector. This will basically decrement or increment the - * threshold by 1 - */ -class CV_EXPORTS FastAdjuster: public AdjusterAdapter -{ -public: - /**\param init_thresh the initial threshold to start with, default = 20 - * \param nonmax whether to use non max or not for fast feature detection - */ - FastAdjuster(int init_thresh=20, bool nonmax=true, int min_thresh=1, int max_thresh=200); - - virtual void tooFew(int min, int n_detected); - virtual void tooMany(int max, int n_detected); - virtual bool good() const; - - virtual Ptr clone() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - int thresh_; - bool nonmax_; - int init_thresh_, min_thresh_, max_thresh_; -}; - - -/** An adjuster for StarFeatureDetector, this one adjusts the responseThreshold for now - * TODO find a faster way to converge the parameters for Star - use CvStarDetectorParams - */ -class CV_EXPORTS StarAdjuster: public AdjusterAdapter -{ -public: - StarAdjuster(double initial_thresh=30.0, double min_thresh=2., double max_thresh=200.); - - virtual void tooFew(int min, int n_detected); - virtual void tooMany(int max, int n_detected); - virtual bool good() const; - - virtual Ptr clone() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - double thresh_, init_thresh_, min_thresh_, max_thresh_; - CvStarDetectorParams params_; //todo use these instead of thresh_ -}; - -class CV_EXPORTS SurfAdjuster: public AdjusterAdapter -{ -public: - SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 ); - - virtual void tooFew(int min, int n_detected); - virtual void tooMany(int max, int n_detected); - virtual bool good() const; - - virtual Ptr clone() const; - -protected: - virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; - - double thresh_, init_thresh_, min_thresh_, max_thresh_; -}; - -CV_EXPORTS Mat windowedMatchingMask( const vector& keypoints1, const vector& keypoints2, - float maxDeltaX, float maxDeltaY ); - -/****************************************************************************************\ -* DescriptorExtractor * -\****************************************************************************************/ - -/* - * Abstract base class for computing descriptors for image keypoints. - * - * In this interface we assume a keypoint descriptor can be represented as a - * dense, fixed-dimensional vector of some basic type. Most descriptors used - * in practice follow this pattern, as it makes it very easy to compute - * distances between descriptors. Therefore we represent a collection of - * descriptors as a cv::Mat, where each row is one keypoint descriptor. - */ -class CV_EXPORTS_W DescriptorExtractor -{ -public: - virtual ~DescriptorExtractor(); - - /* - * Compute the descriptors for a set of keypoints in an image. - * image The image. - * keypoints The input keypoints. Keypoints for which a descriptor cannot be computed are removed. - * descriptors Copmputed descriptors. Row i is the descriptor for keypoint i. - */ - CV_WRAP void compute( const Mat& image, CV_OUT CV_IN_OUT vector& keypoints, CV_OUT Mat& descriptors ) const; - - /* - * Compute the descriptors for a keypoints collection detected in image collection. - * images Image collection. - * keypoints Input keypoints collection. keypoints[i] is keypoints detected in images[i]. - * Keypoints for which a descriptor cannot be computed are removed. - * descriptors Descriptor collection. descriptors[i] are descriptors computed for set keypoints[i]. - */ - void compute( const vector& images, vector >& keypoints, vector& descriptors ) const; - - virtual void read( const FileNode& ); - virtual void write( FileStorage& ) const; - - CV_WRAP virtual int descriptorSize() const = 0; - CV_WRAP virtual int descriptorType() const = 0; - - CV_WRAP virtual bool empty() const; - - CV_WRAP static Ptr create( const string& descriptorExtractorType ); - -protected: - virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const = 0; - - /* - * Remove keypoints within borderPixels of an image edge. - */ - static void removeBorderKeypoints( vector& keypoints, - Size imageSize, int borderSize ); -}; - -/* - * SiftDescriptorExtractor - */ -class CV_EXPORTS SiftDescriptorExtractor : public DescriptorExtractor -{ -public: - SiftDescriptorExtractor( const SIFT::DescriptorParams& descriptorParams=SIFT::DescriptorParams(), - const SIFT::CommonParams& commonParams=SIFT::CommonParams() ); - SiftDescriptorExtractor( double magnification, bool isNormalize=true, bool recalculateAngles=true, - int nOctaves=SIFT::CommonParams::DEFAULT_NOCTAVES, - int nOctaveLayers=SIFT::CommonParams::DEFAULT_NOCTAVE_LAYERS, - int firstOctave=SIFT::CommonParams::DEFAULT_FIRST_OCTAVE, - int angleMode=SIFT::CommonParams::FIRST_ANGLE ); - - virtual void read( const FileNode &fn ); - virtual void write( FileStorage &fs ) const; - - virtual int descriptorSize() const; - virtual int descriptorType() const; - -protected: - virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; - - SIFT sift; -}; - -/* - * SurfDescriptorExtractor - */ -class CV_EXPORTS SurfDescriptorExtractor : public DescriptorExtractor -{ -public: - SurfDescriptorExtractor( int nOctaves=4, int nOctaveLayers=2, bool extended=false, bool upright=false ); - - virtual void read( const FileNode &fn ); - virtual void write( FileStorage &fs ) const; - - virtual int descriptorSize() const; - virtual int descriptorType() const; - -protected: - virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; - - SURF surf; -}; - -/** The descriptor extractor for the ORB descriptor - * There are two ways to speed up its computation: - * - if you know the step size of the integral image, use setStepSize so that offsets are precomputed and cached - * - if you know the integral image, use setIntegralImage so that it is not recomputed. This calls - * setStepSize automatically - */ -class CV_EXPORTS OrbDescriptorExtractor : public cv::DescriptorExtractor -{ -public: - /** default constructor - * @param params parameters to use - */ - OrbDescriptorExtractor(ORB::CommonParams params = ORB::CommonParams()); - - /** destructor */ - ~OrbDescriptorExtractor() - { - } - - virtual int descriptorSize() const; - virtual int descriptorType() const; - - virtual void read(const cv::FileNode&); - virtual void write(cv::FileStorage&) const; - -protected: - void computeImpl(const cv::Mat& image, std::vector& keypoints, cv::Mat& descriptors) const; -private: - /** the ORB object we use for the computations */ - mutable ORB orb_; - /** The parameters used */ - ORB::CommonParams params_; -}; - -/* - * CalonderDescriptorExtractor - */ -template -class CV_EXPORTS CalonderDescriptorExtractor : public DescriptorExtractor -{ -public: - CalonderDescriptorExtractor( const string& classifierFile ); - - virtual void read( const FileNode &fn ); - virtual void write( FileStorage &fs ) const; - - virtual int descriptorSize() const { return classifier_.classes(); } - virtual int descriptorType() const { return DataType::type; } - - virtual bool empty() const; - -protected: - virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; - - RTreeClassifier classifier_; - static const int BORDER_SIZE = 16; -}; - -template -CalonderDescriptorExtractor::CalonderDescriptorExtractor(const std::string& classifier_file) -{ - classifier_.read( classifier_file.c_str() ); -} - -template -void CalonderDescriptorExtractor::computeImpl( const cv::Mat& image, - std::vector& keypoints, - cv::Mat& descriptors) const -{ - // Cannot compute descriptors for keypoints on the image border. - KeyPointsFilter::runByImageBorder(keypoints, image.size(), BORDER_SIZE); - - /// @todo Check 16-byte aligned - descriptors.create(keypoints.size(), classifier_.classes(), cv::DataType::type); - - int patchSize = RandomizedTree::PATCH_SIZE; - int offset = patchSize / 2; - for (size_t i = 0; i < keypoints.size(); ++i) - { - cv::Point2f pt = keypoints[i].pt; - IplImage ipl = image( Rect((int)(pt.x - offset), (int)(pt.y - offset), patchSize, patchSize) ); - classifier_.getSignature( &ipl, descriptors.ptr(i)); - } -} - -template -void CalonderDescriptorExtractor::read( const FileNode& ) -{} - -template -void CalonderDescriptorExtractor::write( FileStorage& ) const -{} - -template -bool CalonderDescriptorExtractor::empty() const -{ - return classifier_.trees_.empty(); -} - -/* - * OpponentColorDescriptorExtractor - * - * Adapts a descriptor extractor to compute descripors in Opponent Color Space - * (refer to van de Sande et al., CGIV 2008 "Color Descriptors for Object Category Recognition"). - * Input RGB image is transformed in Opponent Color Space. Then unadapted descriptor extractor - * (set in constructor) computes descriptors on each of the three channel and concatenate - * them into a single color descriptor. - */ -class CV_EXPORTS OpponentColorDescriptorExtractor : public DescriptorExtractor -{ -public: - OpponentColorDescriptorExtractor( const Ptr& descriptorExtractor ); - - virtual void read( const FileNode& ); - virtual void write( FileStorage& ) const; - - virtual int descriptorSize() const; - virtual int descriptorType() const; - - virtual bool empty() const; - -protected: - virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; - - Ptr descriptorExtractor; -}; - -/* - * BRIEF Descriptor - */ -class CV_EXPORTS BriefDescriptorExtractor : public DescriptorExtractor -{ -public: - static const int PATCH_SIZE = 48; - static const int KERNEL_SIZE = 9; - - // bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes. - BriefDescriptorExtractor( int bytes = 32 ); - - virtual void read( const FileNode& ); - virtual void write( FileStorage& ) const; - - virtual int descriptorSize() const; - virtual int descriptorType() const; - - /// @todo read and write for brief - -protected: - virtual void computeImpl(const Mat& image, std::vector& keypoints, Mat& descriptors) const; - - typedef void(*PixelTestFn)(const Mat&, const std::vector&, Mat&); - - int bytes_; - PixelTestFn test_fn_; -}; - -/****************************************************************************************\ -* Distance * -\****************************************************************************************/ -template -struct CV_EXPORTS Accumulator -{ - typedef T Type; -}; - -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; - -/* - * Squared Euclidean distance functor - */ -template -struct CV_EXPORTS SL2 -{ - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL2Sqr(a, b, size); - } -}; - -/* - * Euclidean distance functor - */ -template -struct CV_EXPORTS L2 -{ - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return (ResultType)sqrt((double)normL2Sqr(a, b, size)); - } -}; - -/* - * Manhattan distance (city block distance) functor - */ -template -struct CV_EXPORTS L1 -{ - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL1(a, b, size); - } -}; - -/* - * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor - * bit count of A exclusive XOR'ed with B - */ -struct CV_EXPORTS Hamming -{ - typedef unsigned char ValueType; - typedef int ResultType; - - /** this will count the bits in a ^ b - */ - ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const - { - return normHamming(a, b, size); - } -}; - -typedef Hamming HammingLUT; - -/****************************************************************************************\ -* DMatch * -\****************************************************************************************/ -/* - * Struct for matching: query descriptor index, train descriptor index, train image index and distance between descriptors. - */ -struct CV_EXPORTS_W_SIMPLE DMatch -{ - CV_WRAP DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(std::numeric_limits::max()) {} - CV_WRAP DMatch( int _queryIdx, int _trainIdx, float _distance ) : - queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} - CV_WRAP DMatch( int _queryIdx, int _trainIdx, int _imgIdx, float _distance ) : - queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} - - CV_PROP_RW int queryIdx; // query descriptor index - CV_PROP_RW int trainIdx; // train descriptor index - CV_PROP_RW int imgIdx; // train image index - - CV_PROP_RW float distance; - - // less is better - bool operator<( const DMatch &m ) const - { - return distance < m.distance; - } -}; - -/****************************************************************************************\ -* DescriptorMatcher * -\****************************************************************************************/ -/* - * Abstract base class for matching two sets of descriptors. - */ -class CV_EXPORTS_W DescriptorMatcher -{ -public: - virtual ~DescriptorMatcher(); - - /* - * Add descriptors to train descriptor collection. - * descriptors Descriptors to add. Each descriptors[i] is a descriptors set from one image. - */ - CV_WRAP virtual void add( const vector& descriptors ); - /* - * Get train descriptors collection. - */ - CV_WRAP const vector& getTrainDescriptors() const; - /* - * Clear train descriptors collection. - */ - CV_WRAP virtual void clear(); - - /* - * Return true if there are not train descriptors in collection. - */ - CV_WRAP virtual bool empty() const; - /* - * Return true if the matcher supports mask in match methods. - */ - CV_WRAP virtual bool isMaskSupported() const = 0; - - /* - * Train matcher (e.g. train flann index). - * In all methods to match the method train() is run every time before matching. - * Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation - * of this method, other matchers really train their inner structures - * (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation - * of train() should check the class object state and do traing/retraining - * only if the state requires that (e.g. FlannBasedMatcher trains flann::Index - * if it has not trained yet or if new descriptors have been added to the train - * collection). - */ - CV_WRAP virtual void train(); - /* - * Group of methods to match descriptors from image pair. - * Method train() is run in this methods. - */ - // Find one best match for each query descriptor (if mask is empty). - CV_WRAP void match( const Mat& queryDescriptors, const Mat& trainDescriptors, - CV_OUT vector& matches, const Mat& mask=Mat() ) const; - // Find k best matches for each query descriptor (in increasing order of distances). - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - CV_WRAP void knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, - CV_OUT vector >& matches, int k, - const Mat& mask=Mat(), bool compactResult=false ) const; - // Find best matches for each query descriptor which have distance less than - // maxDistance (in increasing order of distances). - void radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, - vector >& matches, float maxDistance, - const Mat& mask=Mat(), bool compactResult=false ) const; - /* - * Group of methods to match descriptors from one image to image set. - * See description of similar methods for matching image pair above. - */ - CV_WRAP void match( const Mat& queryDescriptors, CV_OUT vector& matches, - const vector& masks=vector() ); - CV_WRAP void knnMatch( const Mat& queryDescriptors, CV_OUT vector >& matches, int k, - const vector& masks=vector(), bool compactResult=false ); - void radiusMatch( const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks=vector(), bool compactResult=false ); - - // Reads matcher object from a file node - virtual void read( const FileNode& ); - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const; - - // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies - // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters - // but with empty train data. - virtual Ptr clone( bool emptyTrainData=false ) const = 0; - - CV_WRAP static Ptr create( const string& descriptorMatcherType ); -protected: - /* - * Class to work with descriptors from several images as with one merged matrix. - * It is used e.g. in FlannBasedMatcher. - */ - class CV_EXPORTS DescriptorCollection - { - public: - DescriptorCollection(); - DescriptorCollection( const DescriptorCollection& collection ); - virtual ~DescriptorCollection(); - - // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. - void set( const vector& descriptors ); - virtual void clear(); - - const Mat& getDescriptors() const; - const Mat getDescriptor( int imgIdx, int localDescIdx ) const; - const Mat getDescriptor( int globalDescIdx ) const; - void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; - - int size() const; - - protected: - Mat mergedDescriptors; - vector startIdxs; - }; - - // In fact the matching is implemented only by the following two methods. These methods suppose - // that the class object has been trained already. Public match methods call these methods - // after calling train(). - virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks=vector(), bool compactResult=false ) = 0; - virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks=vector(), bool compactResult=false ) = 0; - - static bool isPossibleMatch( const Mat& mask, int queryIdx, int trainIdx ); - static bool isMaskedOut( const vector& masks, int queryIdx ); - - static Mat clone_op( Mat m ) { return m.clone(); } - void checkMasks( const vector& masks, int queryDescriptorsCount ) const; - - // Collection of descriptors from train images. - vector trainDescCollection; -}; - -/* - * Brute-force descriptor matcher. - * - * For each descriptor in the first set, this matcher finds the closest - * descriptor in the second set by trying each one. - * - * For efficiency, BruteForceMatcher is templated on the distance metric. - * For float descriptors, a common choice would be cv::L2. - */ -template -class CV_EXPORTS BruteForceMatcher : public DescriptorMatcher -{ -public: - BruteForceMatcher( Distance d = Distance() ) : distance(d) {} - virtual ~BruteForceMatcher() {} - - virtual bool isMaskSupported() const { return true; } - - virtual Ptr clone( bool emptyTrainData=false ) const; - -protected: - virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks=vector(), bool compactResult=false ); - virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks=vector(), bool compactResult=false ); - - Distance distance; - -private: - /* - * Next two methods are used to implement specialization. - */ - static void commonKnnMatchImpl( BruteForceMatcher& matcher, - const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks, bool compactResult ); - static void commonRadiusMatchImpl( BruteForceMatcher& matcher, - const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks, bool compactResult ); -}; - -template -Ptr BruteForceMatcher::clone( bool emptyTrainData ) const -{ - BruteForceMatcher* matcher = new BruteForceMatcher(distance); - if( !emptyTrainData ) - { - matcher->trainDescCollection.resize(trainDescCollection.size()); - std::transform( trainDescCollection.begin(), trainDescCollection.end(), - matcher->trainDescCollection.begin(), clone_op ); - } - return matcher; -} - -template -void BruteForceMatcher::knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks, bool compactResult ) -{ - commonKnnMatchImpl( *this, queryDescriptors, matches, k, masks, compactResult ); -} - -template -void BruteForceMatcher::radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, - float maxDistance, const vector& masks, bool compactResult ) -{ - commonRadiusMatchImpl( *this, queryDescriptors, matches, maxDistance, masks, compactResult ); -} - -template -inline void BruteForceMatcher::commonKnnMatchImpl( BruteForceMatcher& matcher, - const Mat& queryDescriptors, vector >& matches, int knn, - const vector& masks, bool compactResult ) -{ - typedef typename Distance::ValueType ValueType; - typedef typename Distance::ResultType DistanceType; - CV_DbgAssert( !queryDescriptors.empty() ); - CV_Assert( DataType::type == queryDescriptors.type() ); - - int dimension = queryDescriptors.cols; - matches.reserve(queryDescriptors.rows); - - size_t imgCount = matcher.trainDescCollection.size(); - vector allDists( imgCount ); // distances between one query descriptor and all train descriptors - for( size_t i = 0; i < imgCount; i++ ) - allDists[i] = Mat( 1, matcher.trainDescCollection[i].rows, DataType::type ); - - for( int qIdx = 0; qIdx < queryDescriptors.rows; qIdx++ ) - { - if( matcher.isMaskedOut( masks, qIdx ) ) - { - if( !compactResult ) // push empty vector - matches.push_back( vector() ); - } - else - { - // 1. compute distances between i-th query descriptor and all train descriptors - for( size_t iIdx = 0; iIdx < imgCount; iIdx++ ) - { - CV_Assert( DataType::type == matcher.trainDescCollection[iIdx].type() || matcher.trainDescCollection[iIdx].empty() ); - CV_Assert( queryDescriptors.cols == matcher.trainDescCollection[iIdx].cols || - matcher.trainDescCollection[iIdx].empty() ); - - const ValueType* d1 = (const ValueType*)(queryDescriptors.data + queryDescriptors.step*qIdx); - allDists[iIdx].setTo( Scalar::all(std::numeric_limits::max()) ); - for( int tIdx = 0; tIdx < matcher.trainDescCollection[iIdx].rows; tIdx++ ) - { - if( masks.empty() || matcher.isPossibleMatch(masks[iIdx], qIdx, tIdx) ) - { - const ValueType* d2 = (const ValueType*)(matcher.trainDescCollection[iIdx].data + - matcher.trainDescCollection[iIdx].step*tIdx); - allDists[iIdx].at(0, tIdx) = matcher.distance(d1, d2, dimension); - } - } - } - - // 2. choose k nearest matches for query[i] - matches.push_back( vector() ); - vector >::reverse_iterator curMatches = matches.rbegin(); - for( int k = 0; k < knn; k++ ) - { - DMatch bestMatch; - bestMatch.distance = std::numeric_limits::max(); - for( size_t iIdx = 0; iIdx < imgCount; iIdx++ ) - { - if( !allDists[iIdx].empty() ) - { - double minVal; - Point minLoc; - minMaxLoc( allDists[iIdx], &minVal, 0, &minLoc, 0 ); - if( minVal < bestMatch.distance ) - bestMatch = DMatch( qIdx, minLoc.x, (int)iIdx, (float)minVal ); - } - } - if( bestMatch.trainIdx == -1 ) - break; - - allDists[bestMatch.imgIdx].at(0, bestMatch.trainIdx) = std::numeric_limits::max(); - curMatches->push_back( bestMatch ); - } - //TODO should already be sorted at this point? - std::sort( curMatches->begin(), curMatches->end() ); - } - } -} - -template -inline void BruteForceMatcher::commonRadiusMatchImpl( BruteForceMatcher& matcher, - const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks, bool compactResult ) -{ - typedef typename Distance::ValueType ValueType; - typedef typename Distance::ResultType DistanceType; - CV_DbgAssert( !queryDescriptors.empty() ); - CV_Assert( DataType::type == queryDescriptors.type() ); - - int dimension = queryDescriptors.cols; - matches.reserve(queryDescriptors.rows); - - size_t imgCount = matcher.trainDescCollection.size(); - for( int qIdx = 0; qIdx < queryDescriptors.rows; qIdx++ ) - { - if( matcher.isMaskedOut( masks, qIdx ) ) - { - if( !compactResult ) // push empty vector - matches.push_back( vector() ); - } - else - { - matches.push_back( vector() ); - vector >::reverse_iterator curMatches = matches.rbegin(); - for( size_t iIdx = 0; iIdx < imgCount; iIdx++ ) - { - CV_Assert( DataType::type == matcher.trainDescCollection[iIdx].type() || - matcher.trainDescCollection[iIdx].empty() ); - CV_Assert( queryDescriptors.cols == matcher.trainDescCollection[iIdx].cols || - matcher.trainDescCollection[iIdx].empty() ); - - const ValueType* d1 = (const ValueType*)(queryDescriptors.data + queryDescriptors.step*qIdx); - for( int tIdx = 0; tIdx < matcher.trainDescCollection[iIdx].rows; tIdx++ ) - { - if( masks.empty() || matcher.isPossibleMatch(masks[iIdx], qIdx, tIdx) ) - { - const ValueType* d2 = (const ValueType*)(matcher.trainDescCollection[iIdx].data + - matcher.trainDescCollection[iIdx].step*tIdx); - DistanceType d = matcher.distance(d1, d2, dimension); - if( d < maxDistance ) - curMatches->push_back( DMatch( qIdx, tIdx, (int)iIdx, (float)d ) ); - } - } - } - std::sort( curMatches->begin(), curMatches->end() ); - } - } -} - -/* - * BruteForceMatcher L2 specialization - */ -template<> -void BruteForceMatcher >::knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks, bool compactResult ); -template<> -void BruteForceMatcher >::radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, - float maxDistance, const vector& masks, bool compactResult ); - -/* - * Flann based matcher - */ -class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher -{ -public: - CV_WRAP FlannBasedMatcher( const Ptr& indexParams=new flann::KDTreeIndexParams(), - const Ptr& searchParams=new flann::SearchParams() ); - - virtual void add( const vector& descriptors ); - virtual void clear(); - - // Reads matcher object from a file node - virtual void read( const FileNode& ); - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const; - - virtual void train(); - virtual bool isMaskSupported() const; - - virtual Ptr clone( bool emptyTrainData=false ) const; - -protected: - static void convertToDMatches( const DescriptorCollection& descriptors, - const Mat& indices, const Mat& distances, - vector >& matches ); - - virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, - const vector& masks=vector(), bool compactResult=false ); - virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, - const vector& masks=vector(), bool compactResult=false ); - - Ptr indexParams; - Ptr searchParams; - Ptr flannIndex; - - DescriptorCollection mergedDescriptors; - int addedDescCount; -}; - -/****************************************************************************************\ -* GenericDescriptorMatcher * -\****************************************************************************************/ -/* - * Abstract interface for a keypoint descriptor and matcher - */ -class GenericDescriptorMatcher; -typedef GenericDescriptorMatcher GenericDescriptorMatch; - -class CV_EXPORTS GenericDescriptorMatcher -{ -public: - GenericDescriptorMatcher(); - virtual ~GenericDescriptorMatcher(); - - /* - * Add train collection: images and keypoints from them. - * images A set of train images. - * ketpoints Keypoint collection that have been detected on train images. - * - * Keypoints for which a descriptor cannot be computed are removed. Such keypoints - * must be filtered in this method befor adding keypoints to train collection "trainPointCollection". - * If inheritor class need perform such prefiltering the method add() must be overloaded. - * In the other class methods programmer has access to the train keypoints by a constant link. - */ - virtual void add( const vector& images, - vector >& keypoints ); - - const vector& getTrainImages() const; - const vector >& getTrainKeypoints() const; - - /* - * Clear images and keypoints storing in train collection. - */ - virtual void clear(); - /* - * Returns true if matcher supports mask to match descriptors. - */ - virtual bool isMaskSupported() = 0; - /* - * Train some inner structures (e.g. flann index or decision trees). - * train() methods is run every time in matching methods. So the method implementation - * should has a check whether these inner structures need be trained/retrained or not. - */ - virtual void train(); - - /* - * Classifies query keypoints. - * queryImage The query image - * queryKeypoints Keypoints from the query image - * trainImage The train image - * trainKeypoints Keypoints from the train image - */ - // Classify keypoints from query image under one train image. - void classify( const Mat& queryImage, vector& queryKeypoints, - const Mat& trainImage, vector& trainKeypoints ) const; - // Classify keypoints from query image under train image collection. - void classify( const Mat& queryImage, vector& queryKeypoints ); - - /* - * Group of methods to match keypoints from image pair. - * Keypoints for which a descriptor cannot be computed are removed. - * train() method is called here. - */ - // Find one best match for each query descriptor (if mask is empty). - void match( const Mat& queryImage, vector& queryKeypoints, - const Mat& trainImage, vector& trainKeypoints, - vector& matches, const Mat& mask=Mat() ) const; - // Find k best matches for each query keypoint (in increasing order of distances). - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. - // If compactResult is true matches vector will not contain matches for fully masked out query descriptors. - void knnMatch( const Mat& queryImage, vector& queryKeypoints, - const Mat& trainImage, vector& trainKeypoints, - vector >& matches, int k, - const Mat& mask=Mat(), bool compactResult=false ) const; - // Find best matches for each query descriptor which have distance less than maxDistance (in increasing order of distances). - void radiusMatch( const Mat& queryImage, vector& queryKeypoints, - const Mat& trainImage, vector& trainKeypoints, - vector >& matches, float maxDistance, - const Mat& mask=Mat(), bool compactResult=false ) const; - /* - * Group of methods to match keypoints from one image to image set. - * See description of similar methods for matching image pair above. - */ - void match( const Mat& queryImage, vector& queryKeypoints, - vector& matches, const vector& masks=vector() ); - void knnMatch( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, int k, - const vector& masks=vector(), bool compactResult=false ); - void radiusMatch( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, float maxDistance, - const vector& masks=vector(), bool compactResult=false ); - - // Reads matcher object from a file node - virtual void read( const FileNode& ); - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const; - - // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty) - virtual bool empty() const; - - // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies - // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters - // but with empty train data. - virtual Ptr clone( bool emptyTrainData=false ) const = 0; - - static Ptr create( const string& genericDescritptorMatcherType, - const string ¶msFilename=string() ); - -protected: - // In fact the matching is implemented only by the following two methods. These methods suppose - // that the class object has been trained already. Public match methods call these methods - // after calling train(). - virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, int k, - const vector& masks, bool compactResult ) = 0; - virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, float maxDistance, - const vector& masks, bool compactResult ) = 0; - /* - * A storage for sets of keypoints together with corresponding images and class IDs - */ - class CV_EXPORTS KeyPointCollection - { - public: - KeyPointCollection(); - KeyPointCollection( const KeyPointCollection& collection ); - void add( const vector& images, const vector >& keypoints ); - void clear(); - - // Returns the total number of keypoints in the collection - size_t keypointCount() const; - size_t imageCount() const; - - const vector >& getKeypoints() const; - const vector& getKeypoints( int imgIdx ) const; - const KeyPoint& getKeyPoint( int imgIdx, int localPointIdx ) const; - const KeyPoint& getKeyPoint( int globalPointIdx ) const; - void getLocalIdx( int globalPointIdx, int& imgIdx, int& localPointIdx ) const; - - const vector& getImages() const; - const Mat& getImage( int imgIdx ) const; - - protected: - int pointCount; - - vector images; - vector > keypoints; - // global indices of the first points in each image, startIndices.size() = keypoints.size() - vector startIndices; - - private: - static Mat clone_op( Mat m ) { return m.clone(); } - }; - - KeyPointCollection trainPointCollection; -}; - -/* - * OneWayDescriptorMatcher - */ -class OneWayDescriptorMatcher; -typedef OneWayDescriptorMatcher OneWayDescriptorMatch; - -class CV_EXPORTS OneWayDescriptorMatcher : public GenericDescriptorMatcher -{ -public: - class CV_EXPORTS Params - { - public: - static const int POSE_COUNT = 500; - static const int PATCH_WIDTH = 24; - static const int PATCH_HEIGHT = 24; - static float GET_MIN_SCALE() { return 0.7f; } - static float GET_MAX_SCALE() { return 1.5f; } - static float GET_STEP_SCALE() { return 1.2f; } - - Params( int poseCount = POSE_COUNT, - Size patchSize = Size(PATCH_WIDTH, PATCH_HEIGHT), - string pcaFilename = string(), - string trainPath = string(), string trainImagesList = string(), - float minScale = GET_MIN_SCALE(), float maxScale = GET_MAX_SCALE(), - float stepScale = GET_STEP_SCALE() ); - - int poseCount; - Size patchSize; - string pcaFilename; - string trainPath; - string trainImagesList; - - float minScale, maxScale, stepScale; - }; - - OneWayDescriptorMatcher( const Params& params=Params() ); - virtual ~OneWayDescriptorMatcher(); - - void initialize( const Params& params, const Ptr& base=Ptr() ); - - // Clears keypoints storing in collection and OneWayDescriptorBase - virtual void clear(); - - virtual void train(); - - virtual bool isMaskSupported(); - - virtual void read( const FileNode &fn ); - virtual void write( FileStorage& fs ) const; - - virtual bool empty() const; - - virtual Ptr clone( bool emptyTrainData=false ) const; - -protected: - // Matches a set of keypoints from a single image of the training set. A rectangle with a center in a keypoint - // and size (patch_width/2*scale, patch_height/2*scale) is cropped from the source image for each - // keypoint. scale is iterated from DescriptorOneWayParams::min_scale to DescriptorOneWayParams::max_scale. - // The minimum distance to each training patch with all its affine poses is found over all scales. - // The class ID of a match is returned for each keypoint. The distance is calculated over PCA components - // loaded with DescriptorOneWay::Initialize, kd tree is used for finding minimum distances. - virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, int k, - const vector& masks, bool compactResult ); - virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, float maxDistance, - const vector& masks, bool compactResult ); - - Ptr base; - Params params; - int prevTrainCount; -}; - -/* - * FernDescriptorMatcher - */ -class FernDescriptorMatcher; -typedef FernDescriptorMatcher FernDescriptorMatch; - -class CV_EXPORTS FernDescriptorMatcher : public GenericDescriptorMatcher -{ -public: - class CV_EXPORTS Params - { - public: - Params( int nclasses=0, - int patchSize=FernClassifier::PATCH_SIZE, - int signatureSize=FernClassifier::DEFAULT_SIGNATURE_SIZE, - int nstructs=FernClassifier::DEFAULT_STRUCTS, - int structSize=FernClassifier::DEFAULT_STRUCT_SIZE, - int nviews=FernClassifier::DEFAULT_VIEWS, - int compressionMethod=FernClassifier::COMPRESSION_NONE, - const PatchGenerator& patchGenerator=PatchGenerator() ); - - Params( const string& filename ); - - int nclasses; - int patchSize; - int signatureSize; - int nstructs; - int structSize; - int nviews; - int compressionMethod; - PatchGenerator patchGenerator; - - string filename; - }; - - FernDescriptorMatcher( const Params& params=Params() ); - virtual ~FernDescriptorMatcher(); - - virtual void clear(); - - virtual void train(); - - virtual bool isMaskSupported(); - - virtual void read( const FileNode &fn ); - virtual void write( FileStorage& fs ) const; - virtual bool empty() const; - - virtual Ptr clone( bool emptyTrainData=false ) const; - -protected: - virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, int k, - const vector& masks, bool compactResult ); - virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, float maxDistance, - const vector& masks, bool compactResult ); - - void trainFernClassifier(); - void calcBestProbAndMatchIdx( const Mat& image, const Point2f& pt, - float& bestProb, int& bestMatchIdx, vector& signature ); - Ptr classifier; - Params params; - int prevTrainCount; -}; - -/****************************************************************************************\ -* VectorDescriptorMatcher * -\****************************************************************************************/ - -/* - * A class used for matching descriptors that can be described as vectors in a finite-dimensional space - */ -class VectorDescriptorMatcher; -typedef VectorDescriptorMatcher VectorDescriptorMatch; - -class CV_EXPORTS VectorDescriptorMatcher : public GenericDescriptorMatcher -{ -public: - VectorDescriptorMatcher( const Ptr& extractor, const Ptr& matcher ); - virtual ~VectorDescriptorMatcher(); - - virtual void add( const vector& imgCollection, - vector >& pointCollection ); - - virtual void clear(); - - virtual void train(); - - virtual bool isMaskSupported(); - - virtual void read( const FileNode& fn ); - virtual void write( FileStorage& fs ) const; - virtual bool empty() const; - - virtual Ptr clone( bool emptyTrainData=false ) const; - -protected: - virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, int k, - const vector& masks, bool compactResult ); - virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, - vector >& matches, float maxDistance, - const vector& masks, bool compactResult ); - - Ptr extractor; - Ptr matcher; -}; - -/****************************************************************************************\ -* Drawing functions * -\****************************************************************************************/ -struct CV_EXPORTS DrawMatchesFlags -{ - enum{ DEFAULT = 0, // Output image matrix will be created (Mat::create), - // i.e. existing memory of output image may be reused. - // Two source image, matches and single keypoints will be drawn. - // For each keypoint only the center point will be drawn (without - // the circle around keypoint with keypoint size and orientation). - DRAW_OVER_OUTIMG = 1, // Output image matrix will not be created (Mat::create). - // Matches will be drawn on existing content of output image. - NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn. - DRAW_RICH_KEYPOINTS = 4 // For each keypoint the circle around keypoint with keypoint size and - // orientation will be drawn. - }; -}; - -// Draw keypoints. -CV_EXPORTS void drawKeypoints( const Mat& image, const vector& keypoints, Mat& outImage, - const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT ); - -// Draws matches of keypints from two images on output image. -CV_EXPORTS void drawMatches( const Mat& img1, const vector& keypoints1, - const Mat& img2, const vector& keypoints2, - const vector& matches1to2, Mat& outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const vector& matchesMask=vector(), int flags=DrawMatchesFlags::DEFAULT ); - -CV_EXPORTS void drawMatches( const Mat& img1, const vector& keypoints1, - const Mat& img2, const vector& keypoints2, - const vector >& matches1to2, Mat& outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const vector >& matchesMask=vector >(), int flags=DrawMatchesFlags::DEFAULT ); - -/****************************************************************************************\ -* Functions to evaluate the feature detectors and [generic] descriptor extractors * -\****************************************************************************************/ - -CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, - vector* keypoints1, vector* keypoints2, - float& repeatability, int& correspCount, - const Ptr& fdetector=Ptr() ); - -CV_EXPORTS void computeRecallPrecisionCurve( const vector >& matches1to2, - const vector >& correctMatches1to2Mask, - vector& recallPrecisionCurve ); - -CV_EXPORTS float getRecall( const vector& recallPrecisionCurve, float l_precision ); -CV_EXPORTS int getNearestPoint( const vector& recallPrecisionCurve, float l_precision ); - -CV_EXPORTS void evaluateGenericDescriptorMatcher( const Mat& img1, const Mat& img2, const Mat& H1to2, - vector& keypoints1, vector& keypoints2, - vector >* matches1to2, vector >* correctMatches1to2Mask, - vector& recallPrecisionCurve, - const Ptr& dmatch=Ptr() ); - - -/****************************************************************************************\ -* Bag of visual words * -\****************************************************************************************/ -/* - * Abstract base class for training of a 'bag of visual words' vocabulary from a set of descriptors - */ -class CV_EXPORTS BOWTrainer -{ -public: - BOWTrainer(); - virtual ~BOWTrainer(); - - void add( const Mat& descriptors ); - const vector& getDescriptors() const; - int descripotorsCount() const; - - virtual void clear(); - - /* - * Train visual words vocabulary, that is cluster training descriptors and - * compute cluster centers. - * Returns cluster centers. - * - * descriptors Training descriptors computed on images keypoints. - */ - virtual Mat cluster() const = 0; - virtual Mat cluster( const Mat& descriptors ) const = 0; - -protected: - vector descriptors; - int size; -}; - -/* - * This is BOWTrainer using cv::kmeans to get vocabulary. - */ -class CV_EXPORTS BOWKMeansTrainer : public BOWTrainer -{ -public: - BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), - int attempts=3, int flags=KMEANS_PP_CENTERS ); - virtual ~BOWKMeansTrainer(); - - // Returns trained vocabulary (i.e. cluster centers). - virtual Mat cluster() const; - virtual Mat cluster( const Mat& descriptors ) const; - -protected: - - int clusterCount; - TermCriteria termcrit; - int attempts; - int flags; -}; - -/* - * Class to compute image descriptor using bag of visual words. - */ -class CV_EXPORTS BOWImgDescriptorExtractor -{ -public: - BOWImgDescriptorExtractor( const Ptr& dextractor, - const Ptr& dmatcher ); - virtual ~BOWImgDescriptorExtractor(); - - void setVocabulary( const Mat& vocabulary ); - const Mat& getVocabulary() const; - void compute( const Mat& image, vector& keypoints, Mat& imgDescriptor, - vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); - // compute() is not constant because DescriptorMatcher::match is not constant - - int descriptorSize() const; - int descriptorType() const; - -protected: - Mat vocabulary; - Ptr dextractor; - Ptr dmatcher; -}; - -} /* namespace cv */ - -#endif /* __cplusplus */ - -#endif - -/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NCV.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NCV.hpp deleted file mode 100755 index 530aa0b..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NCV.hpp +++ /dev/null @@ -1,1014 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2009-2010, NVIDIA 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 the copyright holders 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 _ncv_hpp_ -#define _ncv_hpp_ - -#if (defined WIN32 || defined _WIN32 || defined WINCE) && defined CVAPI_EXPORTS - #define NCV_EXPORTS __declspec(dllexport) -#else - #define NCV_EXPORTS -#endif - -#ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN -#endif - -#include -#include -#include - - -//============================================================================== -// -// Compile-time assert functionality -// -//============================================================================== - - -/** -* Compile-time assert namespace -*/ -namespace NcvCTprep -{ - template - struct CT_ASSERT_FAILURE; - - template <> - struct CT_ASSERT_FAILURE {}; - - template - struct assertTest{}; -} - - -#define NCV_CT_PREP_PASTE_AUX(a,b) a##b ///< Concatenation indirection macro -#define NCV_CT_PREP_PASTE(a,b) NCV_CT_PREP_PASTE_AUX(a, b) ///< Concatenation macro - - -/** -* Performs compile-time assertion of a condition on the file scope -*/ -#define NCV_CT_ASSERT(X) \ - typedef NcvCTprep::assertTest)> \ - NCV_CT_PREP_PASTE(__ct_assert_typedef_, __LINE__) - - - -//============================================================================== -// -// Alignment macros -// -//============================================================================== - - -#if !defined(__align__) && !defined(__CUDACC__) - #if defined(_WIN32) || defined(_WIN64) - #define __align__(n) __declspec(align(n)) - #elif defined(__unix__) - #define __align__(n) __attribute__((__aligned__(n))) - #endif -#endif - - -//============================================================================== -// -// Integral and compound types of guaranteed size -// -//============================================================================== - - -typedef bool NcvBool; -typedef long long Ncv64s; - -#if defined(__APPLE__) && !defined(__CUDACC__) - typedef uint64_t Ncv64u; -#else - typedef unsigned long long Ncv64u; -#endif - -typedef int Ncv32s; -typedef unsigned int Ncv32u; -typedef short Ncv16s; -typedef unsigned short Ncv16u; -typedef char Ncv8s; -typedef unsigned char Ncv8u; -typedef float Ncv32f; -typedef double Ncv64f; - - -struct NcvRect8u -{ - Ncv8u x; - Ncv8u y; - Ncv8u width; - Ncv8u height; - __host__ __device__ NcvRect8u() : x(0), y(0), width(0), height(0) {}; - __host__ __device__ NcvRect8u(Ncv8u x, Ncv8u y, Ncv8u width, Ncv8u height) : x(x), y(y), width(width), height(height) {} -}; - - -struct NcvRect32s -{ - Ncv32s x; ///< x-coordinate of upper left corner. - Ncv32s y; ///< y-coordinate of upper left corner. - Ncv32s width; ///< Rectangle width. - Ncv32s height; ///< Rectangle height. - __host__ __device__ NcvRect32s() : x(0), y(0), width(0), height(0) {}; - __host__ __device__ NcvRect32s(Ncv32s x, Ncv32s y, Ncv32s width, Ncv32s height) : x(x), y(y), width(width), height(height) {} -}; - - -struct NcvRect32u -{ - Ncv32u x; ///< x-coordinate of upper left corner. - Ncv32u y; ///< y-coordinate of upper left corner. - Ncv32u width; ///< Rectangle width. - Ncv32u height; ///< Rectangle height. - __host__ __device__ NcvRect32u() : x(0), y(0), width(0), height(0) {}; - __host__ __device__ NcvRect32u(Ncv32u x, Ncv32u y, Ncv32u width, Ncv32u height) : x(x), y(y), width(width), height(height) {} -}; - - -struct NcvSize32s -{ - Ncv32s width; ///< Rectangle width. - Ncv32s height; ///< Rectangle height. - __host__ __device__ NcvSize32s() : width(0), height(0) {}; - __host__ __device__ NcvSize32s(Ncv32s width, Ncv32s height) : width(width), height(height) {} -}; - - -struct NcvSize32u -{ - Ncv32u width; ///< Rectangle width. - Ncv32u height; ///< Rectangle height. - __host__ __device__ NcvSize32u() : width(0), height(0) {}; - __host__ __device__ NcvSize32u(Ncv32u width, Ncv32u height) : width(width), height(height) {} - __host__ __device__ bool operator == (const NcvSize32u &another) const {return this->width == another.width && this->height == another.height;} -}; - - -struct NcvPoint2D32s -{ - Ncv32s x; ///< Point X. - Ncv32s y; ///< Point Y. - __host__ __device__ NcvPoint2D32s() : x(0), y(0) {}; - __host__ __device__ NcvPoint2D32s(Ncv32s x, Ncv32s y) : x(x), y(y) {} -}; - - -struct NcvPoint2D32u -{ - Ncv32u x; ///< Point X. - Ncv32u y; ///< Point Y. - __host__ __device__ NcvPoint2D32u() : x(0), y(0) {}; - __host__ __device__ NcvPoint2D32u(Ncv32u x, Ncv32u y) : x(x), y(y) {} -}; - - -NCV_CT_ASSERT(sizeof(NcvBool) <= 4); -NCV_CT_ASSERT(sizeof(Ncv64s) == 8); -NCV_CT_ASSERT(sizeof(Ncv64u) == 8); -NCV_CT_ASSERT(sizeof(Ncv32s) == 4); -NCV_CT_ASSERT(sizeof(Ncv32u) == 4); -NCV_CT_ASSERT(sizeof(Ncv16s) == 2); -NCV_CT_ASSERT(sizeof(Ncv16u) == 2); -NCV_CT_ASSERT(sizeof(Ncv8s) == 1); -NCV_CT_ASSERT(sizeof(Ncv8u) == 1); -NCV_CT_ASSERT(sizeof(Ncv32f) == 4); -NCV_CT_ASSERT(sizeof(Ncv64f) == 8); -NCV_CT_ASSERT(sizeof(NcvRect8u) == sizeof(Ncv32u)); -NCV_CT_ASSERT(sizeof(NcvRect32s) == 4 * sizeof(Ncv32s)); -NCV_CT_ASSERT(sizeof(NcvRect32u) == 4 * sizeof(Ncv32u)); -NCV_CT_ASSERT(sizeof(NcvSize32u) == 2 * sizeof(Ncv32u)); -NCV_CT_ASSERT(sizeof(NcvPoint2D32u) == 2 * sizeof(Ncv32u)); - - -//============================================================================== -// -// Persistent constants -// -//============================================================================== - - -const Ncv32u K_WARP_SIZE = 32; -const Ncv32u K_LOG2_WARP_SIZE = 5; - - -//============================================================================== -// -// Error handling -// -//============================================================================== - - -NCV_EXPORTS void ncvDebugOutput(const std::string &msg); - - -typedef void NCVDebugOutputHandler(const std::string &msg); - - -NCV_EXPORTS void ncvSetDebugOutputHandler(NCVDebugOutputHandler* func); - - -#define ncvAssertPrintCheck(pred, msg) \ - do \ - { \ - if (!(pred)) \ - { \ - std::ostringstream oss; \ - oss << "NCV Assertion Failed: " << msg << ", file=" << __FILE__ << ", line=" << __LINE__ << std::endl; \ - ncvDebugOutput(oss.str()); \ - } \ - } while (0) - - -#define ncvAssertPrintReturn(pred, msg, err) \ - do \ - { \ - ncvAssertPrintCheck(pred, msg); \ - if (!(pred)) return err; \ - } while (0) - - -#define ncvAssertReturn(pred, err) \ - ncvAssertPrintReturn(pred, "retcode=" << (int)err, err) - - -#define ncvAssertReturnNcvStat(ncvOp) \ - do \ - { \ - NCVStatus _ncvStat = ncvOp; \ - ncvAssertPrintReturn(NCV_SUCCESS==_ncvStat, "NcvStat=" << (int)_ncvStat, _ncvStat); \ - } while (0) - - -#define ncvAssertCUDAReturn(cudacall, errCode) \ - do \ - { \ - cudaError_t resCall = cudacall; \ - cudaError_t resGLE = cudaGetLastError(); \ - ncvAssertPrintReturn(cudaSuccess==resCall && cudaSuccess==resGLE, "cudaError_t=" << (int)(resCall | resGLE), errCode); \ - } while (0) - - -/** -* Return-codes for status notification, errors and warnings -*/ -enum -{ - //NCV statuses - NCV_SUCCESS, - NCV_UNKNOWN_ERROR, - - NCV_CUDA_ERROR, - NCV_NPP_ERROR, - NCV_FILE_ERROR, - - NCV_NULL_PTR, - NCV_INCONSISTENT_INPUT, - NCV_TEXTURE_BIND_ERROR, - NCV_DIMENSIONS_INVALID, - - NCV_INVALID_ROI, - NCV_INVALID_STEP, - NCV_INVALID_SCALE, - - NCV_ALLOCATOR_NOT_INITIALIZED, - NCV_ALLOCATOR_BAD_ALLOC, - NCV_ALLOCATOR_BAD_DEALLOC, - NCV_ALLOCATOR_INSUFFICIENT_CAPACITY, - NCV_ALLOCATOR_DEALLOC_ORDER, - NCV_ALLOCATOR_BAD_REUSE, - - NCV_MEM_COPY_ERROR, - NCV_MEM_RESIDENCE_ERROR, - NCV_MEM_INSUFFICIENT_CAPACITY, - - NCV_HAAR_INVALID_PIXEL_STEP, - NCV_HAAR_TOO_MANY_FEATURES_IN_CLASSIFIER, - NCV_HAAR_TOO_MANY_FEATURES_IN_CASCADE, - NCV_HAAR_TOO_LARGE_FEATURES, - NCV_HAAR_XML_LOADING_EXCEPTION, - - NCV_NOIMPL_HAAR_TILTED_FEATURES, - - NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW, - - //NPP statuses - NPPST_SUCCESS = NCV_SUCCESS, ///< Successful operation (same as NPP_NO_ERROR) - NPPST_ERROR, ///< Unknown error - NPPST_CUDA_KERNEL_EXECUTION_ERROR, ///< CUDA kernel execution error - NPPST_NULL_POINTER_ERROR, ///< NULL pointer argument error - NPPST_TEXTURE_BIND_ERROR, ///< CUDA texture binding error or non-zero offset returned - NPPST_MEMCPY_ERROR, ///< CUDA memory copy error - NPPST_MEM_ALLOC_ERR, ///< CUDA memory allocation error - NPPST_MEMFREE_ERR, ///< CUDA memory deallocation error - - //NPPST statuses - NPPST_INVALID_ROI, ///< Invalid region of interest argument - NPPST_INVALID_STEP, ///< Invalid image lines step argument (check sign, alignment, relation to image width) - NPPST_INVALID_SCALE, ///< Invalid scale parameter passed - NPPST_MEM_INSUFFICIENT_BUFFER, ///< Insufficient user-allocated buffer - NPPST_MEM_RESIDENCE_ERROR, ///< Memory residence error detected (check if pointers should be device or pinned) - NPPST_MEM_INTERNAL_ERROR, ///< Internal memory management error - - NCV_LAST_STATUS ///< Marker to continue error numeration in other files -}; - - -typedef Ncv32u NCVStatus; - - -#define NCV_SET_SKIP_COND(x) \ - bool __ncv_skip_cond = x - - -#define NCV_RESET_SKIP_COND(x) \ - __ncv_skip_cond = x - - -#define NCV_SKIP_COND_BEGIN \ - if (!__ncv_skip_cond) { - - -#define NCV_SKIP_COND_END \ - } - - -//============================================================================== -// -// Timer -// -//============================================================================== - - -typedef struct _NcvTimer *NcvTimer; - -NCV_EXPORTS NcvTimer ncvStartTimer(void); - -NCV_EXPORTS double ncvEndQueryTimerUs(NcvTimer t); - -NCV_EXPORTS double ncvEndQueryTimerMs(NcvTimer t); - - -//============================================================================== -// -// Memory management classes template compound types -// -//============================================================================== - - -/** -* Calculates the aligned top bound value -*/ -NCV_EXPORTS Ncv32u alignUp(Ncv32u what, Ncv32u alignment); - - -/** -* NCVMemoryType -*/ -enum NCVMemoryType -{ - NCVMemoryTypeNone, - NCVMemoryTypeHostPageable, - NCVMemoryTypeHostPinned, - NCVMemoryTypeDevice -}; - - -/** -* NCVMemPtr -*/ -struct NCV_EXPORTS NCVMemPtr -{ - void *ptr; - NCVMemoryType memtype; - void clear(); -}; - - -/** -* NCVMemSegment -*/ -struct NCV_EXPORTS NCVMemSegment -{ - NCVMemPtr begin; - size_t size; - void clear(); -}; - - -/** -* INCVMemAllocator (Interface) -*/ -class NCV_EXPORTS INCVMemAllocator -{ -public: - virtual ~INCVMemAllocator() = 0; - - virtual NCVStatus alloc(NCVMemSegment &seg, size_t size) = 0; - virtual NCVStatus dealloc(NCVMemSegment &seg) = 0; - - virtual NcvBool isInitialized(void) const = 0; - virtual NcvBool isCounting(void) const = 0; - - virtual NCVMemoryType memType(void) const = 0; - virtual Ncv32u alignment(void) const = 0; - virtual size_t maxSize(void) const = 0; -}; - -inline INCVMemAllocator::~INCVMemAllocator() {} - - -/** -* NCVMemStackAllocator -*/ -class NCV_EXPORTS NCVMemStackAllocator : public INCVMemAllocator -{ - NCVMemStackAllocator(); - NCVMemStackAllocator(const NCVMemStackAllocator &); - -public: - - explicit NCVMemStackAllocator(Ncv32u alignment); - NCVMemStackAllocator(NCVMemoryType memT, size_t capacity, Ncv32u alignment, void *reusePtr=NULL); - virtual ~NCVMemStackAllocator(); - - virtual NCVStatus alloc(NCVMemSegment &seg, size_t size); - virtual NCVStatus dealloc(NCVMemSegment &seg); - - virtual NcvBool isInitialized(void) const; - virtual NcvBool isCounting(void) const; - - virtual NCVMemoryType memType(void) const; - virtual Ncv32u alignment(void) const; - virtual size_t maxSize(void) const; - -private: - - NCVMemoryType _memType; - Ncv32u _alignment; - Ncv8u *allocBegin; - Ncv8u *begin; - Ncv8u *end; - size_t currentSize; - size_t _maxSize; - NcvBool bReusesMemory; -}; - - -/** -* NCVMemNativeAllocator -*/ -class NCV_EXPORTS NCVMemNativeAllocator : public INCVMemAllocator -{ -public: - - NCVMemNativeAllocator(NCVMemoryType memT, Ncv32u alignment); - virtual ~NCVMemNativeAllocator(); - - virtual NCVStatus alloc(NCVMemSegment &seg, size_t size); - virtual NCVStatus dealloc(NCVMemSegment &seg); - - virtual NcvBool isInitialized(void) const; - virtual NcvBool isCounting(void) const; - - virtual NCVMemoryType memType(void) const; - virtual Ncv32u alignment(void) const; - virtual size_t maxSize(void) const; - -private: - - NCVMemNativeAllocator(); - NCVMemNativeAllocator(const NCVMemNativeAllocator &); - - NCVMemoryType _memType; - Ncv32u _alignment; - size_t currentSize; - size_t _maxSize; -}; - - -/** -* Copy dispatchers -*/ -NCV_EXPORTS NCVStatus memSegCopyHelper(void *dst, NCVMemoryType dstType, - const void *src, NCVMemoryType srcType, - size_t sz, cudaStream_t cuStream); - - -NCV_EXPORTS NCVStatus memSegCopyHelper2D(void *dst, Ncv32u dstPitch, NCVMemoryType dstType, - const void *src, Ncv32u srcPitch, NCVMemoryType srcType, - Ncv32u widthbytes, Ncv32u height, cudaStream_t cuStream); - - -/** -* NCVVector (1D) -*/ -template -class NCVVector -{ - NCVVector(const NCVVector &); - -public: - - NCVVector() - { - clear(); - } - - virtual ~NCVVector() {} - - void clear() - { - _ptr = NULL; - _length = 0; - _memtype = NCVMemoryTypeNone; - } - - NCVStatus copySolid(NCVVector &dst, cudaStream_t cuStream, size_t howMuch=0) const - { - if (howMuch == 0) - { - ncvAssertReturn(dst._length == this->_length, NCV_MEM_COPY_ERROR); - howMuch = this->_length * sizeof(T); - } - else - { - ncvAssertReturn(dst._length * sizeof(T) >= howMuch && - this->_length * sizeof(T) >= howMuch && - howMuch > 0, NCV_MEM_COPY_ERROR); - } - ncvAssertReturn((this->_ptr != NULL || this->_memtype == NCVMemoryTypeNone) && - (dst._ptr != NULL || dst._memtype == NCVMemoryTypeNone), NCV_NULL_PTR); - - NCVStatus ncvStat = NCV_SUCCESS; - if (this->_memtype != NCVMemoryTypeNone) - { - ncvStat = memSegCopyHelper(dst._ptr, dst._memtype, - this->_ptr, this->_memtype, - howMuch, cuStream); - } - - return ncvStat; - } - - T *ptr() const {return this->_ptr;} - size_t length() const {return this->_length;} - NCVMemoryType memType() const {return this->_memtype;} - -protected: - - T *_ptr; - size_t _length; - NCVMemoryType _memtype; -}; - - -/** -* NCVVectorAlloc -*/ -template -class NCVVectorAlloc : public NCVVector -{ - NCVVectorAlloc(); - NCVVectorAlloc(const NCVVectorAlloc &); - NCVVectorAlloc& operator=(const NCVVectorAlloc&); - -public: - - NCVVectorAlloc(INCVMemAllocator &allocator, Ncv32u length) - : - allocator(allocator) - { - NCVStatus ncvStat; - - this->clear(); - this->allocatedMem.clear(); - - ncvStat = allocator.alloc(this->allocatedMem, length * sizeof(T)); - ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "NCVVectorAlloc ctor:: alloc failed", ); - - this->_ptr = (T *)this->allocatedMem.begin.ptr; - this->_length = length; - this->_memtype = this->allocatedMem.begin.memtype; - } - - ~NCVVectorAlloc() - { - NCVStatus ncvStat; - - ncvStat = allocator.dealloc(this->allocatedMem); - ncvAssertPrintCheck(ncvStat == NCV_SUCCESS, "NCVVectorAlloc dtor:: dealloc failed"); - - this->clear(); - } - - NcvBool isMemAllocated() const - { - return (this->allocatedMem.begin.ptr != NULL) || (this->allocator.isCounting()); - } - - Ncv32u getAllocatorsAlignment() const - { - return allocator.alignment(); - } - - NCVMemSegment getSegment() const - { - return allocatedMem; - } - -private: - INCVMemAllocator &allocator; - NCVMemSegment allocatedMem; -}; - - -/** -* NCVVectorReuse -*/ -template -class NCVVectorReuse : public NCVVector -{ - NCVVectorReuse(); - NCVVectorReuse(const NCVVectorReuse &); - -public: - - explicit NCVVectorReuse(const NCVMemSegment &memSegment) - { - this->bReused = false; - this->clear(); - - this->_length = memSegment.size / sizeof(T); - this->_ptr = (T *)memSegment.begin.ptr; - this->_memtype = memSegment.begin.memtype; - - this->bReused = true; - } - - NCVVectorReuse(const NCVMemSegment &memSegment, Ncv32u length) - { - this->bReused = false; - this->clear(); - - ncvAssertPrintReturn(length * sizeof(T) <= memSegment.size, \ - "NCVVectorReuse ctor:: memory binding failed due to size mismatch", ); - - this->_length = length; - this->_ptr = (T *)memSegment.begin.ptr; - this->_memtype = memSegment.begin.memtype; - - this->bReused = true; - } - - NcvBool isMemReused() const - { - return this->bReused; - } - -private: - - NcvBool bReused; -}; - - -/** -* NCVMatrix (2D) -*/ -template -class NCVMatrix -{ - NCVMatrix(const NCVMatrix &); - -public: - - NCVMatrix() - { - clear(); - } - - virtual ~NCVMatrix() {} - - void clear() - { - _ptr = NULL; - _pitch = 0; - _width = 0; - _height = 0; - _memtype = NCVMemoryTypeNone; - } - - Ncv32u stride() const - { - return _pitch / sizeof(T); - } - - //a side effect of this function is that it copies everything in a single chunk, so the "padding" will be overwritten - NCVStatus copySolid(NCVMatrix &dst, cudaStream_t cuStream, size_t howMuch=0) const - { - if (howMuch == 0) - { - ncvAssertReturn(dst._pitch == this->_pitch && - dst._height == this->_height, NCV_MEM_COPY_ERROR); - howMuch = this->_pitch * this->_height; - } - else - { - ncvAssertReturn(dst._pitch * dst._height >= howMuch && - this->_pitch * this->_height >= howMuch && - howMuch > 0, NCV_MEM_COPY_ERROR); - } - ncvAssertReturn((this->_ptr != NULL || this->_memtype == NCVMemoryTypeNone) && - (dst._ptr != NULL || dst._memtype == NCVMemoryTypeNone), NCV_NULL_PTR); - - NCVStatus ncvStat = NCV_SUCCESS; - if (this->_memtype != NCVMemoryTypeNone) - { - ncvStat = memSegCopyHelper(dst._ptr, dst._memtype, - this->_ptr, this->_memtype, - howMuch, cuStream); - } - - return ncvStat; - } - - NCVStatus copy2D(NCVMatrix &dst, NcvSize32u roi, cudaStream_t cuStream) const - { - ncvAssertReturn(this->width() >= roi.width && this->height() >= roi.height && - dst.width() >= roi.width && dst.height() >= roi.height, NCV_MEM_COPY_ERROR); - ncvAssertReturn((this->_ptr != NULL || this->_memtype == NCVMemoryTypeNone) && - (dst._ptr != NULL || dst._memtype == NCVMemoryTypeNone), NCV_NULL_PTR); - - NCVStatus ncvStat = NCV_SUCCESS; - if (this->_memtype != NCVMemoryTypeNone) - { - ncvStat = memSegCopyHelper2D(dst._ptr, dst._pitch, dst._memtype, - this->_ptr, this->_pitch, this->_memtype, - roi.width * sizeof(T), roi.height, cuStream); - } - - return ncvStat; - } - - T &at(Ncv32u x, Ncv32u y) const - { - if (x >= this->_width || y >= this->_height) - { - printf("Error addressing matrix at [%d, %d]\n", x, y); - return *this->_ptr; - } - return ((T *)((Ncv8u *)this->_ptr + y * this->_pitch))[x]; - } - - T *ptr() const {return this->_ptr;} - Ncv32u width() const {return this->_width;} - Ncv32u height() const {return this->_height;} - NcvSize32u size() const {return NcvSize32u(this->_width, this->_height);} - Ncv32u pitch() const {return this->_pitch;} - NCVMemoryType memType() const {return this->_memtype;} - -protected: - - T *_ptr; - Ncv32u _width; - Ncv32u _height; - Ncv32u _pitch; - NCVMemoryType _memtype; -}; - - -/** -* NCVMatrixAlloc -*/ -template -class NCVMatrixAlloc : public NCVMatrix -{ - NCVMatrixAlloc(); - NCVMatrixAlloc(const NCVMatrixAlloc &); - NCVMatrixAlloc& operator=(const NCVMatrixAlloc &); -public: - - NCVMatrixAlloc(INCVMemAllocator &allocator, Ncv32u width, Ncv32u height, Ncv32u pitch=0) - : - allocator(allocator) - { - NCVStatus ncvStat; - - this->clear(); - this->allocatedMem.clear(); - - Ncv32u widthBytes = width * sizeof(T); - Ncv32u pitchBytes = alignUp(widthBytes, allocator.alignment()); - - if (pitch != 0) - { - ncvAssertPrintReturn(pitch >= pitchBytes && - (pitch & (allocator.alignment() - 1)) == 0, - "NCVMatrixAlloc ctor:: incorrect pitch passed", ); - pitchBytes = pitch; - } - - Ncv32u requiredAllocSize = pitchBytes * height; - - ncvStat = allocator.alloc(this->allocatedMem, requiredAllocSize); - ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "NCVMatrixAlloc ctor:: alloc failed", ); - - this->_ptr = (T *)this->allocatedMem.begin.ptr; - this->_width = width; - this->_height = height; - this->_pitch = pitchBytes; - this->_memtype = this->allocatedMem.begin.memtype; - } - - ~NCVMatrixAlloc() - { - NCVStatus ncvStat; - - ncvStat = allocator.dealloc(this->allocatedMem); - ncvAssertPrintCheck(ncvStat == NCV_SUCCESS, "NCVMatrixAlloc dtor:: dealloc failed"); - - this->clear(); - } - - NcvBool isMemAllocated() const - { - return (this->allocatedMem.begin.ptr != NULL) || (this->allocator.isCounting()); - } - - Ncv32u getAllocatorsAlignment() const - { - return allocator.alignment(); - } - - NCVMemSegment getSegment() const - { - return allocatedMem; - } - -private: - - INCVMemAllocator &allocator; - NCVMemSegment allocatedMem; -}; - - -/** -* NCVMatrixReuse -*/ -template -class NCVMatrixReuse : public NCVMatrix -{ - NCVMatrixReuse(); - NCVMatrixReuse(const NCVMatrixReuse &); - -public: - - NCVMatrixReuse(const NCVMemSegment &memSegment, Ncv32u alignment, Ncv32u width, Ncv32u height, Ncv32u pitch=0, NcvBool bSkipPitchCheck=false) - { - this->bReused = false; - this->clear(); - - Ncv32u widthBytes = width * sizeof(T); - Ncv32u pitchBytes = alignUp(widthBytes, alignment); - - if (pitch != 0) - { - if (!bSkipPitchCheck) - { - ncvAssertPrintReturn(pitch >= pitchBytes && - (pitch & (alignment - 1)) == 0, - "NCVMatrixReuse ctor:: incorrect pitch passed", ); - } - else - { - ncvAssertPrintReturn(pitch >= widthBytes, "NCVMatrixReuse ctor:: incorrect pitch passed", ); - } - pitchBytes = pitch; - } - - ncvAssertPrintReturn(pitchBytes * height <= memSegment.size, \ - "NCVMatrixReuse ctor:: memory binding failed due to size mismatch", ); - - this->_width = width; - this->_height = height; - this->_pitch = pitchBytes; - this->_ptr = (T *)memSegment.begin.ptr; - this->_memtype = memSegment.begin.memtype; - - this->bReused = true; - } - - NCVMatrixReuse(const NCVMatrix &mat, NcvRect32u roi) - { - this->bReused = false; - this->clear(); - - ncvAssertPrintReturn(roi.x < mat.width() && roi.y < mat.height() && \ - roi.x + roi.width <= mat.width() && roi.y + roi.height <= mat.height(), - "NCVMatrixReuse ctor:: memory binding failed due to mismatching ROI and source matrix dims", ); - - this->_width = roi.width; - this->_height = roi.height; - this->_pitch = mat.pitch(); - this->_ptr = &mat.at(roi.x, roi.y); - this->_memtype = mat.memType(); - - this->bReused = true; - } - - NcvBool isMemReused() const - { - return this->bReused; - } - -private: - - NcvBool bReused; -}; - - -/** -* Operations with rectangles -*/ -NCV_EXPORTS NCVStatus ncvGroupRectangles_host(NCVVector &hypotheses, Ncv32u &numHypotheses, - Ncv32u minNeighbors, Ncv32f intersectEps, NCVVector *hypothesesWeights); - - -NCV_EXPORTS NCVStatus ncvDrawRects_8u_host(Ncv8u *h_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, - NcvRect32u *h_rects, Ncv32u numRects, Ncv8u color); - - -NCV_EXPORTS NCVStatus ncvDrawRects_32u_host(Ncv32u *h_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, - NcvRect32u *h_rects, Ncv32u numRects, Ncv32u color); - - -NCV_EXPORTS NCVStatus ncvDrawRects_8u_device(Ncv8u *d_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, - NcvRect32u *d_rects, Ncv32u numRects, Ncv8u color, cudaStream_t cuStream); - - -NCV_EXPORTS NCVStatus ncvDrawRects_32u_device(Ncv32u *d_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, - NcvRect32u *d_rects, Ncv32u numRects, Ncv32u color, cudaStream_t cuStream); - - -#define CLAMP(x,a,b) ( (x) > (b) ? (b) : ( (x) < (a) ? (a) : (x) ) ) -#define CLAMP_TOP(x, a) (((x) > (a)) ? (a) : (x)) -#define CLAMP_BOTTOM(x, a) (((x) < (a)) ? (a) : (x)) -#define CLAMP_0_255(x) CLAMP(x,0,255) - - -#define SUB_BEGIN(type, name) struct { __inline type name -#define SUB_END(name) } name; -#define SUB_CALL(name) name.name - -#define SQR(x) ((x)*(x)) - - -#define ncvSafeMatAlloc(name, type, alloc, width, height, err) \ - NCVMatrixAlloc name(alloc, width, height); \ - ncvAssertReturn(name.isMemAllocated(), err); - - - -#endif // _ncv_hpp_ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NPP_staging.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NPP_staging.hpp deleted file mode 100755 index e7a65e5..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/NPP_staging.hpp +++ /dev/null @@ -1,906 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2009-2010, NVIDIA 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 the copyright holders 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 _npp_staging_hpp_ -#define _npp_staging_hpp_ - -#include "NCV.hpp" - - -/** -* \file NPP_staging.hpp -* NPP Staging Library -*/ - - -/** \defgroup core_npp NPPST Core - * Basic functions for CUDA streams management. - * @{ - */ - - -/** - * Gets an active CUDA stream used by NPPST - * NOT THREAD SAFE - * \return Current CUDA stream - */ -NCV_EXPORTS -cudaStream_t nppStGetActiveCUDAstream(); - - -/** - * Sets an active CUDA stream used by NPPST - * NOT THREAD SAFE - * \param cudaStream [IN] cudaStream CUDA stream to become current - * \return CUDA stream used before - */ -NCV_EXPORTS -cudaStream_t nppStSetActiveCUDAstream(cudaStream_t cudaStream); - - -/*@}*/ - - -/** \defgroup nppi NPPST Image Processing -* @{ -*/ - - -/** Border type - * - * Filtering operations assume that each pixel has a neighborhood of pixels. - * The following structure describes possible ways to define non-existent pixels. - */ -enum NppStBorderType -{ - nppStBorderNone = 0, ///< There is no need to define additional pixels, image is extended already - nppStBorderClamp = 1, ///< Clamp out of range position to borders - nppStBorderWrap = 2, ///< Wrap out of range position. Image becomes periodic. - nppStBorderMirror = 3 ///< reflect out of range position across borders -}; - - -/** - * Filter types for image resizing - */ -enum NppStInterpMode -{ - nppStSupersample, ///< Supersampling. For downscaling only - nppStBicubic ///< Bicubic convolution filter, a = -0.5 (cubic Hermite spline) -}; - - -/** Frame interpolation state - * - * This structure holds parameters required for frame interpolation. - * Forward displacement field is a per-pixel mapping from frame 0 to frame 1. - * Backward displacement field is a per-pixel mapping from frame 1 to frame 0. - */ - - struct NppStInterpolationState -{ - NcvSize32u size; ///< frame size - Ncv32u nStep; ///< pitch - Ncv32f pos; ///< new frame position - Ncv32f *pSrcFrame0; ///< frame 0 - Ncv32f *pSrcFrame1; ///< frame 1 - Ncv32f *pFU; ///< forward horizontal displacement - Ncv32f *pFV; ///< forward vertical displacement - Ncv32f *pBU; ///< backward horizontal displacement - Ncv32f *pBV; ///< backward vertical displacement - Ncv32f *pNewFrame; ///< new frame - Ncv32f *ppBuffers[6]; ///< temporary buffers -}; - - -/** Size of a buffer required for interpolation. - * - * Requires several such buffers. See \see NppStInterpolationState. - * - * \param srcSize [IN] Frame size (both frames must be of the same size) - * \param nStep [IN] Frame line step - * \param hpSize [OUT] Where to store computed size (host memory) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStGetInterpolationBufferSize(NcvSize32u srcSize, - Ncv32u nStep, - Ncv32u *hpSize); - - -/** Interpolate frames (images) using provided optical flow (displacement field). - * 32-bit floating point images, single channel - * - * \param pState [IN] structure containing all required parameters (host memory) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStInterpolateFrames(const NppStInterpolationState *pState); - - -/** Row linear filter. 32-bit floating point image, single channel - * - * Apply horizontal linear filter - * - * \param pSrc [IN] Source image pointer (CUDA device memory) - * \param srcSize [IN] Source image size - * \param nSrcStep [IN] Source image line step - * \param pDst [OUT] Destination image pointer (CUDA device memory) - * \param dstSize [OUT] Destination image size - * \param oROI [IN] Region of interest in the source image - * \param borderType [IN] Type of border - * \param pKernel [IN] Pointer to row kernel values (CUDA device memory) - * \param nKernelSize [IN] Size of the kernel in pixels - * \param nAnchor [IN] The kernel row alignment with respect to the position of the input pixel - * \param multiplier [IN] Value by which the computed result is multiplied - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStFilterRowBorder_32f_C1R(const Ncv32f *pSrc, - NcvSize32u srcSize, - Ncv32u nSrcStep, - Ncv32f *pDst, - NcvSize32u dstSize, - Ncv32u nDstStep, - NcvRect32u oROI, - NppStBorderType borderType, - const Ncv32f *pKernel, - Ncv32s nKernelSize, - Ncv32s nAnchor, - Ncv32f multiplier); - - -/** Column linear filter. 32-bit floating point image, single channel - * - * Apply vertical linear filter - * - * \param pSrc [IN] Source image pointer (CUDA device memory) - * \param srcSize [IN] Source image size - * \param nSrcStep [IN] Source image line step - * \param pDst [OUT] Destination image pointer (CUDA device memory) - * \param dstSize [OUT] Destination image size - * \param oROI [IN] Region of interest in the source image - * \param borderType [IN] Type of border - * \param pKernel [IN] Pointer to column kernel values (CUDA device memory) - * \param nKernelSize [IN] Size of the kernel in pixels - * \param nAnchor [IN] The kernel column alignment with respect to the position of the input pixel - * \param multiplier [IN] Value by which the computed result is multiplied - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStFilterColumnBorder_32f_C1R(const Ncv32f *pSrc, - NcvSize32u srcSize, - Ncv32u nSrcStep, - Ncv32f *pDst, - NcvSize32u dstSize, - Ncv32u nDstStep, - NcvRect32u oROI, - NppStBorderType borderType, - const Ncv32f *pKernel, - Ncv32s nKernelSize, - Ncv32s nAnchor, - Ncv32f multiplier); - - -/** Size of buffer required for vector image warping. - * - * \param srcSize [IN] Source image size - * \param nStep [IN] Source image line step - * \param hpSize [OUT] Where to store computed size (host memory) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStVectorWarpGetBufferSize(NcvSize32u srcSize, - Ncv32u nSrcStep, - Ncv32u *hpSize); - - -/** Warp image using provided 2D vector field and 1x1 point spread function. - * 32-bit floating point image, single channel - * - * During warping pixels from the source image may fall between pixels of the destination image. - * PSF (point spread function) describes how the source image pixel affects pixels of the destination. - * For 1x1 PSF only single pixel with the largest intersection is affected (similar to nearest interpolation). - * - * Destination image size and line step must be the same as the source image size and line step - * - * \param pSrc [IN] Source image pointer (CUDA device memory) - * \param srcSize [IN] Source image size - * \param nSrcStep [IN] Source image line step - * \param pU [IN] Pointer to horizontal displacement field (CUDA device memory) - * \param pV [IN] Pointer to vertical displacement field (CUDA device memory) - * \param nVFStep [IN] Displacement field line step - * \param timeScale [IN] Value by which displacement field will be scaled for warping - * \param pDst [OUT] Destination image pointer (CUDA device memory) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStVectorWarp_PSF1x1_32f_C1(const Ncv32f *pSrc, - NcvSize32u srcSize, - Ncv32u nSrcStep, - const Ncv32f *pU, - const Ncv32f *pV, - Ncv32u nVFStep, - Ncv32f timeScale, - Ncv32f *pDst); - - -/** Warp image using provided 2D vector field and 2x2 point spread function. - * 32-bit floating point image, single channel - * - * During warping pixels from the source image may fall between pixels of the destination image. - * PSF (point spread function) describes how the source image pixel affects pixels of the destination. - * For 2x2 PSF all four intersected pixels will be affected. - * - * Destination image size and line step must be the same as the source image size and line step - * - * \param pSrc [IN] Source image pointer (CUDA device memory) - * \param srcSize [IN] Source image size - * \param nSrcStep [IN] Source image line step - * \param pU [IN] Pointer to horizontal displacement field (CUDA device memory) - * \param pV [IN] Pointer to vertical displacement field (CUDA device memory) - * \param nVFStep [IN] Displacement field line step - * \param timeScale [IN] Value by which displacement field will be scaled for warping - * \param pDst [OUT] Destination image pointer (CUDA device memory) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStVectorWarp_PSF2x2_32f_C1(const Ncv32f *pSrc, - NcvSize32u srcSize, - Ncv32u nSrcStep, - const Ncv32f *pU, - const Ncv32f *pV, - Ncv32u nVFStep, - Ncv32f *pBuffer, - Ncv32f timeScale, - Ncv32f *pDst); - - -/** Resize. 32-bit floating point image, single channel - * - * Resizes image using specified filter (interpolation type) - * - * \param pSrc [IN] Source image pointer (CUDA device memory) - * \param srcSize [IN] Source image size - * \param nSrcStep [IN] Source image line step - * \param srcROI [IN] Source image region of interest - * \param pDst [OUT] Destination image pointer (CUDA device memory) - * \param dstSize [IN] Destination image size - * \param nDstStep [IN] Destination image line step - * \param dstROI [IN] Destination image region of interest - * \param xFactor [IN] Row scale factor - * \param yFactor [IN] Column scale factor - * \param interpolation [IN] Interpolation type - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStResize_32f_C1R(const Ncv32f *pSrc, - NcvSize32u srcSize, - Ncv32u nSrcStep, - NcvRect32u srcROI, - Ncv32f *pDst, - NcvSize32u dstSize, - Ncv32u nDstStep, - NcvRect32u dstROI, - Ncv32f xFactor, - Ncv32f yFactor, - NppStInterpMode interpolation); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit unsigned pixels, single channel. - * - * \param d_src [IN] Source image pointer (CUDA device memory) - * \param srcStep [IN] Source image line step - * \param d_dst [OUT] Destination image pointer (CUDA device memory) - * \param dstStep [IN] Destination image line step - * \param srcRoi [IN] Region of interest in the source image - * \param scale [IN] Downsampling scale factor (positive integer) - * \param readThruTexture [IN] Performance hint to cache source in texture (true) or read directly (false) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32u_C1R(Ncv32u *d_src, Ncv32u srcStep, - Ncv32u *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit signed pixels, single channel. - * \see nppiStDecimate_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32s_C1R(Ncv32s *d_src, Ncv32u srcStep, - Ncv32s *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit float pixels, single channel. - * \see nppiStDecimate_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32f_C1R(Ncv32f *d_src, Ncv32u srcStep, - Ncv32f *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** -* Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit unsigned pixels, single channel. -* \see nppiStDecimate_32u_C1R -*/ -NCV_EXPORTS -NCVStatus nppiStDecimate_64u_C1R(Ncv64u *d_src, Ncv32u srcStep, - Ncv64u *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit signed pixels, single channel. - * \see nppiStDecimate_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_64s_C1R(Ncv64s *d_src, Ncv32u srcStep, - Ncv64s *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit float pixels, single channel. - * \see nppiStDecimate_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_64f_C1R(Ncv64f *d_src, Ncv32u srcStep, - Ncv64f *d_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale, - NcvBool readThruTexture); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit unsigned pixels, single channel. Host implementation. - * - * \param h_src [IN] Source image pointer (Host or pinned memory) - * \param srcStep [IN] Source image line step - * \param h_dst [OUT] Destination image pointer (Host or pinned memory) - * \param dstStep [IN] Destination image line step - * \param srcRoi [IN] Region of interest in the source image - * \param scale [IN] Downsampling scale factor (positive integer) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32u_C1R_host(Ncv32u *h_src, Ncv32u srcStep, - Ncv32u *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit signed pixels, single channel. Host implementation. - * \see nppiStDecimate_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32s_C1R_host(Ncv32s *h_src, Ncv32u srcStep, - Ncv32s *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 32-bit float pixels, single channel. Host implementation. - * \see nppiStDecimate_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_32f_C1R_host(Ncv32f *h_src, Ncv32u srcStep, - Ncv32f *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit unsigned pixels, single channel. Host implementation. - * \see nppiStDecimate_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_64u_C1R_host(Ncv64u *h_src, Ncv32u srcStep, - Ncv64u *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit signed pixels, single channel. Host implementation. - * \see nppiStDecimate_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_64s_C1R_host(Ncv64s *h_src, Ncv32u srcStep, - Ncv64s *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Downsamples (decimates) an image using the nearest neighbor algorithm. 64-bit float pixels, single channel. Host implementation. - * \see nppiStDecimate_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStDecimate_64f_C1R_host(Ncv64f *h_src, Ncv32u srcStep, - Ncv64f *h_dst, Ncv32u dstStep, - NcvSize32u srcRoi, Ncv32u scale); - - -/** - * Computes standard deviation for each rectangular region of the input image using integral images. - * - * \param d_sum [IN] Integral image pointer (CUDA device memory) - * \param sumStep [IN] Integral image line step - * \param d_sqsum [IN] Squared integral image pointer (CUDA device memory) - * \param sqsumStep [IN] Squared integral image line step - * \param d_norm [OUT] Stddev image pointer (CUDA device memory). Each pixel contains stddev of a rect with top-left corner at the original location in the image - * \param normStep [IN] Stddev image line step - * \param roi [IN] Region of interest in the source image - * \param rect [IN] Rectangular region to calculate stddev over - * \param scaleArea [IN] Multiplication factor to account decimated scale - * \param readThruTexture [IN] Performance hint to cache source in texture (true) or read directly (false) - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStRectStdDev_32f_C1R(Ncv32u *d_sum, Ncv32u sumStep, - Ncv64u *d_sqsum, Ncv32u sqsumStep, - Ncv32f *d_norm, Ncv32u normStep, - NcvSize32u roi, NcvRect32u rect, - Ncv32f scaleArea, NcvBool readThruTexture); - - -/** - * Computes standard deviation for each rectangular region of the input image using integral images. Host implementation - * - * \param h_sum [IN] Integral image pointer (Host or pinned memory) - * \param sumStep [IN] Integral image line step - * \param h_sqsum [IN] Squared integral image pointer (Host or pinned memory) - * \param sqsumStep [IN] Squared integral image line step - * \param h_norm [OUT] Stddev image pointer (Host or pinned memory). Each pixel contains stddev of a rect with top-left corner at the original location in the image - * \param normStep [IN] Stddev image line step - * \param roi [IN] Region of interest in the source image - * \param rect [IN] Rectangular region to calculate stddev over - * \param scaleArea [IN] Multiplication factor to account decimated scale - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStRectStdDev_32f_C1R_host(Ncv32u *h_sum, Ncv32u sumStep, - Ncv64u *h_sqsum, Ncv32u sqsumStep, - Ncv32f *h_norm, Ncv32u normStep, - NcvSize32u roi, NcvRect32u rect, - Ncv32f scaleArea); - - -/** - * Transposes an image. 32-bit unsigned pixels, single channel - * - * \param d_src [IN] Source image pointer (CUDA device memory) - * \param srcStride [IN] Source image line step - * \param d_dst [OUT] Destination image pointer (CUDA device memory) - * \param dstStride [IN] Destination image line step - * \param srcRoi [IN] Region of interest of the source image - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32u_C1R(Ncv32u *d_src, Ncv32u srcStride, - Ncv32u *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 32-bit signed pixels, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32s_C1R(Ncv32s *d_src, Ncv32u srcStride, - Ncv32s *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 32-bit float pixels, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32f_C1R(Ncv32f *d_src, Ncv32u srcStride, - Ncv32f *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit unsigned pixels, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64u_C1R(Ncv64u *d_src, Ncv32u srcStride, - Ncv64u *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit signed pixels, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64s_C1R(Ncv64s *d_src, Ncv32u srcStride, - Ncv64s *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit float pixels, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64f_C1R(Ncv64f *d_src, Ncv32u srcStride, - Ncv64f *d_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 128-bit pixels of any type, single channel - * \see nppiStTranspose_32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_128_C1R(void *d_src, Ncv32u srcStep, - void *d_dst, Ncv32u dstStep, NcvSize32u srcRoi); - - -/** - * Transposes an image. 32-bit unsigned pixels, single channel. Host implementation - * - * \param h_src [IN] Source image pointer (Host or pinned memory) - * \param srcStride [IN] Source image line step - * \param h_dst [OUT] Destination image pointer (Host or pinned memory) - * \param dstStride [IN] Destination image line step - * \param srcRoi [IN] Region of interest of the source image - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32u_C1R_host(Ncv32u *h_src, Ncv32u srcStride, - Ncv32u *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 32-bit signed pixels, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32s_C1R_host(Ncv32s *h_src, Ncv32u srcStride, - Ncv32s *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 32-bit float pixels, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_32f_C1R_host(Ncv32f *h_src, Ncv32u srcStride, - Ncv32f *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit unsigned pixels, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64u_C1R_host(Ncv64u *h_src, Ncv32u srcStride, - Ncv64u *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit signed pixels, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64s_C1R_host(Ncv64s *h_src, Ncv32u srcStride, - Ncv64s *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 64-bit float pixels, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_64f_C1R_host(Ncv64f *h_src, Ncv32u srcStride, - Ncv64f *h_dst, Ncv32u dstStride, NcvSize32u srcRoi); - - -/** - * Transposes an image. 128-bit pixels of any type, single channel. Host implementation - * \see nppiStTranspose_32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStTranspose_128_C1R_host(void *d_src, Ncv32u srcStep, - void *d_dst, Ncv32u dstStep, NcvSize32u srcRoi); - - -/** - * Calculates the size of the temporary buffer for integral image creation - * - * \param roiSize [IN] Size of the input image - * \param pBufsize [OUT] Pointer to host variable that returns the size of the temporary buffer (in bytes) - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStIntegralGetSize_8u32u(NcvSize32u roiSize, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Calculates the size of the temporary buffer for integral image creation - * \see nppiStIntegralGetSize_8u32u - */ -NCV_EXPORTS -NCVStatus nppiStIntegralGetSize_32f32f(NcvSize32u roiSize, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Creates an integral image representation for the input image - * - * \param d_src [IN] Source image pointer (CUDA device memory) - * \param srcStep [IN] Source image line step - * \param d_dst [OUT] Destination integral image pointer (CUDA device memory) - * \param dstStep [IN] Destination image line step - * \param roiSize [IN] Region of interest of the source image - * \param pBuffer [IN] Pointer to the pre-allocated temporary buffer (CUDA device memory) - * \param bufSize [IN] Size of the pBuffer in bytes - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStIntegral_8u32u_C1R(Ncv8u *d_src, Ncv32u srcStep, - Ncv32u *d_dst, Ncv32u dstStep, NcvSize32u roiSize, - Ncv8u *pBuffer, Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Creates an integral image representation for the input image - * \see nppiStIntegral_8u32u_C1R - */ -NCV_EXPORTS -NCVStatus nppiStIntegral_32f32f_C1R(Ncv32f *d_src, Ncv32u srcStep, - Ncv32f *d_dst, Ncv32u dstStep, NcvSize32u roiSize, - Ncv8u *pBuffer, Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Creates an integral image representation for the input image. Host implementation - * - * \param h_src [IN] Source image pointer (Host or pinned memory) - * \param srcStep [IN] Source image line step - * \param h_dst [OUT] Destination integral image pointer (Host or pinned memory) - * \param dstStep [IN] Destination image line step - * \param roiSize [IN] Region of interest of the source image - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStIntegral_8u32u_C1R_host(Ncv8u *h_src, Ncv32u srcStep, - Ncv32u *h_dst, Ncv32u dstStep, NcvSize32u roiSize); - - -/** - * Creates an integral image representation for the input image. Host implementation - * \see nppiStIntegral_8u32u_C1R_host - */ -NCV_EXPORTS -NCVStatus nppiStIntegral_32f32f_C1R_host(Ncv32f *h_src, Ncv32u srcStep, - Ncv32f *h_dst, Ncv32u dstStep, NcvSize32u roiSize); - - -/** - * Calculates the size of the temporary buffer for squared integral image creation - * - * \param roiSize [IN] Size of the input image - * \param pBufsize [OUT] Pointer to host variable that returns the size of the temporary buffer (in bytes) - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStSqrIntegralGetSize_8u64u(NcvSize32u roiSize, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Creates a squared integral image representation for the input image - * - * \param d_src [IN] Source image pointer (CUDA device memory) - * \param srcStep [IN] Source image line step - * \param d_dst [OUT] Destination squared integral image pointer (CUDA device memory) - * \param dstStep [IN] Destination image line step - * \param roiSize [IN] Region of interest of the source image - * \param pBuffer [IN] Pointer to the pre-allocated temporary buffer (CUDA device memory) - * \param bufSize [IN] Size of the pBuffer in bytes - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStSqrIntegral_8u64u_C1R(Ncv8u *d_src, Ncv32u srcStep, - Ncv64u *d_dst, Ncv32u dstStep, NcvSize32u roiSize, - Ncv8u *pBuffer, Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Creates a squared integral image representation for the input image. Host implementation - * - * \param h_src [IN] Source image pointer (Host or pinned memory) - * \param srcStep [IN] Source image line step - * \param h_dst [OUT] Destination squared integral image pointer (Host or pinned memory) - * \param dstStep [IN] Destination image line step - * \param roiSize [IN] Region of interest of the source image - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppiStSqrIntegral_8u64u_C1R_host(Ncv8u *h_src, Ncv32u srcStep, - Ncv64u *h_dst, Ncv32u dstStep, NcvSize32u roiSize); - - -/*@}*/ - - -/** \defgroup npps NPPST Signal Processing -* @{ -*/ - - -/** - * Calculates the size of the temporary buffer for vector compaction. 32-bit unsigned values - * - * \param srcLen [IN] Length of the input vector in elements - * \param pBufsize [OUT] Pointer to host variable that returns the size of the temporary buffer (in bytes) - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppsStCompactGetSize_32u(Ncv32u srcLen, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Calculates the size of the temporary buffer for vector compaction. 32-bit signed values - * \see nppsStCompactGetSize_32u - */ -NCVStatus nppsStCompactGetSize_32s(Ncv32u srcLen, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Calculates the size of the temporary buffer for vector compaction. 32-bit float values - * \see nppsStCompactGetSize_32u - */ -NCVStatus nppsStCompactGetSize_32f(Ncv32u srcLen, Ncv32u *pBufsize, cudaDeviceProp &devProp); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit unsigned values - * - * \param d_src [IN] Source vector pointer (CUDA device memory) - * \param srcLen [IN] Source vector length - * \param d_dst [OUT] Destination vector pointer (CUDA device memory) - * \param p_dstLen [OUT] Pointer to the destination vector length (Pinned memory or NULL) - * \param elemRemove [IN] The value to be removed - * \param pBuffer [IN] Pointer to the pre-allocated temporary buffer (CUDA device memory) - * \param bufSize [IN] Size of the pBuffer in bytes - * \param devProp [IN] CUDA device properties structure, containing texture alignment information - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32u(Ncv32u *d_src, Ncv32u srcLen, - Ncv32u *d_dst, Ncv32u *p_dstLen, - Ncv32u elemRemove, Ncv8u *pBuffer, - Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit signed values - * \see nppsStCompact_32u - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32s(Ncv32s *d_src, Ncv32u srcLen, - Ncv32s *d_dst, Ncv32u *p_dstLen, - Ncv32s elemRemove, Ncv8u *pBuffer, - Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit float values - * \see nppsStCompact_32u - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32f(Ncv32f *d_src, Ncv32u srcLen, - Ncv32f *d_dst, Ncv32u *p_dstLen, - Ncv32f elemRemove, Ncv8u *pBuffer, - Ncv32u bufSize, cudaDeviceProp &devProp); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit unsigned values. Host implementation - * - * \param h_src [IN] Source vector pointer (CUDA device memory) - * \param srcLen [IN] Source vector length - * \param h_dst [OUT] Destination vector pointer (CUDA device memory) - * \param dstLen [OUT] Pointer to the destination vector length (can be NULL) - * \param elemRemove [IN] The value to be removed - * - * \return NCV status code - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32u_host(Ncv32u *h_src, Ncv32u srcLen, - Ncv32u *h_dst, Ncv32u *dstLen, Ncv32u elemRemove); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit signed values. Host implementation - * \see nppsStCompact_32u_host - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32s_host(Ncv32s *h_src, Ncv32u srcLen, - Ncv32s *h_dst, Ncv32u *dstLen, Ncv32s elemRemove); - - -/** - * Compacts the input vector by removing elements of specified value. 32-bit float values. Host implementation - * \see nppsStCompact_32u_host - */ -NCV_EXPORTS -NCVStatus nppsStCompact_32f_host(Ncv32f *h_src, Ncv32u srcLen, - Ncv32f *h_dst, Ncv32u *dstLen, Ncv32f elemRemove); - - -/*@}*/ - - -#endif // _npp_staging_hpp_ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpu.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpu.hpp deleted file mode 100755 index 38f6a95..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpu.hpp +++ /dev/null @@ -1,1562 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. -// -// * The name of the copyright holders 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 __OPENCV_GPU_HPP__ -#define __OPENCV_GPU_HPP__ - -#include -#include "opencv2/core/core.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/objdetect/objdetect.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/gpu/gpumat.hpp" - -namespace cv -{ - namespace gpu - { - //////////////////////////////// Initialization & Info //////////////////////// - - //! This is the only function that do not throw exceptions if the library is compiled without Cuda. - CV_EXPORTS int getCudaEnabledDeviceCount(); - - //! Functions below throw cv::Expception if the library is compiled without Cuda. - - CV_EXPORTS void setDevice(int device); - CV_EXPORTS int getDevice(); - - //! Explicitly destroys and cleans up all resources associated with the current device in the current process. - //! Any subsequent API call to this device will reinitialize the device. - CV_EXPORTS void resetDevice(); - - enum FeatureSet - { - FEATURE_SET_COMPUTE_10 = 10, - FEATURE_SET_COMPUTE_11 = 11, - FEATURE_SET_COMPUTE_12 = 12, - FEATURE_SET_COMPUTE_13 = 13, - FEATURE_SET_COMPUTE_20 = 20, - FEATURE_SET_COMPUTE_21 = 21, - GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, - SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, - NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13 - }; - - // Gives information about what GPU archs this OpenCV GPU module was - // compiled for - class CV_EXPORTS TargetArchs - { - public: - static bool builtWith(FeatureSet feature_set); - static bool has(int major, int minor); - static bool hasPtx(int major, int minor); - static bool hasBin(int major, int minor); - static bool hasEqualOrLessPtx(int major, int minor); - static bool hasEqualOrGreater(int major, int minor); - static bool hasEqualOrGreaterPtx(int major, int minor); - static bool hasEqualOrGreaterBin(int major, int minor); - private: - TargetArchs(); - }; - - // Gives information about the given GPU - class CV_EXPORTS DeviceInfo - { - public: - // Creates DeviceInfo object for the current GPU - DeviceInfo() : device_id_(getDevice()) { query(); } - - // Creates DeviceInfo object for the given GPU - DeviceInfo(int device_id) : device_id_(device_id) { query(); } - - string name() const { return name_; } - - // Return compute capability versions - int majorVersion() const { return majorVersion_; } - int minorVersion() const { return minorVersion_; } - - int multiProcessorCount() const { return multi_processor_count_; } - - size_t freeMemory() const; - size_t totalMemory() const; - - // Checks whether device supports the given feature - bool supports(FeatureSet feature_set) const; - - // Checks whether the GPU module can be run on the given device - bool isCompatible() const; - - int deviceID() const { return device_id_; } - - private: - void query(); - void queryMemory(size_t& free_memory, size_t& total_memory) const; - - int device_id_; - - string name_; - int multi_processor_count_; - int majorVersion_; - int minorVersion_; - }; - - //////////////////////////////// Error handling //////////////////////// - - CV_EXPORTS void error(const char *error_string, const char *file, const int line, const char *func); - - //////////////////////////////// CudaMem //////////////////////////////// - // CudaMem is limited cv::Mat with page locked memory allocation. - // Page locked memory is only needed for async and faster coping to GPU. - // It is convertable to cv::Mat header without reference counting - // so you can use it with other opencv functions. - - // Page-locks the matrix m memory and maps it for the device(s) - CV_EXPORTS void registerPageLocked(Mat& m); - // Unmaps the memory of matrix m, and makes it pageable again. - CV_EXPORTS void unregisterPageLocked(Mat& m); - - class CV_EXPORTS CudaMem - { - public: - enum { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2, ALLOC_WRITE_COMBINED = 4 }; - - CudaMem(); - CudaMem(const CudaMem& m); - - CudaMem(int rows, int cols, int type, int _alloc_type = ALLOC_PAGE_LOCKED); - CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED); - - - //! creates from cv::Mat with coping data - explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED); - - ~CudaMem(); - - CudaMem& operator = (const CudaMem& m); - - //! returns deep copy of the matrix, i.e. the data is copied - CudaMem clone() const; - - //! allocates new matrix data unless the matrix already has specified size and type. - void create(int rows, int cols, int type, int alloc_type = ALLOC_PAGE_LOCKED); - void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED); - - //! decrements reference counter and released memory if needed. - void release(); - - //! returns matrix header with disabled reference counting for CudaMem data. - Mat createMatHeader() const; - operator Mat() const; - - //! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware. - GpuMat createGpuMatHeader() const; - operator GpuMat() const; - - //returns if host memory can be mapperd to gpu address space; - static bool canMapHostMemory(); - - // Please see cv::Mat for descriptions - bool isContinuous() const; - size_t elemSize() const; - size_t elemSize1() const; - int type() const; - int depth() const; - int channels() const; - size_t step1() const; - Size size() const; - bool empty() const; - - - // Please see cv::Mat for descriptions - int flags; - int rows, cols; - size_t step; - - uchar* data; - int* refcount; - - uchar* datastart; - uchar* dataend; - - int alloc_type; - }; - - //////////////////////////////// CudaStream //////////////////////////////// - // Encapculates Cuda Stream. Provides interface for async coping. - // Passed to each function that supports async kernel execution. - // Reference counting is enabled - - class CV_EXPORTS Stream - { - public: - Stream(); - ~Stream(); - - Stream(const Stream&); - Stream& operator=(const Stream&); - - bool queryIfComplete(); - void waitForCompletion(); - - //! downloads asynchronously. - // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its subMat) - void enqueueDownload(const GpuMat& src, CudaMem& dst); - void enqueueDownload(const GpuMat& src, Mat& dst); - - //! uploads asynchronously. - // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its ROI) - void enqueueUpload(const CudaMem& src, GpuMat& dst); - void enqueueUpload(const Mat& src, GpuMat& dst); - - void enqueueCopy(const GpuMat& src, GpuMat& dst); - - void enqueueMemSet(GpuMat& src, Scalar val); - void enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask); - - // converts matrix type, ex from float to uchar depending on type - void enqueueConvert(const GpuMat& src, GpuMat& dst, int type, double a = 1, double b = 0); - - static Stream& Null(); - - operator bool() const; - - private: - void create(); - void release(); - - struct Impl; - Impl *impl; - - friend struct StreamAccessor; - - explicit Stream(Impl* impl); - }; - - - //////////////////////////////// Filter Engine //////////////////////////////// - - /*! - The Base Class for 1D or Row-wise Filters - - This is the base class for linear or non-linear filters that process 1D data. - In particular, such filters are used for the "horizontal" filtering parts in separable filters. - */ - class CV_EXPORTS BaseRowFilter_GPU - { - public: - BaseRowFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {} - virtual ~BaseRowFilter_GPU() {} - virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0; - int ksize, anchor; - }; - - /*! - The Base Class for Column-wise Filters - - This is the base class for linear or non-linear filters that process columns of 2D arrays. - Such filters are used for the "vertical" filtering parts in separable filters. - */ - class CV_EXPORTS BaseColumnFilter_GPU - { - public: - BaseColumnFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {} - virtual ~BaseColumnFilter_GPU() {} - virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0; - int ksize, anchor; - }; - - /*! - The Base Class for Non-Separable 2D Filters. - - This is the base class for linear or non-linear 2D filters. - */ - class CV_EXPORTS BaseFilter_GPU - { - public: - BaseFilter_GPU(const Size& ksize_, const Point& anchor_) : ksize(ksize_), anchor(anchor_) {} - virtual ~BaseFilter_GPU() {} - virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0; - Size ksize; - Point anchor; - }; - - /*! - The Base Class for Filter Engine. - - The class can be used to apply an arbitrary filtering operation to an image. - It contains all the necessary intermediate buffers. - */ - class CV_EXPORTS FilterEngine_GPU - { - public: - virtual ~FilterEngine_GPU() {} - - virtual void apply(const GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1), Stream& stream = Stream::Null()) = 0; - }; - - //! returns the non-separable filter engine with the specified filter - CV_EXPORTS Ptr createFilter2D_GPU(const Ptr& filter2D, int srcType, int dstType); - - //! returns the separable filter engine with the specified filters - CV_EXPORTS Ptr createSeparableFilter_GPU(const Ptr& rowFilter, - const Ptr& columnFilter, int srcType, int bufType, int dstType); - CV_EXPORTS Ptr createSeparableFilter_GPU(const Ptr& rowFilter, - const Ptr& columnFilter, int srcType, int bufType, int dstType, GpuMat& buf); - - //! returns horizontal 1D box filter - //! supports only CV_8UC1 source type and CV_32FC1 sum type - CV_EXPORTS Ptr getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1); - - //! returns vertical 1D box filter - //! supports only CV_8UC1 sum type and CV_32FC1 dst type - CV_EXPORTS Ptr getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1); - - //! returns 2D box filter - //! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type - CV_EXPORTS Ptr getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1)); - - //! returns box filter engine - CV_EXPORTS Ptr createBoxFilter_GPU(int srcType, int dstType, const Size& ksize, - const Point& anchor = Point(-1,-1)); - - //! returns 2D morphological filter - //! only MORPH_ERODE and MORPH_DILATE are supported - //! supports CV_8UC1 and CV_8UC4 types - //! kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height - CV_EXPORTS Ptr getMorphologyFilter_GPU(int op, int type, const Mat& kernel, const Size& ksize, - Point anchor=Point(-1,-1)); - - //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported. - CV_EXPORTS Ptr createMorphologyFilter_GPU(int op, int type, const Mat& kernel, - const Point& anchor = Point(-1,-1), int iterations = 1); - CV_EXPORTS Ptr createMorphologyFilter_GPU(int op, int type, const Mat& kernel, GpuMat& buf, - const Point& anchor = Point(-1,-1), int iterations = 1); - - //! returns 2D filter with the specified kernel - //! supports CV_8UC1 and CV_8UC4 types - CV_EXPORTS Ptr getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, const Size& ksize, - Point anchor = Point(-1, -1)); - - //! returns the non-separable linear filter engine - CV_EXPORTS Ptr createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, - const Point& anchor = Point(-1,-1)); - - //! returns the primitive row filter with the specified kernel. - //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type. - //! there are two version of algorithm: NPP and OpenCV. - //! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType, - //! otherwise calls OpenCV version. - //! NPP supports only BORDER_CONSTANT border type. - //! OpenCV version supports only CV_32F as buffer depth and - //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types. - CV_EXPORTS Ptr getLinearRowFilter_GPU(int srcType, int bufType, const Mat& rowKernel, - int anchor = -1, int borderType = BORDER_DEFAULT); - - //! returns the primitive column filter with the specified kernel. - //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type. - //! there are two version of algorithm: NPP and OpenCV. - //! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType, - //! otherwise calls OpenCV version. - //! NPP supports only BORDER_CONSTANT border type. - //! OpenCV version supports only CV_32F as buffer depth and - //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types. - CV_EXPORTS Ptr getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel, - int anchor = -1, int borderType = BORDER_DEFAULT); - - //! returns the separable linear filter engine - CV_EXPORTS Ptr createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel, - const Mat& columnKernel, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, - int columnBorderType = -1); - CV_EXPORTS Ptr createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel, - const Mat& columnKernel, GpuMat& buf, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, - int columnBorderType = -1); - - //! returns filter engine for the generalized Sobel operator - CV_EXPORTS Ptr createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS Ptr createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, GpuMat& buf, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - - //! returns the Gaussian filter engine - CV_EXPORTS Ptr createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS Ptr createGaussianFilter_GPU(int type, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - - //! returns maximum filter - CV_EXPORTS Ptr getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1)); - - //! returns minimum filter - CV_EXPORTS Ptr getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1)); - - //! smooths the image using the normalized box filter - //! supports CV_8UC1, CV_8UC4 types - CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null()); - - //! a synonym for normalized box filter - static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null()) { boxFilter(src, dst, -1, ksize, anchor, stream); } - - //! erodes the image (applies the local minimum operator) - CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); - CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null()); - - //! dilates the image (applies the local maximum operator) - CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); - CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null()); - - //! applies an advanced morphological operation to the image - CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1); - CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, GpuMat& buf1, GpuMat& buf2, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null()); - - //! applies non-separable 2D linear filter to the image - CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1), Stream& stream = Stream::Null()); - - //! applies separable 2D linear filter to the image - CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, - Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, GpuMat& buf, - Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null()); - - //! applies generalized Sobel operator to the image - CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, int ksize = 3, double scale = 1, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null()); - - //! applies the vertical or horizontal Scharr operator to the image - CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, double scale = 1, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null()); - - //! smooths the image using Gaussian filter. - CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1); - CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0, - int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null()); - - //! applies Laplacian operator to the image - //! supports only ksize = 1 and ksize = 3 - CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1, Stream& stream = Stream::Null()); - - - ////////////////////////////// Arithmetics /////////////////////////////////// - - //! implements generalized matrix product algorithm GEMM from BLAS - CV_EXPORTS void gemm(const GpuMat& src1, const GpuMat& src2, double alpha, - const GpuMat& src3, double beta, GpuMat& dst, int flags = 0, Stream& stream = Stream::Null()); - - //! transposes the matrix - //! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc) - CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst, Stream& stream = Stream::Null()); - - //! reverses the order of the rows, columns or both in a matrix - //! supports CV_8UC1, CV_8UC4 types - CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode, Stream& stream = Stream::Null()); - - //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i)) - //! destination array will have the depth type as lut and the same channels number as source - //! supports CV_8UC1, CV_8UC3 types - CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst, Stream& stream = Stream::Null()); - - //! makes multi-channel array out of several single-channel arrays - CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, Stream& stream = Stream::Null()); - - //! makes multi-channel array out of several single-channel arrays - CV_EXPORTS void merge(const vector& src, GpuMat& dst, Stream& stream = Stream::Null()); - - //! copies each plane of a multi-channel array to a dedicated array - CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, Stream& stream = Stream::Null()); - - //! copies each plane of a multi-channel array to a dedicated array - CV_EXPORTS void split(const GpuMat& src, vector& dst, Stream& stream = Stream::Null()); - - //! computes magnitude of complex (x(i).re, x(i).im) vector - //! supports only CV_32FC2 type - CV_EXPORTS void magnitude(const GpuMat& x, GpuMat& magnitude, Stream& stream = Stream::Null()); - - //! computes squared magnitude of complex (x(i).re, x(i).im) vector - //! supports only CV_32FC2 type - CV_EXPORTS void magnitudeSqr(const GpuMat& x, GpuMat& magnitude, Stream& stream = Stream::Null()); - - //! computes magnitude of each (x(i), y(i)) vector - //! supports only floating-point source - CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null()); - - //! computes squared magnitude of each (x(i), y(i)) vector - //! supports only floating-point source - CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null()); - - //! computes angle (angle(i)) of each (x(i), y(i)) vector - //! supports only floating-point source - CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null()); - - //! converts Cartesian coordinates to polar - //! supports only floating-point source - CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null()); - - //! converts polar coordinates to Cartesian - //! supports only floating-point source - CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false, Stream& stream = Stream::Null()); - - - //////////////////////////// Per-element operations //////////////////////////////////// - - //! adds one matrix to another (c = a + b) - CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null()); - //! adds scalar to a matrix (c = a + s) - CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null()); - - //! subtracts one matrix from another (c = a - b) - CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null()); - //! subtracts scalar from a matrix (c = a - s) - CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null()); - - //! computes element-wise weighted product of the two arrays (c = scale * a * b) - CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null()); - //! weighted multiplies matrix to a scalar (c = scale * a * s) - CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null()); - - //! computes element-wise weighted quotient of the two arrays (c = a / b) - CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null()); - //! computes element-wise weighted quotient of matrix and scalar (c = a / s) - CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null()); - //! computes element-wise weighted reciprocal of an array (dst = scale/src2) - CV_EXPORTS void divide(double scale, const GpuMat& src2, GpuMat& dst, int dtype = -1, Stream& stream = Stream::Null()); - - //! computes the weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) - CV_EXPORTS void addWeighted(const GpuMat& src1, double alpha, const GpuMat& src2, double beta, double gamma, GpuMat& dst, - int dtype = -1, Stream& stream = Stream::Null()); - - //! adds scaled array to another one (dst = alpha*src1 + src2) - static inline void scaleAdd(const GpuMat& src1, double alpha, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null()) - { - addWeighted(src1, alpha, src2, 1.0, 0.0, dst, -1, stream); - } - - //! computes element-wise absolute difference of two arrays (c = abs(a - b)) - CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null()); - //! computes element-wise absolute difference of array and scalar (c = abs(a - s)) - CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c, Stream& stream = Stream::Null()); - - //! computes exponent of each matrix element (b = e**a) - //! supports only CV_32FC1 type - CV_EXPORTS void exp(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null()); - - //! computes power of each matrix element: - // (dst(i,j) = pow( src(i,j) , power), if src.type() is integer - // (dst(i,j) = pow(fabs(src(i,j)), power), otherwise - //! supports all, except depth == CV_64F - CV_EXPORTS void pow(const GpuMat& src, double power, GpuMat& dst, Stream& stream = Stream::Null()); - - //! computes natural logarithm of absolute value of each matrix element: b = log(abs(a)) - //! supports only CV_32FC1 type - CV_EXPORTS void log(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null()); - - //! compares elements of two arrays (c = a b) - //! supports CV_8UC4, CV_32FC1 types - CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop, Stream& stream = Stream::Null()); - - //! performs per-elements bit-wise inversion - CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null()); - - //! calculates per-element bit-wise disjunction of two arrays - CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null()); - - //! calculates per-element bit-wise conjunction of two arrays - CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null()); - - //! calculates per-element bit-wise "exclusive or" operation - CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null()); - - //! computes per-element minimum of two arrays (dst = min(src1, src2)) - CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null()); - - //! computes per-element minimum of array and scalar (dst = min(src1, src2)) - CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null()); - - //! computes per-element maximum of two arrays (dst = max(src1, src2)) - CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null()); - - //! computes per-element maximum of array and scalar (dst = max(src1, src2)) - CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null()); - - - ////////////////////////////// Image processing ////////////////////////////// - - //! DST[x,y] = SRC[xmap[x,y],ymap[x,y]] - //! supports only CV_32FC1 map type - CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap, - int interpolation, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar(), - Stream& stream = Stream::Null()); - - //! Does mean shift filtering on GPU. - CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr, - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1), Stream& stream = Stream::Null()); - - //! Does mean shift procedure on GPU. - CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr, - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1), Stream& stream = Stream::Null()); - - //! Does mean shift segmentation with elimination of small regions. - CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize, - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1)); - - //! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV. - //! Supported types of input disparity: CV_8U, CV_16S. - //! Output disparity has CV_8UC4 type in BGRA format (alpha = 255). - CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, Stream& stream = Stream::Null()); - - //! Reprojects disparity image to 3D space. - //! Supports CV_8U and CV_16S types of input disparity. - //! The output is a 4-channel floating-point (CV_32FC4) matrix. - //! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map. - //! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify. - CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, Stream& stream = Stream::Null()); - - //! converts image from one color space to another - CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0, Stream& stream = Stream::Null()); - - //! applies fixed threshold to the image - CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, Stream& stream = Stream::Null()); - - //! resizes the image - //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC - CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null()); - - //! warps the image using affine transformation - //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC - CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null()); - - //! warps the image using perspective transformation - //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC - CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null()); - - //! builds plane warping maps - CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, const Mat &T, float scale, - GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null()); - - //! builds cylindrical warping maps - CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale, - GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null()); - - //! builds spherical warping maps - CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale, - GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null()); - - //! rotate 8bit single or four channel image - //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC - //! supports CV_8UC1, CV_8UC4 types - CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0, - int interpolation = INTER_LINEAR, Stream& stream = Stream::Null()); - - //! copies 2D array to a larger destination array and pads borders with user-specifiable constant - CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, int borderType, - const Scalar& value = Scalar(), Stream& stream = Stream::Null()); - - //! computes the integral image - //! sum will have CV_32S type, but will contain unsigned int values - //! supports only CV_8UC1 source type - CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, Stream& stream = Stream::Null()); - - //! buffered version - CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer, Stream& stream = Stream::Null()); - - //! computes the integral image and integral for the squared image - //! sum will have CV_32S type, sqsum - CV32F type - //! supports only CV_8UC1 source type - CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, GpuMat& sqsum, Stream& stream = Stream::Null()); - - //! computes squared integral image - //! result matrix will have 64F type, but will contain 64U values - //! supports source images of 8UC1 type only - CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum, Stream& stream = Stream::Null()); - - //! computes vertical sum, supports only CV_32FC1 images - CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum); - - //! computes the standard deviation of integral images - //! supports only CV_32SC1 source type and CV_32FC1 sqr type - //! output will have CV_32FC1 type - CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect, Stream& stream = Stream::Null()); - - //! computes Harris cornerness criteria at each image pixel - CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, - int borderType = BORDER_REFLECT101); - CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, double k, - int borderType = BORDER_REFLECT101); - CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize, double k, - int borderType = BORDER_REFLECT101, Stream& stream = Stream::Null()); - - //! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria - CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101); - CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, int borderType=BORDER_REFLECT101); - CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize, - int borderType=BORDER_REFLECT101, Stream& stream = Stream::Null()); - - //! performs per-element multiplication of two full (not packed) Fourier spectrums - //! supports 32FC2 matrixes only (interleaved format) - CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false, Stream& stream = Stream::Null()); - - //! performs per-element multiplication of two full (not packed) Fourier spectrums - //! supports 32FC2 matrixes only (interleaved format) - CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false, Stream& stream = Stream::Null()); - - //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix. - //! Param dft_size is the size of DFT transform. - //! - //! If the source matrix is not continous, then additional copy will be done, - //! so to avoid copying ensure the source matrix is continous one. If you want to use - //! preallocated output ensure it is continuous too, otherwise it will be reallocated. - //! - //! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values - //! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved. - //! - //! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format. - CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0, Stream& stream = Stream::Null()); - - //! computes convolution (or cross-correlation) of two images using discrete Fourier transform - //! supports source images of 32FC1 type only - //! result matrix will have 32FC1 type - struct CV_EXPORTS ConvolveBuf; - CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr = false); - CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream& stream = Stream::Null()); - - struct CV_EXPORTS ConvolveBuf - { - ConvolveBuf() {} - ConvolveBuf(Size image_size, Size templ_size) - { create(image_size, templ_size); } - void create(Size image_size, Size templ_size); - void create(Size image_size, Size templ_size, Size block_size); - - private: - static Size estimateBlockSize(Size result_size, Size templ_size); - friend void convolve(const GpuMat&, const GpuMat&, GpuMat&, bool, ConvolveBuf&, Stream& stream); - - Size result_size; - Size block_size; - Size dft_size; - int spect_len; - - GpuMat image_spect, templ_spect, result_spect; - GpuMat image_block, templ_block, result_data; - }; - - //! computes the proximity map for the raster template and the image where the template is searched for - CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, Stream& stream = Stream::Null()); - - //! smoothes the source image and downsamples it - CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null()); - - //! upsamples the source image and then smoothes it - CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null()); - - //! performs linear blending of two images - //! to avoid accuracy errors sum of weigths shouldn't be very close to zero - CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2, - GpuMat& result, Stream& stream = Stream::Null()); - - - struct CV_EXPORTS CannyBuf; - - CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false); - CV_EXPORTS void Canny(const GpuMat& image, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false); - CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false); - CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false); - - struct CV_EXPORTS CannyBuf - { - CannyBuf() {} - explicit CannyBuf(const Size& image_size, int apperture_size = 3) {create(image_size, apperture_size);} - CannyBuf(const GpuMat& dx_, const GpuMat& dy_); - - void create(const Size& image_size, int apperture_size = 3); - - void release(); - - GpuMat dx, dy; - GpuMat dx_buf, dy_buf; - GpuMat edgeBuf; - GpuMat trackBuf1, trackBuf2; - Ptr filterDX, filterDY; - }; - - ////////////////////////////// Matrix reductions ////////////////////////////// - - //! computes mean value and standard deviation of all or selected array elements - //! supports only CV_8UC1 type - CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev); - - //! computes norm of array - //! supports NORM_INF, NORM_L1, NORM_L2 - //! supports all matrices except 64F - CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2); - - //! computes norm of array - //! supports NORM_INF, NORM_L1, NORM_L2 - //! supports all matrices except 64F - CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf); - - //! computes norm of the difference between two arrays - //! supports NORM_INF, NORM_L1, NORM_L2 - //! supports only CV_8UC1 type - CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2); - - //! computes sum of array elements - //! supports only single channel images - CV_EXPORTS Scalar sum(const GpuMat& src); - - //! computes sum of array elements - //! supports only single channel images - CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf); - - //! computes sum of array elements absolute values - //! supports only single channel images - CV_EXPORTS Scalar absSum(const GpuMat& src); - - //! computes sum of array elements absolute values - //! supports only single channel images - CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf); - - //! computes squared sum of array elements - //! supports only single channel images - CV_EXPORTS Scalar sqrSum(const GpuMat& src); - - //! computes squared sum of array elements - //! supports only single channel images - CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf); - - //! finds global minimum and maximum array elements and returns their values - CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat()); - - //! finds global minimum and maximum array elements and returns their values - CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf); - - //! finds global minimum and maximum array elements and returns their values with locations - CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, - const GpuMat& mask=GpuMat()); - - //! finds global minimum and maximum array elements and returns their values with locations - CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc, - const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf); - - //! counts non-zero array elements - CV_EXPORTS int countNonZero(const GpuMat& src); - - //! counts non-zero array elements - CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf); - - //! reduces a matrix to a vector - CV_EXPORTS void reduce(const GpuMat& mtx, GpuMat& vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null()); - - - ///////////////////////////// Calibration 3D ////////////////////////////////// - - CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, - GpuMat& dst, Stream& stream = Stream::Null()); - - CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec, - const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst, - Stream& stream = Stream::Null()); - - CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat, - const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false, - int num_iters=100, float max_dist=8.0, int min_inlier_count=100, - vector* inliers=NULL); - - //////////////////////////////// Image Labeling //////////////////////////////// - - //!performs labeling via graph cuts - CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels, GpuMat& buf, Stream& stream = Stream::Null()); - - ////////////////////////////////// Histograms ////////////////////////////////// - - //! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type. - CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel); - //! Calculates histogram with evenly distributed bins for signle channel source. - //! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types. - //! Output hist will have one row and histSize cols and CV_32SC1 type. - CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null()); - CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null()); - //! Calculates histogram with evenly distributed bins for four-channel source. - //! All channels of source are processed separately. - //! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types. - //! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type. - CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null()); - CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null()); - //! Calculates histogram with bins determined by levels array. - //! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise. - //! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types. - //! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type. - CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null()); - CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null()); - //! Calculates histogram with bins determined by levels array. - //! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise. - //! All channels of source are processed separately. - //! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types. - //! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type. - CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null()); - CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null()); - - //! Calculates histogram for 8u one channel image - //! Output hist will have one row, 256 cols and CV32SC1 type. - CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null()); - CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null()); - - //! normalizes the grayscale image brightness and contrast by normalizing its histogram - CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()); - CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null()); - CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null()); - - //////////////////////////////// StereoBM_GPU //////////////////////////////// - - class CV_EXPORTS StereoBM_GPU - { - public: - enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 }; - - enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 }; - - //! the default constructor - StereoBM_GPU(); - //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8. - StereoBM_GPU(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ); - - //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair - //! Output disparity has CV_8U type. - void operator() ( const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null()); - - //! Some heuristics that tries to estmate - // if current GPU will be faster than CPU in this algorithm. - // It queries current active device. - static bool checkIfGpuCallReasonable(); - - int preset; - int ndisp; - int winSize; - - // If avergeTexThreshold == 0 => post procesing is disabled - // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image - // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold - // i.e. input left image is low textured. - float avergeTexThreshold; - private: - GpuMat minSSD, leBuf, riBuf; - }; - - ////////////////////////// StereoBeliefPropagation /////////////////////////// - // "Efficient Belief Propagation for Early Vision" - // P.Felzenszwalb - - class CV_EXPORTS StereoBeliefPropagation - { - public: - enum { DEFAULT_NDISP = 64 }; - enum { DEFAULT_ITERS = 5 }; - enum { DEFAULT_LEVELS = 5 }; - - static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels); - - //! the default constructor - explicit StereoBeliefPropagation(int ndisp = DEFAULT_NDISP, - int iters = DEFAULT_ITERS, - int levels = DEFAULT_LEVELS, - int msg_type = CV_32F); - - //! the full constructor taking the number of disparities, number of BP iterations on each level, - //! number of levels, truncation of data cost, data weight, - //! truncation of discontinuity cost and discontinuity single jump - //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term) - //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term) - //! please see paper for more details - StereoBeliefPropagation(int ndisp, int iters, int levels, - float max_data_term, float data_weight, - float max_disc_term, float disc_single_jump, - int msg_type = CV_32F); - - //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair, - //! if disparity is empty output type will be CV_16S else output type will be disparity.type(). - void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null()); - - - //! version for user specified data term - void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null()); - - int ndisp; - - int iters; - int levels; - - float max_data_term; - float data_weight; - float max_disc_term; - float disc_single_jump; - - int msg_type; - private: - GpuMat u, d, l, r, u2, d2, l2, r2; - std::vector datas; - GpuMat out; - }; - - /////////////////////////// StereoConstantSpaceBP /////////////////////////// - // "A Constant-Space Belief Propagation Algorithm for Stereo Matching" - // Qingxiong Yang, Liang Wang, Narendra Ahuja - // http://vision.ai.uiuc.edu/~qyang6/ - - class CV_EXPORTS StereoConstantSpaceBP - { - public: - enum { DEFAULT_NDISP = 128 }; - enum { DEFAULT_ITERS = 8 }; - enum { DEFAULT_LEVELS = 4 }; - enum { DEFAULT_NR_PLANE = 4 }; - - static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane); - - //! the default constructor - explicit StereoConstantSpaceBP(int ndisp = DEFAULT_NDISP, - int iters = DEFAULT_ITERS, - int levels = DEFAULT_LEVELS, - int nr_plane = DEFAULT_NR_PLANE, - int msg_type = CV_32F); - - //! the full constructor taking the number of disparities, number of BP iterations on each level, - //! number of levels, number of active disparity on the first level, truncation of data cost, data weight, - //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold - StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane, - float max_data_term, float data_weight, float max_disc_term, float disc_single_jump, - int min_disp_th = 0, - int msg_type = CV_32F); - - //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair, - //! if disparity is empty output type will be CV_16S else output type will be disparity.type(). - void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null()); - - int ndisp; - - int iters; - int levels; - - int nr_plane; - - float max_data_term; - float data_weight; - float max_disc_term; - float disc_single_jump; - - int min_disp_th; - - int msg_type; - - bool use_local_init_data_cost; - private: - GpuMat u[2], d[2], l[2], r[2]; - GpuMat disp_selected_pyr[2]; - - GpuMat data_cost; - GpuMat data_cost_selected; - - GpuMat temp; - - GpuMat out; - }; - - /////////////////////////// DisparityBilateralFilter /////////////////////////// - // Disparity map refinement using joint bilateral filtering given a single color image. - // Qingxiong Yang, Liang Wang, Narendra Ahuja - // http://vision.ai.uiuc.edu/~qyang6/ - - class CV_EXPORTS DisparityBilateralFilter - { - public: - enum { DEFAULT_NDISP = 64 }; - enum { DEFAULT_RADIUS = 3 }; - enum { DEFAULT_ITERS = 1 }; - - //! the default constructor - explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS); - - //! the full constructor taking the number of disparities, filter radius, - //! number of iterations, truncation of data continuity, truncation of disparity continuity - //! and filter range sigma - DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range); - - //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image. - //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type. - void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null()); - - private: - int ndisp; - int radius; - int iters; - - float edge_threshold; - float max_disc_threshold; - float sigma_range; - - GpuMat table_color; - GpuMat table_space; - }; - - - //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// - - struct CV_EXPORTS HOGDescriptor - { - enum { DEFAULT_WIN_SIGMA = -1 }; - enum { DEFAULT_NLEVELS = 64 }; - enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL }; - - HOGDescriptor(Size win_size=Size(64, 128), Size block_size=Size(16, 16), - Size block_stride=Size(8, 8), Size cell_size=Size(8, 8), - int nbins=9, double win_sigma=DEFAULT_WIN_SIGMA, - double threshold_L2hys=0.2, bool gamma_correction=true, - int nlevels=DEFAULT_NLEVELS); - - size_t getDescriptorSize() const; - size_t getBlockHistogramSize() const; - - void setSVMDetector(const vector& detector); - - static vector getDefaultPeopleDetector(); - static vector getPeopleDetector48x96(); - static vector getPeopleDetector64x128(); - - void detect(const GpuMat& img, vector& found_locations, - double hit_threshold=0, Size win_stride=Size(), - Size padding=Size()); - - void detectMultiScale(const GpuMat& img, vector& found_locations, - double hit_threshold=0, Size win_stride=Size(), - Size padding=Size(), double scale0=1.05, - int group_threshold=2); - - void getDescriptors(const GpuMat& img, Size win_stride, - GpuMat& descriptors, - int descr_format=DESCR_FORMAT_COL_BY_COL); - - Size win_size; - Size block_size; - Size block_stride; - Size cell_size; - int nbins; - double win_sigma; - double threshold_L2hys; - bool gamma_correction; - int nlevels; - - protected: - void computeBlockHistograms(const GpuMat& img); - void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& qangle); - - double getWinSigma() const; - bool checkDetectorSize() const; - - static int numPartsWithin(int size, int part_size, int stride); - static Size numPartsWithin(Size size, Size part_size, Size stride); - - // Coefficients of the separating plane - float free_coef; - GpuMat detector; - - // Results of the last classification step - GpuMat labels, labels_buf; - Mat labels_host; - - // Results of the last histogram evaluation step - GpuMat block_hists, block_hists_buf; - - // Gradients conputation results - GpuMat grad, qangle, grad_buf, qangle_buf; - - // returns subbuffer with required size, reallocates buffer if nessesary. - static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf); - static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf); - - std::vector image_scales; - }; - - - ////////////////////////////////// BruteForceMatcher ////////////////////////////////// - - class CV_EXPORTS BruteForceMatcher_GPU_base - { - public: - enum DistType {L1Dist = 0, L2Dist, HammingDist}; - - explicit BruteForceMatcher_GPU_base(DistType distType = L2Dist); - - // Add descriptors to train descriptor collection - void add(const std::vector& descCollection); - - // Get train descriptors collection - const std::vector& getTrainDescriptors() const; - - // Clear train descriptors collection - void clear(); - - // Return true if there are not train descriptors in collection - bool empty() const; - - // Return true if the matcher supports mask in match methods - bool isMaskSupported() const; - - // Find one best match for each query descriptor - void matchSingle(const GpuMat& query, const GpuMat& train, - GpuMat& trainIdx, GpuMat& distance, - const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); - - // Download trainIdx and distance and convert it to CPU vector with DMatch - static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector& matches); - // Convert trainIdx and distance to vector with DMatch - static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector& matches); - - // Find one best match for each query descriptor - void match(const GpuMat& query, const GpuMat& train, std::vector& matches, const GpuMat& mask = GpuMat()); - - // Make gpu collection of trains and masks in suitable format for matchCollection function - void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector& masks = std::vector()); - - // Find one best match from train collection for each query descriptor - void matchCollection(const GpuMat& query, const GpuMat& trainCollection, - GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, - const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null()); - - // Download trainIdx, imgIdx and distance and convert it to vector with DMatch - static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector& matches); - // Convert trainIdx, imgIdx and distance to vector with DMatch - static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector& matches); - - // Find one best match from train collection for each query descriptor. - void match(const GpuMat& query, std::vector& matches, const std::vector& masks = std::vector()); - - // Find k best matches for each query descriptor (in increasing order of distances) - void knnMatchSingle(const GpuMat& query, const GpuMat& train, - GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k, - const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); - - // Download trainIdx and distance and convert it to vector with DMatch - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, - std::vector< std::vector >& matches, bool compactResult = false); - // Convert trainIdx and distance to vector with DMatch - static void knnMatchConvert(const Mat& trainIdx, const Mat& distance, - std::vector< std::vector >& matches, bool compactResult = false); - - // Find k best matches for each query descriptor (in increasing order of distances). - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - void knnMatch(const GpuMat& query, const GpuMat& train, - std::vector< std::vector >& matches, int k, const GpuMat& mask = GpuMat(), - bool compactResult = false); - - // Find k best matches from train collection for each query descriptor (in increasing order of distances) - void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection, - GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, - const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null()); - - // Download trainIdx and distance and convert it to vector with DMatch - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - static void knnMatch2Download(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, - std::vector< std::vector >& matches, bool compactResult = false); - // Convert trainIdx and distance to vector with DMatch - static void knnMatch2Convert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, - std::vector< std::vector >& matches, bool compactResult = false); - - // Find k best matches for each query descriptor (in increasing order of distances). - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - void knnMatch(const GpuMat& query, std::vector< std::vector >& matches, int k, - const std::vector& masks = std::vector(), bool compactResult = false); - - // Find best matches for each query descriptor which have distance less than maxDistance. - // nMatches.at(0, queryIdx) will contain matches count for queryIdx. - // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches, - // because it didn't have enough memory. - // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10), - // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches - // Matches doesn't sorted. - void radiusMatchSingle(const GpuMat& query, const GpuMat& train, - GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, - const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); - - // Download trainIdx, nMatches and distance and convert it to vector with DMatch. - // matches will be sorted in increasing order of distances. - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, const GpuMat& nMatches, - std::vector< std::vector >& matches, bool compactResult = false); - // Convert trainIdx, nMatches and distance to vector with DMatch. - static void radiusMatchConvert(const Mat& trainIdx, const Mat& distance, const Mat& nMatches, - std::vector< std::vector >& matches, bool compactResult = false); - - // Find best matches for each query descriptor which have distance less than maxDistance - // in increasing order of distances). - void radiusMatch(const GpuMat& query, const GpuMat& train, - std::vector< std::vector >& matches, float maxDistance, - const GpuMat& mask = GpuMat(), bool compactResult = false); - - // Find best matches for each query descriptor which have distance less than maxDistance. - // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10), - // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches - // Matches doesn't sorted. - void radiusMatchCollection(const GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, - const std::vector& masks = std::vector(), Stream& stream = Stream::Null()); - - // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch. - // matches will be sorted in increasing order of distances. - // compactResult is used when mask is not empty. If compactResult is false matches - // vector will have the same size as queryDescriptors rows. If compactResult is true - // matches vector will not contain matches for fully masked out query descriptors. - static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& nMatches, - std::vector< std::vector >& matches, bool compactResult = false); - // Convert trainIdx, nMatches and distance to vector with DMatch. - static void radiusMatchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, const Mat& nMatches, - std::vector< std::vector >& matches, bool compactResult = false); - - // Find best matches from train collection for each query descriptor which have distance less than - // maxDistance (in increasing order of distances). - void radiusMatch(const GpuMat& query, std::vector< std::vector >& matches, float maxDistance, - const std::vector& masks = std::vector(), bool compactResult = false); - - DistType distType; - - private: - std::vector trainDescCollection; - }; - - template - class CV_EXPORTS BruteForceMatcher_GPU; - - template - class CV_EXPORTS BruteForceMatcher_GPU< L1 > : public BruteForceMatcher_GPU_base - { - public: - explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L1Dist) {} - explicit BruteForceMatcher_GPU(L1 /*d*/) : BruteForceMatcher_GPU_base(L1Dist) {} - }; - template - class CV_EXPORTS BruteForceMatcher_GPU< L2 > : public BruteForceMatcher_GPU_base - { - public: - explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L2Dist) {} - explicit BruteForceMatcher_GPU(L2 /*d*/) : BruteForceMatcher_GPU_base(L2Dist) {} - }; - template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BruteForceMatcher_GPU_base - { - public: - explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(HammingDist) {} - explicit BruteForceMatcher_GPU(Hamming /*d*/) : BruteForceMatcher_GPU_base(HammingDist) {} - }; - - ////////////////////////////////// CascadeClassifier_GPU ////////////////////////////////////////// - // The cascade classifier class for object detection. - class CV_EXPORTS CascadeClassifier_GPU - { - public: - CascadeClassifier_GPU(); - CascadeClassifier_GPU(const string& filename); - ~CascadeClassifier_GPU(); - - bool empty() const; - bool load(const string& filename); - void release(); - - /* returns number of detected objects */ - int detectMultiScale( const GpuMat& image, GpuMat& objectsBuf, double scaleFactor=1.2, int minNeighbors=4, Size minSize=Size()); - - bool findLargestObject; - bool visualizeInPlace; - - Size getClassifierSize() const; - private: - - struct CascadeClassifierImpl; - CascadeClassifierImpl* impl; - }; - - ////////////////////////////////// SURF ////////////////////////////////////////// - - class CV_EXPORTS SURF_GPU : public CvSURFParams - { - public: - enum KeypointLayout - { - SF_X = 0, - SF_Y, - SF_LAPLACIAN, - SF_SIZE, - SF_DIR, - SF_HESSIAN, - SF_FEATURE_STRIDE - }; - - //! the default constructor - SURF_GPU(); - //! the full constructor taking all the necessary parameters - explicit SURF_GPU(double _hessianThreshold, int _nOctaves=4, - int _nOctaveLayers=2, bool _extended=false, float _keypointsRatio=0.01f, bool _upright = false); - - //! returns the descriptor size in float's (64 or 128) - int descriptorSize() const; - - //! upload host keypoints to device memory - void uploadKeypoints(const vector& keypoints, GpuMat& keypointsGPU); - //! download keypoints from device to host memory - void downloadKeypoints(const GpuMat& keypointsGPU, vector& keypoints); - - //! download descriptors from device to host memory - void downloadDescriptors(const GpuMat& descriptorsGPU, vector& descriptors); - - //! finds the keypoints using fast hessian detector used in SURF - //! supports CV_8UC1 images - //! keypoints will have nFeature cols and 6 rows - //! keypoints.ptr(SF_X)[i] will contain x coordinate of i'th feature - //! keypoints.ptr(SF_Y)[i] will contain y coordinate of i'th feature - //! keypoints.ptr(SF_LAPLACIAN)[i] will contain laplacian sign of i'th feature - //! keypoints.ptr(SF_SIZE)[i] will contain size of i'th feature - //! keypoints.ptr(SF_DIR)[i] will contain orientation of i'th feature - //! keypoints.ptr(SF_HESSIAN)[i] will contain response of i'th feature - void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints); - //! finds the keypoints and computes their descriptors. - //! Optionally it can compute descriptors for the user-provided keypoints and recompute keypoints direction - void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors, - bool useProvidedKeypoints = false); - - void operator()(const GpuMat& img, const GpuMat& mask, std::vector& keypoints); - void operator()(const GpuMat& img, const GpuMat& mask, std::vector& keypoints, GpuMat& descriptors, - bool useProvidedKeypoints = false); - - void operator()(const GpuMat& img, const GpuMat& mask, std::vector& keypoints, std::vector& descriptors, - bool useProvidedKeypoints = false); - - void releaseMemory(); - - //! max keypoints = min(keypointsRatio * img.size().area(), 65535) - float keypointsRatio; - - GpuMat sum, mask1, maskSum, intBuffer; - - GpuMat det, trace; - - GpuMat maxPosBuffer; - }; - - ////////////////////////////////// Optical Flow ////////////////////////////////////////// - - class CV_EXPORTS BroxOpticalFlow - { - public: - BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_) : - alpha(alpha_), gamma(gamma_), scale_factor(scale_factor_), - inner_iterations(inner_iterations_), outer_iterations(outer_iterations_), solver_iterations(solver_iterations_) - { - } - - //! Compute optical flow - //! frame0 - source frame (supports only CV_32FC1 type) - //! frame1 - frame to track (with the same size and type as frame0) - //! u - flow horizontal component (along x axis) - //! v - flow vertical component (along y axis) - void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null()); - - //! flow smoothness - float alpha; - - //! gradient constancy importance - float gamma; - - //! pyramid scale factor - float scale_factor; - - //! number of lagged non-linearity iterations (inner loop) - int inner_iterations; - - //! number of warping iterations (number of pyramid levels) - int outer_iterations; - - //! number of linear system solver iterations - int solver_iterations; - - GpuMat buf; - }; - - //! Interpolate frames (images) using provided optical flow (displacement field). - //! frame0 - frame 0 (32-bit floating point images, single channel) - //! frame1 - frame 1 (the same type and size) - //! fu - forward horizontal displacement - //! fv - forward vertical displacement - //! bu - backward horizontal displacement - //! bv - backward vertical displacement - //! pos - new frame position - //! newFrame - new frame - //! buf - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 GpuMat; - //! occlusion masks 0, occlusion masks 1, - //! interpolated forward flow 0, interpolated forward flow 1, - //! interpolated backward flow 0, interpolated backward flow 1 - //! - CV_EXPORTS void interpolateFrames(const GpuMat& frame0, const GpuMat& frame1, - const GpuMat& fu, const GpuMat& fv, - const GpuMat& bu, const GpuMat& bv, - float pos, GpuMat& newFrame, GpuMat& buf, - Stream& stream = Stream::Null()); - - } - - //! Speckle filtering - filters small connected components on diparity image. - //! It sets pixel (x,y) to newVal if it coresponds to small CC with size < maxSpeckleSize. - //! Threshold for border between CC is diffThreshold; - CV_EXPORTS void filterSpeckles( Mat& img, uchar newVal, int maxSpeckleSize, uchar diffThreshold, Mat& buf); - -} -#include "opencv2/gpu/matrix_operations.hpp" - -#endif /* __OPENCV_GPU_HPP__ */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpumat.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpumat.hpp deleted file mode 100755 index c3dc39b..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/gpumat.hpp +++ /dev/null @@ -1,276 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. -// -// * The name of the copyright holders 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 __OPENCV_GPUMAT_HPP__ -#define __OPENCV_GPUMAT_HPP__ - -#include "opencv2/core/core.hpp" -#include "opencv2/gpu/devmem2d.hpp" - -namespace cv { namespace gpu -{ - class Stream; - class CudaMem; - - //! Smart pointer for GPU memory with reference counting. Its interface is mostly similar with cv::Mat. - class CV_EXPORTS GpuMat - { - public: - //! default constructor - GpuMat(); - //! constructs GpuMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) - GpuMat(int rows, int cols, int type); - GpuMat(Size size, int type); - //! constucts GpuMatrix and fills it with the specified value _s. - GpuMat(int rows, int cols, int type, const Scalar& s); - GpuMat(Size size, int type, const Scalar& s); - //! copy constructor - GpuMat(const GpuMat& m); - - //! constructor for GpuMatrix headers pointing to user-allocated data - GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); - GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); - - //! creates a matrix header for a part of the bigger matrix - GpuMat(const GpuMat& m, const Range& rowRange, const Range& colRange); - GpuMat(const GpuMat& m, const Rect& roi); - - //! builds GpuMat from Mat. Perfom blocking upload to device. - explicit GpuMat (const Mat& m); - - //! destructor - calls release() - ~GpuMat(); - - //! assignment operators - GpuMat& operator = (const GpuMat& m); - //! assignment operator. Perfom blocking upload to device. - GpuMat& operator = (const Mat& m); - - //! returns lightweight DevMem2D_ structure for passing to nvcc-compiled code. - // Contains just image size, data ptr and step. - template operator DevMem2D_() const; - template operator PtrStep_() const; - template operator PtrStep() const; - - //! pefroms blocking upload data to GpuMat. - void upload(const cv::Mat& m); - - //! upload async - void upload(const CudaMem& m, Stream& stream); - - //! downloads data from device to host memory. Blocking calls. - operator Mat() const; - void download(cv::Mat& m) const; - - //! download async - void download(CudaMem& m, Stream& stream) const; - - //! returns a new GpuMatrix header for the specified row - GpuMat row(int y) const; - //! returns a new GpuMatrix header for the specified column - GpuMat col(int x) const; - //! ... for the specified row span - GpuMat rowRange(int startrow, int endrow) const; - GpuMat rowRange(const Range& r) const; - //! ... for the specified column span - GpuMat colRange(int startcol, int endcol) const; - GpuMat colRange(const Range& r) const; - - //! returns deep copy of the GpuMatrix, i.e. the data is copied - GpuMat clone() const; - //! copies the GpuMatrix content to "m". - // It calls m.create(this->size(), this->type()). - void copyTo( GpuMat& m ) const; - //! copies those GpuMatrix elements to "m" that are marked with non-zero mask elements. - void copyTo( GpuMat& m, const GpuMat& mask ) const; - //! converts GpuMatrix to another datatype with optional scalng. See cvConvertScale. - void convertTo( GpuMat& m, int rtype, double alpha=1, double beta=0 ) const; - - void assignTo( GpuMat& m, int type=-1 ) const; - - //! sets every GpuMatrix element to s - GpuMat& operator = (const Scalar& s); - //! sets some of the GpuMatrix elements to s, according to the mask - GpuMat& setTo(const Scalar& s, const GpuMat& mask = GpuMat()); - //! creates alternative GpuMatrix header for the same data, with different - // number of channels and/or different number of rows. see cvReshape. - GpuMat reshape(int cn, int rows = 0) const; - - //! allocates new GpuMatrix data unless the GpuMatrix already has specified size and type. - // previous data is unreferenced if needed. - void create(int rows, int cols, int type); - void create(Size size, int type); - //! decreases reference counter; - // deallocate the data when reference counter reaches 0. - void release(); - - //! swaps with other smart pointer - void swap(GpuMat& mat); - - //! locates GpuMatrix header within a parent GpuMatrix. See below - void locateROI( Size& wholeSize, Point& ofs ) const; - //! moves/resizes the current GpuMatrix ROI inside the parent GpuMatrix. - GpuMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - //! extracts a rectangular sub-GpuMatrix - // (this is a generalized form of row, rowRange etc.) - GpuMat operator()( Range rowRange, Range colRange ) const; - GpuMat operator()( const Rect& roi ) const; - - //! returns true iff the GpuMatrix data is continuous - // (i.e. when there are no gaps between successive rows). - // similar to CV_IS_GpuMat_CONT(cvGpuMat->type) - bool isContinuous() const; - //! returns element size in bytes, - // similar to CV_ELEM_SIZE(cvMat->type) - size_t elemSize() const; - //! returns the size of element channel in bytes. - size_t elemSize1() const; - //! returns element type, similar to CV_MAT_TYPE(cvMat->type) - int type() const; - //! returns element type, similar to CV_MAT_DEPTH(cvMat->type) - int depth() const; - //! returns element type, similar to CV_MAT_CN(cvMat->type) - int channels() const; - //! returns step/elemSize1() - size_t step1() const; - //! returns GpuMatrix size: - // width == number of columns, height == number of rows - Size size() const; - //! returns true if GpuMatrix data is NULL - bool empty() const; - - //! returns pointer to y-th row - uchar* ptr(int y = 0); - const uchar* ptr(int y = 0) const; - - //! template version of the above method - template _Tp* ptr(int y = 0); - template const _Tp* ptr(int y = 0) const; - - //! matrix transposition - GpuMat t() const; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - //! the number of rows and columns - int rows, cols; - //! a distance between successive rows in bytes; includes the gap if any - size_t step; - //! pointer to the data - uchar* data; - - //! pointer to the reference counter; - // when GpuMatrix points to user-allocated data, the pointer is NULL - int* refcount; - - //! helper fields used in locateROI and adjustROI - uchar* datastart; - uchar* dataend; - }; - - //! Creates continuous GPU matrix - CV_EXPORTS void createContinuous(int rows, int cols, int type, GpuMat& m); - CV_EXPORTS GpuMat createContinuous(int rows, int cols, int type); - CV_EXPORTS void createContinuous(Size size, int type, GpuMat& m); - CV_EXPORTS GpuMat createContinuous(Size size, int type); - - //! Ensures that size of the given matrix is not less than (rows, cols) size - //! and matrix type is match specified one too - CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, GpuMat& m); - CV_EXPORTS void ensureSizeIsEnough(Size size, int type, GpuMat& m); - - //////////////////////////////////////////////////////////////////////// - //////////////////////////////// GpuMat //////////////////////////////// - //////////////////////////////////////////////////////////////////////// - - inline GpuMat::GpuMat() : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) {} - - inline GpuMat::GpuMat(int rows_, int cols_, int type_) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) - { - if (rows_ > 0 && cols_ > 0) - create(rows_, cols_, type_); - } - - inline GpuMat::~GpuMat() { release(); } - - template inline GpuMat::operator DevMem2D_() const { return DevMem2D_(rows, cols, (T*)data, step); } - template inline GpuMat::operator PtrStep_() const { return PtrStep_(static_cast< DevMem2D_ >(*this)); } - template inline GpuMat::operator PtrStep() const { return PtrStep((T*)data, step); } - - inline GpuMat GpuMat::clone() const - { - GpuMat m; - copyTo(m); - return m; - } - - inline void GpuMat::assignTo(GpuMat& m, int type) const - { - if( type < 0 ) - m = *this; - else - convertTo(m, type); - } - - inline size_t GpuMat::step1() const { return step/elemSize1(); } - - inline bool GpuMat::empty() const { return data == 0; } - - template inline _Tp* GpuMat::ptr(int y) - { - return (_Tp*)ptr(y); - } - - template inline const _Tp* GpuMat::ptr(int y) const - { - return (const _Tp*)ptr(y); - } - - inline void swap(GpuMat& a, GpuMat& b) { a.swap(b); } -}} - -#endif // __OPENCV_GPUMAT_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/matrix_operations.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/matrix_operations.hpp deleted file mode 100755 index 5a6b1bb..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/matrix_operations.hpp +++ /dev/null @@ -1,142 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. -// -// * The name of the copyright holders 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 __OPENCV_GPU_MATRIX_OPERATIONS_HPP__ -#define __OPENCV_GPU_MATRIX_OPERATIONS_HPP__ - -namespace cv -{ - -namespace gpu -{ -/////////////////////////////////////////////////////////////////////// -//////////////////////////////// CudaMem //////////////////////////////// -/////////////////////////////////////////////////////////////////////// - -inline CudaMem::CudaMem() : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0) {} -inline CudaMem::CudaMem(int _rows, int _cols, int _type, int _alloc_type) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0) -{ - if( _rows > 0 && _cols > 0 ) - create( _rows, _cols, _type, _alloc_type); -} - -inline CudaMem::CudaMem(Size _size, int _type, int _alloc_type) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0) -{ - if( _size.height > 0 && _size.width > 0 ) - create( _size.height, _size.width, _type, _alloc_type); -} - -inline CudaMem::CudaMem(const CudaMem& m) : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) -{ - if( refcount ) - CV_XADD(refcount, 1); -} - -inline CudaMem::CudaMem(const Mat& m, int _alloc_type) : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0) -{ - if( m.rows > 0 && m.cols > 0 ) - create( m.size(), m.type(), _alloc_type); - - Mat tmp = createMatHeader(); - m.copyTo(tmp); -} - -inline CudaMem::~CudaMem() -{ - release(); - -} - -inline CudaMem& CudaMem::operator = (const CudaMem& m) -{ - if( this != &m ) - { - if( m.refcount ) - CV_XADD(m.refcount, 1); - release(); - flags = m.flags; - rows = m.rows; cols = m.cols; - step = m.step; data = m.data; - datastart = m.datastart; - dataend = m.dataend; - refcount = m.refcount; - alloc_type = m.alloc_type; - } - return *this; -} - -inline CudaMem CudaMem::clone() const -{ - CudaMem m(size(), type(), alloc_type); - Mat to = m; - Mat from = *this; - from.copyTo(to); - return m; -} - -inline void CudaMem::create(Size _size, int _type, int _alloc_type) { create(_size.height, _size.width, _type, _alloc_type); } - - -//CCP void CudaMem::create(int _rows, int _cols, int _type, int _alloc_type); -//CPP void CudaMem::release(); - -inline Mat CudaMem::createMatHeader() const { return Mat(size(), type(), data, step); } -inline CudaMem::operator Mat() const { return createMatHeader(); } - -inline CudaMem::operator GpuMat() const { return createGpuMatHeader(); } -//CPP GpuMat CudaMem::createGpuMatHeader() const; - -inline bool CudaMem::isContinuous() const { return (flags & Mat::CONTINUOUS_FLAG) != 0; } -inline size_t CudaMem::elemSize() const { return CV_ELEM_SIZE(flags); } -inline size_t CudaMem::elemSize1() const { return CV_ELEM_SIZE1(flags); } -inline int CudaMem::type() const { return CV_MAT_TYPE(flags); } -inline int CudaMem::depth() const { return CV_MAT_DEPTH(flags); } -inline int CudaMem::channels() const { return CV_MAT_CN(flags); } -inline size_t CudaMem::step1() const { return step/elemSize1(); } -inline Size CudaMem::size() const { return Size(cols, rows); } -inline bool CudaMem::empty() const { return data == 0; } - -} /* end of namespace gpu */ - -} /* end of namespace cv */ - -#endif /* __OPENCV_GPU_MATRIX_OPERATIONS_HPP__ */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/stream_accessor.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/stream_accessor.hpp deleted file mode 100755 index cd92ca0..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/stream_accessor.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. -// -// * The name of the copyright holders 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 __OPENCV_GPU_STREAM_ACCESSOR_HPP__ -#define __OPENCV_GPU_STREAM_ACCESSOR_HPP__ - -#include "opencv2/gpu/gpu.hpp" -#include "cuda_runtime_api.h" - -namespace cv -{ - namespace gpu - { - // This is only header file that depends on Cuda. All other headers are independent. - // So if you use OpenCV binaries you do noot need to install Cuda Toolkit. - // But of you wanna use GPU by yourself, may get cuda stream instance using the class below. - // In this case you have to install Cuda Toolkit. - struct StreamAccessor - { - CV_EXPORTS static cudaStream_t getStream(const Stream& stream); - }; - } -} - -#endif /* __OPENCV_GPU_STREAM_ACCESSOR_HPP__ */ \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/legacy.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/legacy.hpp deleted file mode 100755 index d3aaaf6..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/legacy.hpp +++ /dev/null @@ -1,1769 +0,0 @@ -/*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 __OPENCV_LEGACY_HPP__ -#define __OPENCV_LEGACY_HPP__ - -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/calib3d/calib3d.hpp" - -#ifdef __cplusplus -extern "C" { -#endif - -CVAPI(CvSeq*) cvSegmentImage( const CvArr* srcarr, CvArr* dstarr, - double canny_threshold, - double ffill_threshold, - CvMemStorage* storage ); - -/****************************************************************************************\ -* Eigen objects * -\****************************************************************************************/ - -typedef int (CV_CDECL * CvCallback)(int index, void* buffer, void* user_data); -typedef union -{ - CvCallback callback; - void* data; -} -CvInput; - -#define CV_EIGOBJ_NO_CALLBACK 0 -#define CV_EIGOBJ_INPUT_CALLBACK 1 -#define CV_EIGOBJ_OUTPUT_CALLBACK 2 -#define CV_EIGOBJ_BOTH_CALLBACK 3 - -/* Calculates covariation matrix of a set of arrays */ -CVAPI(void) cvCalcCovarMatrixEx( int nObjects, void* input, int ioFlags, - int ioBufSize, uchar* buffer, void* userData, - IplImage* avg, float* covarMatrix ); - -/* Calculates eigen values and vectors of covariation matrix of a set of - arrays */ -CVAPI(void) cvCalcEigenObjects( int nObjects, void* input, void* output, - int ioFlags, int ioBufSize, void* userData, - CvTermCriteria* calcLimit, IplImage* avg, - float* eigVals ); - -/* Calculates dot product (obj - avg) * eigObj (i.e. projects image to eigen vector) */ -CVAPI(double) cvCalcDecompCoeff( IplImage* obj, IplImage* eigObj, IplImage* avg ); - -/* Projects image to eigen space (finds all decomposion coefficients */ -CVAPI(void) cvEigenDecomposite( IplImage* obj, int nEigObjs, void* eigInput, - int ioFlags, void* userData, IplImage* avg, - float* coeffs ); - -/* Projects original objects used to calculate eigen space basis to that space */ -CVAPI(void) cvEigenProjection( void* eigInput, int nEigObjs, int ioFlags, - void* userData, float* coeffs, IplImage* avg, - IplImage* proj ); - -/****************************************************************************************\ -* 1D/2D HMM * -\****************************************************************************************/ - -typedef struct CvImgObsInfo -{ - int obs_x; - int obs_y; - int obs_size; - float* obs;//consequtive observations - - int* state;/* arr of pairs superstate/state to which observation belong */ - int* mix; /* number of mixture to which observation belong */ - -} CvImgObsInfo;/*struct for 1 image*/ - -typedef CvImgObsInfo Cv1DObsInfo; - -typedef struct CvEHMMState -{ - int num_mix; /*number of mixtures in this state*/ - float* mu; /*mean vectors corresponding to each mixture*/ - float* inv_var; /* square root of inversed variances corresp. to each mixture*/ - float* log_var_val; /* sum of 0.5 (LN2PI + ln(variance[i]) ) for i=1,n */ - float* weight; /*array of mixture weights. Summ of all weights in state is 1. */ - -} CvEHMMState; - -typedef struct CvEHMM -{ - int level; /* 0 - lowest(i.e its states are real states), ..... */ - int num_states; /* number of HMM states */ - float* transP;/*transition probab. matrices for states */ - float** obsProb; /* if level == 0 - array of brob matrices corresponding to hmm - if level == 1 - martix of matrices */ - union - { - CvEHMMState* state; /* if level == 0 points to real states array, - if not - points to embedded hmms */ - struct CvEHMM* ehmm; /* pointer to an embedded model or NULL, if it is a leaf */ - } u; - -} CvEHMM; - -/*CVAPI(int) icvCreate1DHMM( CvEHMM** this_hmm, - int state_number, int* num_mix, int obs_size ); - -CVAPI(int) icvRelease1DHMM( CvEHMM** phmm ); - -CVAPI(int) icvUniform1DSegm( Cv1DObsInfo* obs_info, CvEHMM* hmm ); - -CVAPI(int) icvInit1DMixSegm( Cv1DObsInfo** obs_info_array, int num_img, CvEHMM* hmm); - -CVAPI(int) icvEstimate1DHMMStateParams( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm); - -CVAPI(int) icvEstimate1DObsProb( CvImgObsInfo* obs_info, CvEHMM* hmm ); - -CVAPI(int) icvEstimate1DTransProb( Cv1DObsInfo** obs_info_array, - int num_seq, - CvEHMM* hmm ); - -CVAPI(float) icvViterbi( Cv1DObsInfo* obs_info, CvEHMM* hmm); - -CVAPI(int) icv1DMixSegmL2( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm );*/ - -/*********************************** Embedded HMMs *************************************/ - -/* Creates 2D HMM */ -CVAPI(CvEHMM*) cvCreate2DHMM( int* stateNumber, int* numMix, int obsSize ); - -/* Releases HMM */ -CVAPI(void) cvRelease2DHMM( CvEHMM** hmm ); - -#define CV_COUNT_OBS(roi, win, delta, numObs ) \ -{ \ - (numObs)->width =((roi)->width -(win)->width +(delta)->width)/(delta)->width; \ - (numObs)->height =((roi)->height -(win)->height +(delta)->height)/(delta)->height;\ -} - -/* Creates storage for observation vectors */ -CVAPI(CvImgObsInfo*) cvCreateObsInfo( CvSize numObs, int obsSize ); - -/* Releases storage for observation vectors */ -CVAPI(void) cvReleaseObsInfo( CvImgObsInfo** obs_info ); - - -/* The function takes an image on input and and returns the sequnce of observations - to be used with an embedded HMM; Each observation is top-left block of DCT - coefficient matrix */ -CVAPI(void) cvImgToObs_DCT( const CvArr* arr, float* obs, CvSize dctSize, - CvSize obsSize, CvSize delta ); - - -/* Uniformly segments all observation vectors extracted from image */ -CVAPI(void) cvUniformImgSegm( CvImgObsInfo* obs_info, CvEHMM* ehmm ); - -/* Does mixture segmentation of the states of embedded HMM */ -CVAPI(void) cvInitMixSegm( CvImgObsInfo** obs_info_array, - int num_img, CvEHMM* hmm ); - -/* Function calculates means, variances, weights of every Gaussian mixture - of every low-level state of embedded HMM */ -CVAPI(void) cvEstimateHMMStateParams( CvImgObsInfo** obs_info_array, - int num_img, CvEHMM* hmm ); - -/* Function computes transition probability matrices of embedded HMM - given observations segmentation */ -CVAPI(void) cvEstimateTransProb( CvImgObsInfo** obs_info_array, - int num_img, CvEHMM* hmm ); - -/* Function computes probabilities of appearing observations at any state - (i.e. computes P(obs|state) for every pair(obs,state)) */ -CVAPI(void) cvEstimateObsProb( CvImgObsInfo* obs_info, - CvEHMM* hmm ); - -/* Runs Viterbi algorithm for embedded HMM */ -CVAPI(float) cvEViterbi( CvImgObsInfo* obs_info, CvEHMM* hmm ); - - -/* Function clusters observation vectors from several images - given observations segmentation. - Euclidean distance used for clustering vectors. - Centers of clusters are given means of every mixture */ -CVAPI(void) cvMixSegmL2( CvImgObsInfo** obs_info_array, - int num_img, CvEHMM* hmm ); - -/****************************************************************************************\ -* A few functions from old stereo gesture recognition demosions * -\****************************************************************************************/ - -/* Creates hand mask image given several points on the hand */ -CVAPI(void) cvCreateHandMask( CvSeq* hand_points, - IplImage *img_mask, CvRect *roi); - -/* Finds hand region in range image data */ -CVAPI(void) cvFindHandRegion (CvPoint3D32f* points, int count, - CvSeq* indexs, - float* line, CvSize2D32f size, int flag, - CvPoint3D32f* center, - CvMemStorage* storage, CvSeq **numbers); - -/* Finds hand region in range image data (advanced version) */ -CVAPI(void) cvFindHandRegionA( CvPoint3D32f* points, int count, - CvSeq* indexs, - float* line, CvSize2D32f size, int jc, - CvPoint3D32f* center, - CvMemStorage* storage, CvSeq **numbers); - -/* Calculates the cooficients of the homography matrix */ -CVAPI(void) cvCalcImageHomography( float* line, CvPoint3D32f* center, - float* intrinsic, float* homography ); - -/****************************************************************************************\ -* Additional operations on Subdivisions * -\****************************************************************************************/ - -// paints voronoi diagram: just demo function -CVAPI(void) icvDrawMosaic( CvSubdiv2D* subdiv, IplImage* src, IplImage* dst ); - -// checks planar subdivision for correctness. It is not an absolute check, -// but it verifies some relations between quad-edges -CVAPI(int) icvSubdiv2DCheck( CvSubdiv2D* subdiv ); - -// returns squared distance between two 2D points with floating-point coordinates. -CV_INLINE double icvSqDist2D32f( CvPoint2D32f pt1, CvPoint2D32f pt2 ) -{ - double dx = pt1.x - pt2.x; - double dy = pt1.y - pt2.y; - - return dx*dx + dy*dy; -} - - -/****************************************************************************************\ -* More operations on sequences * -\****************************************************************************************/ - -/*****************************************************************************************/ - -#define CV_CURRENT_INT( reader ) (*((int *)(reader).ptr)) -#define CV_PREV_INT( reader ) (*((int *)(reader).prev_elem)) - -#define CV_GRAPH_WEIGHTED_VERTEX_FIELDS() CV_GRAPH_VERTEX_FIELDS()\ - float weight; - -#define CV_GRAPH_WEIGHTED_EDGE_FIELDS() CV_GRAPH_EDGE_FIELDS() - -typedef struct CvGraphWeightedVtx -{ - CV_GRAPH_WEIGHTED_VERTEX_FIELDS() -} CvGraphWeightedVtx; - -typedef struct CvGraphWeightedEdge -{ - CV_GRAPH_WEIGHTED_EDGE_FIELDS() -} CvGraphWeightedEdge; - -typedef enum CvGraphWeightType -{ - CV_NOT_WEIGHTED, - CV_WEIGHTED_VTX, - CV_WEIGHTED_EDGE, - CV_WEIGHTED_ALL -} CvGraphWeightType; - - -/* Calculates histogram of a contour */ -CVAPI(void) cvCalcPGH( const CvSeq* contour, CvHistogram* hist ); - -#define CV_DOMINANT_IPAN 1 - -/* Finds high-curvature points of the contour */ -CVAPI(CvSeq*) cvFindDominantPoints( CvSeq* contour, CvMemStorage* storage, - int method CV_DEFAULT(CV_DOMINANT_IPAN), - double parameter1 CV_DEFAULT(0), - double parameter2 CV_DEFAULT(0), - double parameter3 CV_DEFAULT(0), - double parameter4 CV_DEFAULT(0)); - -/*****************************************************************************************/ - - -/*******************************Stereo correspondence*************************************/ - -typedef struct CvCliqueFinder -{ - CvGraph* graph; - int** adj_matr; - int N; //graph size - - // stacks, counters etc/ - int k; //stack size - int* current_comp; - int** All; - - int* ne; - int* ce; - int* fixp; //node with minimal disconnections - int* nod; - int* s; //for selected candidate - int status; - int best_score; - int weighted; - int weighted_edges; - float best_weight; - float* edge_weights; - float* vertex_weights; - float* cur_weight; - float* cand_weight; - -} CvCliqueFinder; - -#define CLIQUE_TIME_OFF 2 -#define CLIQUE_FOUND 1 -#define CLIQUE_END 0 - -/*CVAPI(void) cvStartFindCliques( CvGraph* graph, CvCliqueFinder* finder, int reverse, - int weighted CV_DEFAULT(0), int weighted_edges CV_DEFAULT(0)); -CVAPI(int) cvFindNextMaximalClique( CvCliqueFinder* finder, int* clock_rest CV_DEFAULT(0) ); -CVAPI(void) cvEndFindCliques( CvCliqueFinder* finder ); - -CVAPI(void) cvBronKerbosch( CvGraph* graph );*/ - - -/*F/////////////////////////////////////////////////////////////////////////////////////// -// -// Name: cvSubgraphWeight -// Purpose: finds weight of subgraph in a graph -// Context: -// Parameters: -// graph - input graph. -// subgraph - sequence of pairwise different ints. These are indices of vertices of subgraph. -// weight_type - describes the way we measure weight. -// one of the following: -// CV_NOT_WEIGHTED - weight of a clique is simply its size -// CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices -// CV_WEIGHTED_EDGE - the same but edges -// CV_WEIGHTED_ALL - the same but both edges and vertices -// weight_vtx - optional vector of floats, with size = graph->total. -// If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL -// weights of vertices must be provided. If weight_vtx not zero -// these weights considered to be here, otherwise function assumes -// that vertices of graph are inherited from CvGraphWeightedVtx. -// weight_edge - optional matrix of floats, of width and height = graph->total. -// If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL -// weights of edges ought to be supplied. If weight_edge is not zero -// function finds them here, otherwise function expects -// edges of graph to be inherited from CvGraphWeightedEdge. -// If this parameter is not zero structure of the graph is determined from matrix -// rather than from CvGraphEdge's. In particular, elements corresponding to -// absent edges should be zero. -// Returns: -// weight of subgraph. -// Notes: -//F*/ -/*CVAPI(float) cvSubgraphWeight( CvGraph *graph, CvSeq *subgraph, - CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED), - CvVect32f weight_vtx CV_DEFAULT(0), - CvMatr32f weight_edge CV_DEFAULT(0) );*/ - - -/*F/////////////////////////////////////////////////////////////////////////////////////// -// -// Name: cvFindCliqueEx -// Purpose: tries to find clique with maximum possible weight in a graph -// Context: -// Parameters: -// graph - input graph. -// storage - memory storage to be used by the result. -// is_complementary - optional flag showing whether function should seek for clique -// in complementary graph. -// weight_type - describes our notion about weight. -// one of the following: -// CV_NOT_WEIGHTED - weight of a clique is simply its size -// CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices -// CV_WEIGHTED_EDGE - the same but edges -// CV_WEIGHTED_ALL - the same but both edges and vertices -// weight_vtx - optional vector of floats, with size = graph->total. -// If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL -// weights of vertices must be provided. If weight_vtx not zero -// these weights considered to be here, otherwise function assumes -// that vertices of graph are inherited from CvGraphWeightedVtx. -// weight_edge - optional matrix of floats, of width and height = graph->total. -// If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL -// weights of edges ought to be supplied. If weight_edge is not zero -// function finds them here, otherwise function expects -// edges of graph to be inherited from CvGraphWeightedEdge. -// Note that in case of CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL -// nonzero is_complementary implies nonzero weight_edge. -// start_clique - optional sequence of pairwise different ints. They are indices of -// vertices that shall be present in the output clique. -// subgraph_of_ban - optional sequence of (maybe equal) ints. They are indices of -// vertices that shall not be present in the output clique. -// clique_weight_ptr - optional output parameter. Weight of found clique stored here. -// num_generations - optional number of generations in evolutionary part of algorithm, -// zero forces to return first found clique. -// quality - optional parameter determining degree of required quality/speed tradeoff. -// Must be in the range from 0 to 9. -// 0 is fast and dirty, 9 is slow but hopefully yields good clique. -// Returns: -// sequence of pairwise different ints. -// These are indices of vertices that form found clique. -// Notes: -// in cases of CV_WEIGHTED_EDGE and CV_WEIGHTED_ALL weights should be nonnegative. -// start_clique has a priority over subgraph_of_ban. -//F*/ -/*CVAPI(CvSeq*) cvFindCliqueEx( CvGraph *graph, CvMemStorage *storage, - int is_complementary CV_DEFAULT(0), - CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED), - CvVect32f weight_vtx CV_DEFAULT(0), - CvMatr32f weight_edge CV_DEFAULT(0), - CvSeq *start_clique CV_DEFAULT(0), - CvSeq *subgraph_of_ban CV_DEFAULT(0), - float *clique_weight_ptr CV_DEFAULT(0), - int num_generations CV_DEFAULT(3), - int quality CV_DEFAULT(2) );*/ - - -#define CV_UNDEF_SC_PARAM 12345 //default value of parameters - -#define CV_IDP_BIRCHFIELD_PARAM1 25 -#define CV_IDP_BIRCHFIELD_PARAM2 5 -#define CV_IDP_BIRCHFIELD_PARAM3 12 -#define CV_IDP_BIRCHFIELD_PARAM4 15 -#define CV_IDP_BIRCHFIELD_PARAM5 25 - - -#define CV_DISPARITY_BIRCHFIELD 0 - - -/*F/////////////////////////////////////////////////////////////////////////// -// -// Name: cvFindStereoCorrespondence -// Purpose: find stereo correspondence on stereo-pair -// Context: -// Parameters: -// leftImage - left image of stereo-pair (format 8uC1). -// rightImage - right image of stereo-pair (format 8uC1). -// mode - mode of correspondence retrieval (now CV_DISPARITY_BIRCHFIELD only) -// dispImage - destination disparity image -// maxDisparity - maximal disparity -// param1, param2, param3, param4, param5 - parameters of algorithm -// Returns: -// Notes: -// Images must be rectified. -// All images must have format 8uC1. -//F*/ -CVAPI(void) -cvFindStereoCorrespondence( - const CvArr* leftImage, const CvArr* rightImage, - int mode, - CvArr* dispImage, - int maxDisparity, - double param1 CV_DEFAULT(CV_UNDEF_SC_PARAM), - double param2 CV_DEFAULT(CV_UNDEF_SC_PARAM), - double param3 CV_DEFAULT(CV_UNDEF_SC_PARAM), - double param4 CV_DEFAULT(CV_UNDEF_SC_PARAM), - double param5 CV_DEFAULT(CV_UNDEF_SC_PARAM) ); - -/*****************************************************************************************/ -/************ Epiline functions *******************/ - - - -typedef struct CvStereoLineCoeff -{ - double Xcoef; - double XcoefA; - double XcoefB; - double XcoefAB; - - double Ycoef; - double YcoefA; - double YcoefB; - double YcoefAB; - - double Zcoef; - double ZcoefA; - double ZcoefB; - double ZcoefAB; -}CvStereoLineCoeff; - - -typedef struct CvCamera -{ - float imgSize[2]; /* size of the camera view, used during calibration */ - float matrix[9]; /* intinsic camera parameters: [ fx 0 cx; 0 fy cy; 0 0 1 ] */ - float distortion[4]; /* distortion coefficients - two coefficients for radial distortion - and another two for tangential: [ k1 k2 p1 p2 ] */ - float rotMatr[9]; - float transVect[3]; /* rotation matrix and transition vector relatively - to some reference point in the space. */ -} CvCamera; - -typedef struct CvStereoCamera -{ - CvCamera* camera[2]; /* two individual camera parameters */ - float fundMatr[9]; /* fundamental matrix */ - - /* New part for stereo */ - CvPoint3D32f epipole[2]; - CvPoint2D32f quad[2][4]; /* coordinates of destination quadrangle after - epipolar geometry rectification */ - double coeffs[2][3][3];/* coefficients for transformation */ - CvPoint2D32f border[2][4]; - CvSize warpSize; - CvStereoLineCoeff* lineCoeffs; - int needSwapCameras;/* flag set to 1 if need to swap cameras for good reconstruction */ - float rotMatrix[9]; - float transVector[3]; -} CvStereoCamera; - - -typedef struct CvContourOrientation -{ - float egvals[2]; - float egvects[4]; - - float max, min; // minimum and maximum projections - int imax, imin; -} CvContourOrientation; - -#define CV_CAMERA_TO_WARP 1 -#define CV_WARP_TO_CAMERA 2 - -CVAPI(int) icvConvertWarpCoordinates(double coeffs[3][3], - CvPoint2D32f* cameraPoint, - CvPoint2D32f* warpPoint, - int direction); - -CVAPI(int) icvGetSymPoint3D( CvPoint3D64f pointCorner, - CvPoint3D64f point1, - CvPoint3D64f point2, - CvPoint3D64f *pointSym2); - -CVAPI(void) icvGetPieceLength3D(CvPoint3D64f point1,CvPoint3D64f point2,double* dist); - -CVAPI(int) icvCompute3DPoint( double alpha,double betta, - CvStereoLineCoeff* coeffs, - CvPoint3D64f* point); - -CVAPI(int) icvCreateConvertMatrVect( double* rotMatr1, - double* transVect1, - double* rotMatr2, - double* transVect2, - double* convRotMatr, - double* convTransVect); - -CVAPI(int) icvConvertPointSystem(CvPoint3D64f M2, - CvPoint3D64f* M1, - double* rotMatr, - double* transVect - ); - -CVAPI(int) icvComputeCoeffForStereo( CvStereoCamera* stereoCamera); - -CVAPI(int) icvGetCrossPieceVector(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f v2_start,CvPoint2D32f v2_end,CvPoint2D32f *cross); -CVAPI(int) icvGetCrossLineDirect(CvPoint2D32f p1,CvPoint2D32f p2,float a,float b,float c,CvPoint2D32f* cross); -CVAPI(float) icvDefinePointPosition(CvPoint2D32f point1,CvPoint2D32f point2,CvPoint2D32f point); -CVAPI(int) icvStereoCalibration( int numImages, - int* nums, - CvSize imageSize, - CvPoint2D32f* imagePoints1, - CvPoint2D32f* imagePoints2, - CvPoint3D32f* objectPoints, - CvStereoCamera* stereoparams - ); - - -CVAPI(int) icvComputeRestStereoParams(CvStereoCamera *stereoparams); - -CVAPI(void) cvComputePerspectiveMap( const double coeffs[3][3], CvArr* rectMapX, CvArr* rectMapY ); - -CVAPI(int) icvComCoeffForLine( CvPoint2D64f point1, - CvPoint2D64f point2, - CvPoint2D64f point3, - CvPoint2D64f point4, - double* camMatr1, - double* rotMatr1, - double* transVect1, - double* camMatr2, - double* rotMatr2, - double* transVect2, - CvStereoLineCoeff* coeffs, - int* needSwapCameras); - -CVAPI(int) icvGetDirectionForPoint( CvPoint2D64f point, - double* camMatr, - CvPoint3D64f* direct); - -CVAPI(int) icvGetCrossLines(CvPoint3D64f point11,CvPoint3D64f point12, - CvPoint3D64f point21,CvPoint3D64f point22, - CvPoint3D64f* midPoint); - -CVAPI(int) icvComputeStereoLineCoeffs( CvPoint3D64f pointA, - CvPoint3D64f pointB, - CvPoint3D64f pointCam1, - double gamma, - CvStereoLineCoeff* coeffs); - -/*CVAPI(int) icvComputeFundMatrEpipoles ( double* camMatr1, - double* rotMatr1, - double* transVect1, - double* camMatr2, - double* rotMatr2, - double* transVect2, - CvPoint2D64f* epipole1, - CvPoint2D64f* epipole2, - double* fundMatr);*/ - -CVAPI(int) icvGetAngleLine( CvPoint2D64f startPoint, CvSize imageSize,CvPoint2D64f *point1,CvPoint2D64f *point2); - -CVAPI(void) icvGetCoefForPiece( CvPoint2D64f p_start,CvPoint2D64f p_end, - double *a,double *b,double *c, - int* result); - -/*CVAPI(void) icvGetCommonArea( CvSize imageSize, - CvPoint2D64f epipole1,CvPoint2D64f epipole2, - double* fundMatr, - double* coeff11,double* coeff12, - double* coeff21,double* coeff22, - int* result);*/ - -CVAPI(void) icvComputeeInfiniteProject1(double* rotMatr, - double* camMatr1, - double* camMatr2, - CvPoint2D32f point1, - CvPoint2D32f *point2); - -CVAPI(void) icvComputeeInfiniteProject2(double* rotMatr, - double* camMatr1, - double* camMatr2, - CvPoint2D32f* point1, - CvPoint2D32f point2); - -CVAPI(void) icvGetCrossDirectDirect( double* direct1,double* direct2, - CvPoint2D64f *cross,int* result); - -CVAPI(void) icvGetCrossPieceDirect( CvPoint2D64f p_start,CvPoint2D64f p_end, - double a,double b,double c, - CvPoint2D64f *cross,int* result); - -CVAPI(void) icvGetCrossPiecePiece( CvPoint2D64f p1_start,CvPoint2D64f p1_end, - CvPoint2D64f p2_start,CvPoint2D64f p2_end, - CvPoint2D64f* cross, - int* result); - -CVAPI(void) icvGetPieceLength(CvPoint2D64f point1,CvPoint2D64f point2,double* dist); - -CVAPI(void) icvGetCrossRectDirect( CvSize imageSize, - double a,double b,double c, - CvPoint2D64f *start,CvPoint2D64f *end, - int* result); - -CVAPI(void) icvProjectPointToImage( CvPoint3D64f point, - double* camMatr,double* rotMatr,double* transVect, - CvPoint2D64f* projPoint); - -CVAPI(void) icvGetQuadsTransform( CvSize imageSize, - double* camMatr1, - double* rotMatr1, - double* transVect1, - double* camMatr2, - double* rotMatr2, - double* transVect2, - CvSize* warpSize, - double quad1[4][2], - double quad2[4][2], - double* fundMatr, - CvPoint3D64f* epipole1, - CvPoint3D64f* epipole2 - ); - -CVAPI(void) icvGetQuadsTransformStruct( CvStereoCamera* stereoCamera); - -CVAPI(void) icvComputeStereoParamsForCameras(CvStereoCamera* stereoCamera); - -CVAPI(void) icvGetCutPiece( double* areaLineCoef1,double* areaLineCoef2, - CvPoint2D64f epipole, - CvSize imageSize, - CvPoint2D64f* point11,CvPoint2D64f* point12, - CvPoint2D64f* point21,CvPoint2D64f* point22, - int* result); - -CVAPI(void) icvGetMiddleAnglePoint( CvPoint2D64f basePoint, - CvPoint2D64f point1,CvPoint2D64f point2, - CvPoint2D64f* midPoint); - -CVAPI(void) icvGetNormalDirect(double* direct,CvPoint2D64f point,double* normDirect); - -CVAPI(double) icvGetVect(CvPoint2D64f basePoint,CvPoint2D64f point1,CvPoint2D64f point2); - -CVAPI(void) icvProjectPointToDirect( CvPoint2D64f point,double* lineCoeff, - CvPoint2D64f* projectPoint); - -CVAPI(void) icvGetDistanceFromPointToDirect( CvPoint2D64f point,double* lineCoef,double*dist); - -CVAPI(IplImage*) icvCreateIsometricImage( IplImage* src, IplImage* dst, - int desired_depth, int desired_num_channels ); - -CVAPI(void) cvDeInterlace( const CvArr* frame, CvArr* fieldEven, CvArr* fieldOdd ); - -/*CVAPI(int) icvSelectBestRt( int numImages, - int* numPoints, - CvSize imageSize, - CvPoint2D32f* imagePoints1, - CvPoint2D32f* imagePoints2, - CvPoint3D32f* objectPoints, - - CvMatr32f cameraMatrix1, - CvVect32f distortion1, - CvMatr32f rotMatrs1, - CvVect32f transVects1, - - CvMatr32f cameraMatrix2, - CvVect32f distortion2, - CvMatr32f rotMatrs2, - CvVect32f transVects2, - - CvMatr32f bestRotMatr, - CvVect32f bestTransVect - );*/ - - -/****************************************************************************************\ -* Contour Tree * -\****************************************************************************************/ - -/* Contour tree header */ -typedef struct CvContourTree -{ - CV_SEQUENCE_FIELDS() - CvPoint p1; /* the first point of the binary tree root segment */ - CvPoint p2; /* the last point of the binary tree root segment */ -} CvContourTree; - -/* Builds hierarhical representation of a contour */ -CVAPI(CvContourTree*) cvCreateContourTree( const CvSeq* contour, - CvMemStorage* storage, - double threshold ); - -/* Reconstruct (completelly or partially) contour a from contour tree */ -CVAPI(CvSeq*) cvContourFromContourTree( const CvContourTree* tree, - CvMemStorage* storage, - CvTermCriteria criteria ); - -/* Compares two contour trees */ -enum { CV_CONTOUR_TREES_MATCH_I1 = 1 }; - -CVAPI(double) cvMatchContourTrees( const CvContourTree* tree1, - const CvContourTree* tree2, - int method, double threshold ); - -/****************************************************************************************\ -* Contour Morphing * -\****************************************************************************************/ - -/* finds correspondence between two contours */ -CvSeq* cvCalcContoursCorrespondence( const CvSeq* contour1, - const CvSeq* contour2, - CvMemStorage* storage); - -/* morphs contours using the pre-calculated correspondence: - alpha=0 ~ contour1, alpha=1 ~ contour2 */ -CvSeq* cvMorphContours( const CvSeq* contour1, const CvSeq* contour2, - CvSeq* corr, double alpha, - CvMemStorage* storage ); - - -/****************************************************************************************\ -* Active Contours * -\****************************************************************************************/ - -#define CV_VALUE 1 -#define CV_ARRAY 2 -/* Updates active contour in order to minimize its cummulative - (internal and external) energy. */ -CVAPI(void) cvSnakeImage( const IplImage* image, CvPoint* points, - int length, float* alpha, - float* beta, float* gamma, - int coeff_usage, CvSize win, - CvTermCriteria criteria, int calc_gradient CV_DEFAULT(1)); - -/****************************************************************************************\ -* Texture Descriptors * -\****************************************************************************************/ - -#define CV_GLCM_OPTIMIZATION_NONE -2 -#define CV_GLCM_OPTIMIZATION_LUT -1 -#define CV_GLCM_OPTIMIZATION_HISTOGRAM 0 - -#define CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST 10 -#define CV_GLCMDESC_OPTIMIZATION_ALLOWTRIPLENEST 11 -#define CV_GLCMDESC_OPTIMIZATION_HISTOGRAM 4 - -#define CV_GLCMDESC_ENTROPY 0 -#define CV_GLCMDESC_ENERGY 1 -#define CV_GLCMDESC_HOMOGENITY 2 -#define CV_GLCMDESC_CONTRAST 3 -#define CV_GLCMDESC_CLUSTERTENDENCY 4 -#define CV_GLCMDESC_CLUSTERSHADE 5 -#define CV_GLCMDESC_CORRELATION 6 -#define CV_GLCMDESC_CORRELATIONINFO1 7 -#define CV_GLCMDESC_CORRELATIONINFO2 8 -#define CV_GLCMDESC_MAXIMUMPROBABILITY 9 - -#define CV_GLCM_ALL 0 -#define CV_GLCM_GLCM 1 -#define CV_GLCM_DESC 2 - -typedef struct CvGLCM CvGLCM; - -CVAPI(CvGLCM*) cvCreateGLCM( const IplImage* srcImage, - int stepMagnitude, - const int* stepDirections CV_DEFAULT(0), - int numStepDirections CV_DEFAULT(0), - int optimizationType CV_DEFAULT(CV_GLCM_OPTIMIZATION_NONE)); - -CVAPI(void) cvReleaseGLCM( CvGLCM** GLCM, int flag CV_DEFAULT(CV_GLCM_ALL)); - -CVAPI(void) cvCreateGLCMDescriptors( CvGLCM* destGLCM, - int descriptorOptimizationType - CV_DEFAULT(CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST)); - -CVAPI(double) cvGetGLCMDescriptor( CvGLCM* GLCM, int step, int descriptor ); - -CVAPI(void) cvGetGLCMDescriptorStatistics( CvGLCM* GLCM, int descriptor, - double* average, double* standardDeviation ); - -CVAPI(IplImage*) cvCreateGLCMImage( CvGLCM* GLCM, int step ); - -/****************************************************************************************\ -* Face eyes&mouth tracking * -\****************************************************************************************/ - - -typedef struct CvFaceTracker CvFaceTracker; - -#define CV_NUM_FACE_ELEMENTS 3 -enum CV_FACE_ELEMENTS -{ - CV_FACE_MOUTH = 0, - CV_FACE_LEFT_EYE = 1, - CV_FACE_RIGHT_EYE = 2 -}; - -CVAPI(CvFaceTracker*) cvInitFaceTracker(CvFaceTracker* pFaceTracking, const IplImage* imgGray, - CvRect* pRects, int nRects); -CVAPI(int) cvTrackFace( CvFaceTracker* pFaceTracker, IplImage* imgGray, - CvRect* pRects, int nRects, - CvPoint* ptRotate, double* dbAngleRotate); -CVAPI(void) cvReleaseFaceTracker(CvFaceTracker** ppFaceTracker); - - -typedef struct CvFace -{ - CvRect MouthRect; - CvRect LeftEyeRect; - CvRect RightEyeRect; -} CvFaceData; - -CvSeq * cvFindFace(IplImage * Image,CvMemStorage* storage); -CvSeq * cvPostBoostingFindFace(IplImage * Image,CvMemStorage* storage); - - -/****************************************************************************************\ -* 3D Tracker * -\****************************************************************************************/ - -typedef unsigned char CvBool; - -typedef struct -{ - int id; - CvPoint2D32f p; // pgruebele: So we do not loose precision, this needs to be float -} Cv3dTracker2dTrackedObject; - -CV_INLINE Cv3dTracker2dTrackedObject cv3dTracker2dTrackedObject(int id, CvPoint2D32f p) -{ - Cv3dTracker2dTrackedObject r; - r.id = id; - r.p = p; - return r; -} - -typedef struct -{ - int id; - CvPoint3D32f p; // location of the tracked object -} Cv3dTrackerTrackedObject; - -CV_INLINE Cv3dTrackerTrackedObject cv3dTrackerTrackedObject(int id, CvPoint3D32f p) -{ - Cv3dTrackerTrackedObject r; - r.id = id; - r.p = p; - return r; -} - -typedef struct -{ - CvBool valid; - float mat[4][4]; /* maps camera coordinates to world coordinates */ - CvPoint2D32f principal_point; /* copied from intrinsics so this structure */ - /* has all the info we need */ -} Cv3dTrackerCameraInfo; - -typedef struct -{ - CvPoint2D32f principal_point; - float focal_length[2]; - float distortion[4]; -} Cv3dTrackerCameraIntrinsics; - -CVAPI(CvBool) cv3dTrackerCalibrateCameras(int num_cameras, - const Cv3dTrackerCameraIntrinsics camera_intrinsics[], /* size is num_cameras */ - CvSize etalon_size, - float square_size, - IplImage *samples[], /* size is num_cameras */ - Cv3dTrackerCameraInfo camera_info[]); /* size is num_cameras */ - -CVAPI(int) cv3dTrackerLocateObjects(int num_cameras, int num_objects, - const Cv3dTrackerCameraInfo camera_info[], /* size is num_cameras */ - const Cv3dTracker2dTrackedObject tracking_info[], /* size is num_objects*num_cameras */ - Cv3dTrackerTrackedObject tracked_objects[]); /* size is num_objects */ -/**************************************************************************************** - tracking_info is a rectangular array; one row per camera, num_objects elements per row. - The id field of any unused slots must be -1. Ids need not be ordered or consecutive. On - completion, the return value is the number of objects located; i.e., the number of objects - visible by more than one camera. The id field of any unused slots in tracked objects is - set to -1. -****************************************************************************************/ - - -/****************************************************************************************\ -* Skeletons and Linear-Contour Models * -\****************************************************************************************/ - -typedef enum CvLeeParameters -{ - CV_LEE_INT = 0, - CV_LEE_FLOAT = 1, - CV_LEE_DOUBLE = 2, - CV_LEE_AUTO = -1, - CV_LEE_ERODE = 0, - CV_LEE_ZOOM = 1, - CV_LEE_NON = 2 -} CvLeeParameters; - -#define CV_NEXT_VORONOISITE2D( SITE ) ((SITE)->edge[0]->site[((SITE)->edge[0]->site[0] == (SITE))]) -#define CV_PREV_VORONOISITE2D( SITE ) ((SITE)->edge[1]->site[((SITE)->edge[1]->site[0] == (SITE))]) -#define CV_FIRST_VORONOIEDGE2D( SITE ) ((SITE)->edge[0]) -#define CV_LAST_VORONOIEDGE2D( SITE ) ((SITE)->edge[1]) -#define CV_NEXT_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[(EDGE)->site[0] != (SITE)]) -#define CV_PREV_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[2 + ((EDGE)->site[0] != (SITE))]) -#define CV_VORONOIEDGE2D_BEGINNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] != (SITE))]) -#define CV_VORONOIEDGE2D_ENDNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] == (SITE))]) -#define CV_TWIN_VORONOISITE2D( SITE, EDGE ) ( (EDGE)->site[((EDGE)->site[0] == (SITE))]) - -#define CV_VORONOISITE2D_FIELDS() \ - struct CvVoronoiNode2D *node[2]; \ - struct CvVoronoiEdge2D *edge[2]; - -typedef struct CvVoronoiSite2D -{ - CV_VORONOISITE2D_FIELDS() - struct CvVoronoiSite2D *next[2]; -} CvVoronoiSite2D; - -#define CV_VORONOIEDGE2D_FIELDS() \ - struct CvVoronoiNode2D *node[2]; \ - struct CvVoronoiSite2D *site[2]; \ - struct CvVoronoiEdge2D *next[4]; - -typedef struct CvVoronoiEdge2D -{ - CV_VORONOIEDGE2D_FIELDS() -} CvVoronoiEdge2D; - -#define CV_VORONOINODE2D_FIELDS() \ - CV_SET_ELEM_FIELDS(CvVoronoiNode2D) \ - CvPoint2D32f pt; \ - float radius; - -typedef struct CvVoronoiNode2D -{ - CV_VORONOINODE2D_FIELDS() -} CvVoronoiNode2D; - -#define CV_VORONOIDIAGRAM2D_FIELDS() \ - CV_GRAPH_FIELDS() \ - CvSet *sites; - -typedef struct CvVoronoiDiagram2D -{ - CV_VORONOIDIAGRAM2D_FIELDS() -} CvVoronoiDiagram2D; - -/* Computes Voronoi Diagram for given polygons with holes */ -CVAPI(int) cvVoronoiDiagramFromContour(CvSeq* ContourSeq, - CvVoronoiDiagram2D** VoronoiDiagram, - CvMemStorage* VoronoiStorage, - CvLeeParameters contour_type CV_DEFAULT(CV_LEE_INT), - int contour_orientation CV_DEFAULT(-1), - int attempt_number CV_DEFAULT(10)); - -/* Computes Voronoi Diagram for domains in given image */ -CVAPI(int) cvVoronoiDiagramFromImage(IplImage* pImage, - CvSeq** ContourSeq, - CvVoronoiDiagram2D** VoronoiDiagram, - CvMemStorage* VoronoiStorage, - CvLeeParameters regularization_method CV_DEFAULT(CV_LEE_NON), - float approx_precision CV_DEFAULT(CV_LEE_AUTO)); - -/* Deallocates the storage */ -CVAPI(void) cvReleaseVoronoiStorage(CvVoronoiDiagram2D* VoronoiDiagram, - CvMemStorage** pVoronoiStorage); - -/*********************** Linear-Contour Model ****************************/ - -struct CvLCMEdge; -struct CvLCMNode; - -typedef struct CvLCMEdge -{ - CV_GRAPH_EDGE_FIELDS() - CvSeq* chain; - float width; - int index1; - int index2; -} CvLCMEdge; - -typedef struct CvLCMNode -{ - CV_GRAPH_VERTEX_FIELDS() - CvContour* contour; -} CvLCMNode; - - -/* Computes hybrid model from Voronoi Diagram */ -CVAPI(CvGraph*) cvLinearContorModelFromVoronoiDiagram(CvVoronoiDiagram2D* VoronoiDiagram, - float maxWidth); - -/* Releases hybrid model storage */ -CVAPI(int) cvReleaseLinearContorModelStorage(CvGraph** Graph); - - -/* two stereo-related functions */ - -CVAPI(void) cvInitPerspectiveTransform( CvSize size, const CvPoint2D32f vertex[4], double matrix[3][3], - CvArr* rectMap ); - -/*CVAPI(void) cvInitStereoRectification( CvStereoCamera* params, - CvArr* rectMap1, CvArr* rectMap2, - int do_undistortion );*/ - -/*************************** View Morphing Functions ************************/ - -typedef struct CvMatrix3 -{ - float m[3][3]; -} CvMatrix3; - -/* The order of the function corresponds to the order they should appear in - the view morphing pipeline */ - -/* Finds ending points of scanlines on left and right images of stereo-pair */ -CVAPI(void) cvMakeScanlines( const CvMatrix3* matrix, CvSize img_size, - int* scanlines1, int* scanlines2, - int* lengths1, int* lengths2, - int* line_count ); - -/* Grab pixel values from scanlines and stores them sequentially - (some sort of perspective image transform) */ -CVAPI(void) cvPreWarpImage( int line_count, - IplImage* img, - uchar* dst, - int* dst_nums, - int* scanlines); - -/* Approximate each grabbed scanline by a sequence of runs - (lossy run-length compression) */ -CVAPI(void) cvFindRuns( int line_count, - uchar* prewarp1, - uchar* prewarp2, - int* line_lengths1, - int* line_lengths2, - int* runs1, - int* runs2, - int* num_runs1, - int* num_runs2); - -/* Compares two sets of compressed scanlines */ -CVAPI(void) cvDynamicCorrespondMulti( int line_count, - int* first, - int* first_runs, - int* second, - int* second_runs, - int* first_corr, - int* second_corr); - -/* Finds scanline ending coordinates for some intermediate "virtual" camera position */ -CVAPI(void) cvMakeAlphaScanlines( int* scanlines1, - int* scanlines2, - int* scanlinesA, - int* lengths, - int line_count, - float alpha); - -/* Blends data of the left and right image scanlines to get - pixel values of "virtual" image scanlines */ -CVAPI(void) cvMorphEpilinesMulti( int line_count, - uchar* first_pix, - int* first_num, - uchar* second_pix, - int* second_num, - uchar* dst_pix, - int* dst_num, - float alpha, - int* first, - int* first_runs, - int* second, - int* second_runs, - int* first_corr, - int* second_corr); - -/* Does reverse warping of the morphing result to make - it fill the destination image rectangle */ -CVAPI(void) cvPostWarpImage( int line_count, - uchar* src, - int* src_nums, - IplImage* img, - int* scanlines); - -/* Deletes Moire (missed pixels that appear due to discretization) */ -CVAPI(void) cvDeleteMoire( IplImage* img ); - - -typedef struct CvConDensation -{ - int MP; - int DP; - float* DynamMatr; /* Matrix of the linear Dynamics system */ - float* State; /* Vector of State */ - int SamplesNum; /* Number of the Samples */ - float** flSamples; /* arr of the Sample Vectors */ - float** flNewSamples; /* temporary array of the Sample Vectors */ - float* flConfidence; /* Confidence for each Sample */ - float* flCumulative; /* Cumulative confidence */ - float* Temp; /* Temporary vector */ - float* RandomSample; /* RandomVector to update sample set */ - struct CvRandState* RandS; /* Array of structures to generate random vectors */ -} CvConDensation; - -/* Creates ConDensation filter state */ -CVAPI(CvConDensation*) cvCreateConDensation( int dynam_params, - int measure_params, - int sample_count ); - -/* Releases ConDensation filter state */ -CVAPI(void) cvReleaseConDensation( CvConDensation** condens ); - -/* Updates ConDensation filter by time (predict future state of the system) */ -CVAPI(void) cvConDensUpdateByTime( CvConDensation* condens); - -/* Initializes ConDensation filter samples */ -CVAPI(void) cvConDensInitSampleSet( CvConDensation* condens, CvMat* lower_bound, CvMat* upper_bound ); - -CV_INLINE int iplWidth( const IplImage* img ) -{ - return !img ? 0 : !img->roi ? img->width : img->roi->width; -} - -CV_INLINE int iplHeight( const IplImage* img ) -{ - return !img ? 0 : !img->roi ? img->height : img->roi->height; -} - -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus - -/****************************************************************************************\ -* Calibration engine * -\****************************************************************************************/ - -typedef enum CvCalibEtalonType -{ - CV_CALIB_ETALON_USER = -1, - CV_CALIB_ETALON_CHESSBOARD = 0, - CV_CALIB_ETALON_CHECKERBOARD = CV_CALIB_ETALON_CHESSBOARD -} -CvCalibEtalonType; - -class CV_EXPORTS CvCalibFilter -{ -public: - /* Constructor & destructor */ - CvCalibFilter(); - virtual ~CvCalibFilter(); - - /* Sets etalon type - one for all cameras. - etalonParams is used in case of pre-defined etalons (such as chessboard). - Number of elements in etalonParams is determined by etalonType. - E.g., if etalon type is CV_ETALON_TYPE_CHESSBOARD then: - etalonParams[0] is number of squares per one side of etalon - etalonParams[1] is number of squares per another side of etalon - etalonParams[2] is linear size of squares in the board in arbitrary units. - pointCount & points are used in case of - CV_CALIB_ETALON_USER (user-defined) etalon. */ - virtual bool - SetEtalon( CvCalibEtalonType etalonType, double* etalonParams, - int pointCount = 0, CvPoint2D32f* points = 0 ); - - /* Retrieves etalon parameters/or and points */ - virtual CvCalibEtalonType - GetEtalon( int* paramCount = 0, const double** etalonParams = 0, - int* pointCount = 0, const CvPoint2D32f** etalonPoints = 0 ) const; - - /* Sets number of cameras calibrated simultaneously. It is equal to 1 initially */ - virtual void SetCameraCount( int cameraCount ); - - /* Retrieves number of cameras */ - int GetCameraCount() const { return cameraCount; } - - /* Starts cameras calibration */ - virtual bool SetFrames( int totalFrames ); - - /* Stops cameras calibration */ - virtual void Stop( bool calibrate = false ); - - /* Retrieves number of cameras */ - bool IsCalibrated() const { return isCalibrated; } - - /* Feeds another serie of snapshots (one per each camera) to filter. - Etalon points on these images are found automatically. - If the function can't locate points, it returns false */ - virtual bool FindEtalon( IplImage** imgs ); - - /* The same but takes matrices */ - virtual bool FindEtalon( CvMat** imgs ); - - /* Lower-level function for feeding filter with already found etalon points. - Array of point arrays for each camera is passed. */ - virtual bool Push( const CvPoint2D32f** points = 0 ); - - /* Returns total number of accepted frames and, optionally, - total number of frames to collect */ - virtual int GetFrameCount( int* framesTotal = 0 ) const; - - /* Retrieves camera parameters for specified camera. - If camera is not calibrated the function returns 0 */ - virtual const CvCamera* GetCameraParams( int idx = 0 ) const; - - virtual const CvStereoCamera* GetStereoParams() const; - - /* Sets camera parameters for all cameras */ - virtual bool SetCameraParams( CvCamera* params ); - - /* Saves all camera parameters to file */ - virtual bool SaveCameraParams( const char* filename ); - - /* Loads all camera parameters from file */ - virtual bool LoadCameraParams( const char* filename ); - - /* Undistorts images using camera parameters. Some of src pointers can be NULL. */ - virtual bool Undistort( IplImage** src, IplImage** dst ); - - /* Undistorts images using camera parameters. Some of src pointers can be NULL. */ - virtual bool Undistort( CvMat** src, CvMat** dst ); - - /* Returns array of etalon points detected/partally detected - on the latest frame for idx-th camera */ - virtual bool GetLatestPoints( int idx, CvPoint2D32f** pts, - int* count, bool* found ); - - /* Draw the latest detected/partially detected etalon */ - virtual void DrawPoints( IplImage** dst ); - - /* Draw the latest detected/partially detected etalon */ - virtual void DrawPoints( CvMat** dst ); - - virtual bool Rectify( IplImage** srcarr, IplImage** dstarr ); - virtual bool Rectify( CvMat** srcarr, CvMat** dstarr ); - -protected: - - enum { MAX_CAMERAS = 3 }; - - /* etalon data */ - CvCalibEtalonType etalonType; - int etalonParamCount; - double* etalonParams; - int etalonPointCount; - CvPoint2D32f* etalonPoints; - CvSize imgSize; - CvMat* grayImg; - CvMat* tempImg; - CvMemStorage* storage; - - /* camera data */ - int cameraCount; - CvCamera cameraParams[MAX_CAMERAS]; - CvStereoCamera stereo; - CvPoint2D32f* points[MAX_CAMERAS]; - CvMat* undistMap[MAX_CAMERAS][2]; - CvMat* undistImg; - int latestCounts[MAX_CAMERAS]; - CvPoint2D32f* latestPoints[MAX_CAMERAS]; - CvMat* rectMap[MAX_CAMERAS][2]; - - /* Added by Valery */ - //CvStereoCamera stereoParams; - - int maxPoints; - int framesTotal; - int framesAccepted; - bool isCalibrated; -}; - -#include -#include - -class CV_EXPORTS CvImage -{ -public: - CvImage() : image(0), refcount(0) {} - CvImage( CvSize size, int depth, int channels ) - { - image = cvCreateImage( size, depth, channels ); - refcount = image ? new int(1) : 0; - } - - CvImage( IplImage* img ) : image(img) - { - refcount = image ? new int(1) : 0; - } - - CvImage( const CvImage& img ) : image(img.image), refcount(img.refcount) - { - if( refcount ) ++(*refcount); - } - - CvImage( const char* filename, const char* imgname=0, int color=-1 ) : image(0), refcount(0) - { load( filename, imgname, color ); } - - CvImage( CvFileStorage* fs, const char* mapname, const char* imgname ) : image(0), refcount(0) - { read( fs, mapname, imgname ); } - - CvImage( CvFileStorage* fs, const char* seqname, int idx ) : image(0), refcount(0) - { read( fs, seqname, idx ); } - - ~CvImage() - { - if( refcount && !(--*refcount) ) - { - cvReleaseImage( &image ); - delete refcount; - } - } - - CvImage clone() { return CvImage(image ? cvCloneImage(image) : 0); } - - void create( CvSize size, int depth, int channels ) - { - if( !image || !refcount || - image->width != size.width || image->height != size.height || - image->depth != depth || image->nChannels != channels ) - attach( cvCreateImage( size, depth, channels )); - } - - void release() { detach(); } - void clear() { detach(); } - - void attach( IplImage* img, bool use_refcount=true ) - { - if( refcount && --*refcount == 0 ) - { - cvReleaseImage( &image ); - delete refcount; - } - image = img; - refcount = use_refcount && image ? new int(1) : 0; - } - - void detach() - { - if( refcount && --*refcount == 0 ) - { - cvReleaseImage( &image ); - delete refcount; - } - image = 0; - refcount = 0; - } - - bool load( const char* filename, const char* imgname=0, int color=-1 ); - bool read( CvFileStorage* fs, const char* mapname, const char* imgname ); - bool read( CvFileStorage* fs, const char* seqname, int idx ); - void save( const char* filename, const char* imgname, const int* params=0 ); - void write( CvFileStorage* fs, const char* imgname ); - - void show( const char* window_name ); - bool is_valid() { return image != 0; } - - int width() const { return image ? image->width : 0; } - int height() const { return image ? image->height : 0; } - - CvSize size() const { return image ? cvSize(image->width, image->height) : cvSize(0,0); } - - CvSize roi_size() const - { - return !image ? cvSize(0,0) : - !image->roi ? cvSize(image->width,image->height) : - cvSize(image->roi->width, image->roi->height); - } - - CvRect roi() const - { - return !image ? cvRect(0,0,0,0) : - !image->roi ? cvRect(0,0,image->width,image->height) : - cvRect(image->roi->xOffset,image->roi->yOffset, - image->roi->width,image->roi->height); - } - - int coi() const { return !image || !image->roi ? 0 : image->roi->coi; } - - void set_roi(CvRect roi) { cvSetImageROI(image,roi); } - void reset_roi() { cvResetImageROI(image); } - void set_coi(int coi) { cvSetImageCOI(image,coi); } - int depth() const { return image ? image->depth : 0; } - int channels() const { return image ? image->nChannels : 0; } - int pix_size() const { return image ? ((image->depth & 255)>>3)*image->nChannels : 0; } - - uchar* data() { return image ? (uchar*)image->imageData : 0; } - const uchar* data() const { return image ? (const uchar*)image->imageData : 0; } - int step() const { return image ? image->widthStep : 0; } - int origin() const { return image ? image->origin : 0; } - - uchar* roi_row(int y) - { - assert(0<=y); - assert(!image ? - 1 : image->roi ? - yroi->height : yheight); - - return !image ? 0 : - !image->roi ? - (uchar*)(image->imageData + y*image->widthStep) : - (uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep + - image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels); - } - - const uchar* roi_row(int y) const - { - assert(0<=y); - assert(!image ? - 1 : image->roi ? - yroi->height : yheight); - - return !image ? 0 : - !image->roi ? - (const uchar*)(image->imageData + y*image->widthStep) : - (const uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep + - image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels); - } - - operator const IplImage* () const { return image; } - operator IplImage* () { return image; } - - CvImage& operator = (const CvImage& img) - { - if( img.refcount ) - ++*img.refcount; - if( refcount && !(--*refcount) ) - cvReleaseImage( &image ); - image=img.image; - refcount=img.refcount; - return *this; - } - -protected: - IplImage* image; - int* refcount; -}; - - -class CV_EXPORTS CvMatrix -{ -public: - CvMatrix() : matrix(0) {} - CvMatrix( int rows, int cols, int type ) - { matrix = cvCreateMat( rows, cols, type ); } - - CvMatrix( int rows, int cols, int type, CvMat* hdr, - void* data=0, int step=CV_AUTOSTEP ) - { matrix = cvInitMatHeader( hdr, rows, cols, type, data, step ); } - - CvMatrix( int rows, int cols, int type, CvMemStorage* storage, bool alloc_data=true ); - - CvMatrix( int rows, int cols, int type, void* data, int step=CV_AUTOSTEP ) - { matrix = cvCreateMatHeader( rows, cols, type ); - cvSetData( matrix, data, step ); } - - CvMatrix( CvMat* m ) - { matrix = m; } - - CvMatrix( const CvMatrix& m ) - { - matrix = m.matrix; - addref(); - } - - CvMatrix( const char* filename, const char* matname=0, int color=-1 ) : matrix(0) - { load( filename, matname, color ); } - - CvMatrix( CvFileStorage* fs, const char* mapname, const char* matname ) : matrix(0) - { read( fs, mapname, matname ); } - - CvMatrix( CvFileStorage* fs, const char* seqname, int idx ) : matrix(0) - { read( fs, seqname, idx ); } - - ~CvMatrix() - { - release(); - } - - CvMatrix clone() { return CvMatrix(matrix ? cvCloneMat(matrix) : 0); } - - void set( CvMat* m, bool add_ref ) - { - release(); - matrix = m; - if( add_ref ) - addref(); - } - - void create( int rows, int cols, int type ) - { - if( !matrix || !matrix->refcount || - matrix->rows != rows || matrix->cols != cols || - CV_MAT_TYPE(matrix->type) != type ) - set( cvCreateMat( rows, cols, type ), false ); - } - - void addref() const - { - if( matrix ) - { - if( matrix->hdr_refcount ) - ++matrix->hdr_refcount; - else if( matrix->refcount ) - ++*matrix->refcount; - } - } - - void release() - { - if( matrix ) - { - if( matrix->hdr_refcount ) - { - if( --matrix->hdr_refcount == 0 ) - cvReleaseMat( &matrix ); - } - else if( matrix->refcount ) - { - if( --*matrix->refcount == 0 ) - cvFree( &matrix->refcount ); - } - matrix = 0; - } - } - - void clear() - { - release(); - } - - bool load( const char* filename, const char* matname=0, int color=-1 ); - bool read( CvFileStorage* fs, const char* mapname, const char* matname ); - bool read( CvFileStorage* fs, const char* seqname, int idx ); - void save( const char* filename, const char* matname, const int* params=0 ); - void write( CvFileStorage* fs, const char* matname ); - - void show( const char* window_name ); - - bool is_valid() { return matrix != 0; } - - int rows() const { return matrix ? matrix->rows : 0; } - int cols() const { return matrix ? matrix->cols : 0; } - - CvSize size() const - { - return !matrix ? cvSize(0,0) : cvSize(matrix->rows,matrix->cols); - } - - int type() const { return matrix ? CV_MAT_TYPE(matrix->type) : 0; } - int depth() const { return matrix ? CV_MAT_DEPTH(matrix->type) : 0; } - int channels() const { return matrix ? CV_MAT_CN(matrix->type) : 0; } - int pix_size() const { return matrix ? CV_ELEM_SIZE(matrix->type) : 0; } - - uchar* data() { return matrix ? matrix->data.ptr : 0; } - const uchar* data() const { return matrix ? matrix->data.ptr : 0; } - int step() const { return matrix ? matrix->step : 0; } - - void set_data( void* data, int step=CV_AUTOSTEP ) - { cvSetData( matrix, data, step ); } - - uchar* row(int i) { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; } - const uchar* row(int i) const - { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; } - - operator const CvMat* () const { return matrix; } - operator CvMat* () { return matrix; } - - CvMatrix& operator = (const CvMatrix& _m) - { - _m.addref(); - release(); - matrix = _m.matrix; - return *this; - } - -protected: - CvMat* matrix; -}; - -/****************************************************************************************\ - * CamShiftTracker * - \****************************************************************************************/ - -class CV_EXPORTS CvCamShiftTracker -{ -public: - - CvCamShiftTracker(); - virtual ~CvCamShiftTracker(); - - /**** Characteristics of the object that are calculated by track_object method *****/ - float get_orientation() const // orientation of the object in degrees - { return m_box.angle; } - float get_length() const // the larger linear size of the object - { return m_box.size.height; } - float get_width() const // the smaller linear size of the object - { return m_box.size.width; } - CvPoint2D32f get_center() const // center of the object - { return m_box.center; } - CvRect get_window() const // bounding rectangle for the object - { return m_comp.rect; } - - /*********************** Tracking parameters ************************/ - int get_threshold() const // thresholding value that applied to back project - { return m_threshold; } - - int get_hist_dims( int* dims = 0 ) const // returns number of histogram dimensions and sets - { return m_hist ? cvGetDims( m_hist->bins, dims ) : 0; } - - int get_min_ch_val( int channel ) const // get the minimum allowed value of the specified channel - { return m_min_ch_val[channel]; } - - int get_max_ch_val( int channel ) const // get the maximum allowed value of the specified channel - { return m_max_ch_val[channel]; } - - // set initial object rectangle (must be called before initial calculation of the histogram) - bool set_window( CvRect window) - { m_comp.rect = window; return true; } - - bool set_threshold( int threshold ) // threshold applied to the histogram bins - { m_threshold = threshold; return true; } - - bool set_hist_bin_range( int dim, int min_val, int max_val ); - - bool set_hist_dims( int c_dims, int* dims );// set the histogram parameters - - bool set_min_ch_val( int channel, int val ) // set the minimum allowed value of the specified channel - { m_min_ch_val[channel] = val; return true; } - bool set_max_ch_val( int channel, int val ) // set the maximum allowed value of the specified channel - { m_max_ch_val[channel] = val; return true; } - - /************************ The processing methods *********************************/ - // update object position - virtual bool track_object( const IplImage* cur_frame ); - - // update object histogram - virtual bool update_histogram( const IplImage* cur_frame ); - - // reset histogram - virtual void reset_histogram(); - - /************************ Retrieving internal data *******************************/ - // get back project image - virtual IplImage* get_back_project() - { return m_back_project; } - - float query( int* bin ) const - { return m_hist ? (float)cvGetRealND(m_hist->bins, bin) : 0.f; } - -protected: - - // internal method for color conversion: fills m_color_planes group - virtual void color_transform( const IplImage* img ); - - CvHistogram* m_hist; - - CvBox2D m_box; - CvConnectedComp m_comp; - - float m_hist_ranges_data[CV_MAX_DIM][2]; - float* m_hist_ranges[CV_MAX_DIM]; - - int m_min_ch_val[CV_MAX_DIM]; - int m_max_ch_val[CV_MAX_DIM]; - int m_threshold; - - IplImage* m_color_planes[CV_MAX_DIM]; - IplImage* m_back_project; - IplImage* m_temp; - IplImage* m_mask; -}; - -//#include "cvvidsurv.hpp" -#endif - -#endif - -/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/stitching/warpers_inl.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/stitching/warpers_inl.hpp deleted file mode 100755 index e925c63..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/stitching/warpers_inl.hpp +++ /dev/null @@ -1,304 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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 __OPENCV_STITCHING_WARPERS_INL_HPP__ -#define __OPENCV_STITCHING_WARPERS_INL_HPP__ - -#include "opencv2/core/core.hpp" -#include "warpers.hpp" // Make your IDE see declarations - -namespace cv { -namespace detail { - -template -Point2f RotationWarperBase

::warpPoint(const Point2f &pt, const Mat &K, const Mat &R) -{ - projector_.setCameraParams(K, R); - Point2f uv; - projector_.mapForward(pt.x, pt.y, uv.x, uv.y); - return uv; -} - - -template -Rect RotationWarperBase

::buildMaps(Size src_size, const Mat &K, const Mat &R, Mat &xmap, Mat &ymap) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - xmap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - ymap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - - float x, y; - for (int v = dst_tl.y; v <= dst_br.y; ++v) - { - for (int u = dst_tl.x; u <= dst_br.x; ++u) - { - projector_.mapBackward(static_cast(u), static_cast(v), x, y); - xmap.at(v - dst_tl.y, u - dst_tl.x) = x; - ymap.at(v - dst_tl.y, u - dst_tl.x) = y; - } - } - - return Rect(dst_tl, dst_br); -} - - -template -Point RotationWarperBase

::warp(const Mat &src, const Mat &K, const Mat &R, int interp_mode, int border_mode, - Mat &dst) -{ - Mat xmap, ymap; - Rect dst_roi = buildMaps(src.size(), K, R, xmap, ymap); - - dst.create(dst_roi.height + 1, dst_roi.width + 1, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); - - return dst_roi.tl(); -} - - -template -void RotationWarperBase

::warpBackward(const Mat &src, const Mat &K, const Mat &R, int interp_mode, int border_mode, - Size dst_size, Mat &dst) -{ - projector_.setCameraParams(K, R); - - Point src_tl, src_br; - detectResultRoi(dst_size, src_tl, src_br); - CV_Assert(src_br.x - src_tl.x + 1 == src.cols && src_br.y - src_tl.y + 1 == src.rows); - - Mat xmap(dst_size, CV_32F); - Mat ymap(dst_size, CV_32F); - - float u, v; - for (int y = 0; y < dst_size.height; ++y) - { - for (int x = 0; x < dst_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - xmap.at(y, x) = u - src_tl.x; - ymap.at(y, x) = v - src_tl.y; - } - } - - dst.create(dst_size, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); -} - - -template -Rect RotationWarperBase

::warpRoi(Size src_size, const Mat &K, const Mat &R) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - return Rect(dst_tl, Point(dst_br.x + 1, dst_br.y + 1)); -} - - -template -void RotationWarperBase

::detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = std::numeric_limits::max(); - float tl_vf = std::numeric_limits::max(); - float br_uf = -std::numeric_limits::max(); - float br_vf = -std::numeric_limits::max(); - - float u, v; - for (int y = 0; y < src_size.height; ++y) - { - for (int x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - tl_uf = std::min(tl_uf, u); tl_vf = std::min(tl_vf, v); - br_uf = std::max(br_uf, u); br_vf = std::max(br_vf, v); - } - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -template -void RotationWarperBase

::detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = std::numeric_limits::max(); - float tl_vf = std::numeric_limits::max(); - float br_uf = -std::numeric_limits::max(); - float br_vf = -std::numeric_limits::max(); - - float u, v; - for (float x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), 0, u, v); - tl_uf = std::min(tl_uf, u); tl_vf = std::min(tl_vf, v); - br_uf = std::max(br_uf, u); br_vf = std::max(br_vf, v); - - projector_.mapForward(static_cast(x), static_cast(src_size.height - 1), u, v); - tl_uf = std::min(tl_uf, u); tl_vf = std::min(tl_vf, v); - br_uf = std::max(br_uf, u); br_vf = std::max(br_vf, v); - } - for (int y = 0; y < src_size.height; ++y) - { - projector_.mapForward(0, static_cast(y), u, v); - tl_uf = std::min(tl_uf, u); tl_vf = std::min(tl_vf, v); - br_uf = std::max(br_uf, u); br_vf = std::max(br_vf, v); - - projector_.mapForward(static_cast(src_size.width - 1), static_cast(y), u, v); - tl_uf = std::min(tl_uf, u); tl_vf = std::min(tl_vf, v); - br_uf = std::max(br_uf, u); br_vf = std::max(br_vf, v); - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -inline -void PlaneProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - x_ = t[0] + x_ / z_ * (1 - t[2]); - y_ = t[1] + y_ / z_ * (1 - t[2]); - - u = scale * x_; - v = scale * y_; -} - - -inline -void PlaneProjector::mapBackward(float u, float v, float &x, float &y) -{ - u = u / scale - t[0]; - v = v / scale - t[1]; - - float z; - x = k_rinv[0] * u + k_rinv[1] * v + k_rinv[2] * (1 - t[2]); - y = k_rinv[3] * u + k_rinv[4] * v + k_rinv[5] * (1 - t[2]); - z = k_rinv[6] * u + k_rinv[7] * v + k_rinv[8] * (1 - t[2]); - - x /= z; - y /= z; -} - - -inline -void SphericalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - v = scale * (static_cast(CV_PI) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))); -} - - -inline -void SphericalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float sinv = sinf(static_cast(CV_PI) - v); - float x_ = sinv * sinf(u); - float y_ = cosf(static_cast(CV_PI) - v); - float z_ = sinv * cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - - -inline -void CylindricalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); -} - - -inline -void CylindricalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float x_ = sinf(u); - float y_ = v; - float z_ = cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -} // namespace detail -} // namespace cv - -#endif // __OPENCV_STITCHING_WARPERS_INL_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts.hpp deleted file mode 100755 index c3603d2..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts.hpp +++ /dev/null @@ -1,561 +0,0 @@ -#ifndef __OPENCV_GTESTCV_HPP__ -#define __OPENCV_GTESTCV_HPP__ - -#if HAVE_CVCONFIG_H -#include "cvconfig.h" -#endif -#ifndef GTEST_CREATE_SHARED_LIBRARY -#ifdef BUILD_SHARED_LIBS -#define GTEST_LINKED_AS_SHARED_LIBRARY 1 -#endif -#endif - -#ifdef ANDROID -# include -# define GTEST_HAS_CLONE (__ANDROID_API__ > 7) -# define GTEST_HAS_POSIX_RE (__ANDROID_API__ > 7) -# define GTEST_HAS_STD_WSTRING _GLIBCXX_USE_WCHAR_T -#endif - -#include // for va_list - -#if _MSC_VER >= 1200 -#pragma warning( disable: 4251 4275 4355 4127 ) -#endif - -#include "opencv2/ts/ts_gtest.h" -#include "opencv2/core/core.hpp" - -namespace cvtest -{ - -using std::vector; -using std::string; -using cv::RNG; -using cv::Mat; -using cv::Scalar; -using cv::Size; -using cv::Point; -using cv::Rect; - -class CV_EXPORTS TS; - -CV_EXPORTS int64 readSeed(const char* str); - -CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 ); - -inline unsigned randInt( RNG& rng ) -{ - return (unsigned)rng; -} - -inline double randReal( RNG& rng ) -{ - return (double)rng; -} - - -CV_EXPORTS const char* getTypeName( int type ); -CV_EXPORTS int typeByName( const char* type_name ); - -CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems); - -inline int clipInt( int val, int min_val, int max_val ) -{ - if( val < min_val ) - val = min_val; - if( val > max_val ) - val = max_val; - return val; -} - -CV_EXPORTS double getMinVal(int depth); -CV_EXPORTS double getMaxVal(int depth); - -CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog); -CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector& sz); -CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels); -CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi); -CV_EXPORTS Mat randomMat(RNG& rng, const vector& size, int type, double minVal, double maxVal, bool useRoi); -CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta, - Scalar gamma, Mat& c, int ctype, bool calcAbs=false); -CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1); -CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1); - -CV_EXPORTS void convert(const Mat& src, Mat& dst, int dtype, double alpha=1, double beta=0); -CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false); -CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat()); - -// working with multi-channel arrays -CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi ); -CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi ); - -// checks that the array does not have NaNs and/or Infs and all the elements are -// within [min_val,max_val). idx is the index of the first "bad" element. -CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector* idx ); - -// modifies values that are close to zero -CV_EXPORTS void patchZeros( Mat& mat, double level ); - -CV_EXPORTS void transpose(const Mat& src, Mat& dst); -CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1), - int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar()); -CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1), - int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar()); -CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel, - Point anchor, double delta, int borderType, - const Scalar& borderValue=Scalar()); -CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right, - int borderType, const Scalar& borderValue=Scalar()); -CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 ); -CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size ); - -CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy ); - -CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval, - vector* minloc, vector* maxloc, const Mat& mask=Mat()); -CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat()); -CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat()); -CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat()); - -CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector* idx); - -// compares two arrays. max_diff is the maximum actual difference, -// success_err_level is maximum allowed difference, idx is the index of the first -// element for which difference is >success_err_level -// (or index of element with the maximum difference) -CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff, - double success_err_level, vector* idx, - bool element_wise_relative_error ); - -// a wrapper for the previous function. in case of error prints the message to log file. -CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level, - bool element_wise_relative_error, const char* desc ); - -CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len, - double eps, const char* param_name ); - -CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c); -CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c); -CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); -CV_EXPORTS void min(const Mat& src, double s, Mat& dst); -CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); -CV_EXPORTS void max(const Mat& src, double s, Mat& dst); - -CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop); -CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop); -CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha, - const Mat& src3, double beta, Mat& dst, int flags); - CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift ); -CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2); - -struct CV_EXPORTS MatInfo -{ - MatInfo(const Mat& _m) : m(&_m) {} - const Mat* m; -}; - -CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m); - -struct CV_EXPORTS MatComparator -{ -public: - MatComparator(double maxdiff, int context); - - ::testing::AssertionResult operator()(const char* expr1, const char* expr2, - const Mat& m1, const Mat& m2); - - double maxdiff; - double realmaxdiff; - vector loc0; - int context; -}; - - - -class BaseTest; -class TS; - -class CV_EXPORTS BaseTest -{ -public: - // constructor(s) and destructor - BaseTest(); - virtual ~BaseTest(); - - // the main procedure of the test - virtual void run( int start_from ); - - // the wrapper for run that cares of exceptions - virtual void safe_run( int start_from=0 ); - - const string& get_name() const { return name; } - - // returns true if and only if the different test cases do not depend on each other - // (so that test system could get right to a problematic test case) - virtual bool can_do_fast_forward(); - - // deallocates all the memory. - // called by init() (before initialization) and by the destructor - virtual void clear(); - -protected: - int test_case_count; // the total number of test cases - - // read test params - virtual int read_params( CvFileStorage* fs ); - - // returns the number of tests or -1 if it is unknown a-priori - virtual int get_test_case_count(); - - // prepares data for the next test case. rng seed is updated by the function - virtual int prepare_test_case( int test_case_idx ); - - // checks if the test output is valid and accurate - virtual int validate_test_results( int test_case_idx ); - - // calls the tested function. the method is called from run_test_case() - virtual void run_func(); // runs tested func(s) - - // updates progress bar - virtual int update_progress( int progress, int test_case_idx, int count, double dt ); - - // finds test parameter - const CvFileNode* find_param( CvFileStorage* fs, const char* param_name ); - - // name of the test (it is possible to locate a test by its name) - string name; - - // pointer to the system that includes the test - TS* ts; -}; - - -/*****************************************************************************************\ -* Information about a failed test * -\*****************************************************************************************/ - -struct TestInfo -{ - TestInfo(); - - // pointer to the test - BaseTest* test; - - // failure code (CV_FAIL*) - int code; - - // seed value right before the data for the failed test case is prepared. - uint64 rng_seed; - - // seed value right before running the test - uint64 rng_seed0; - - // index of test case, can be then passed to BaseTest::proceed_to_test_case() - int test_case_idx; -}; - -/*****************************************************************************************\ -* Base Class for test system * -\*****************************************************************************************/ - -// common parameters: -struct CV_EXPORTS TSParams -{ - TSParams(); - - // RNG seed, passed to and updated by every test executed. - uint64 rng_seed; - - // whether to use IPP, MKL etc. or not - bool use_optimized; - - // extensivity of the tests, scale factor for test_case_count - double test_case_count_scale; -}; - - -class CV_EXPORTS TS -{ -public: - // constructor(s) and destructor - TS(); - virtual ~TS(); - - enum - { - NUL=0, - SUMMARY_IDX=0, - SUMMARY=1 << SUMMARY_IDX, - LOG_IDX=1, - LOG=1 << LOG_IDX, - CSV_IDX=2, - CSV=1 << CSV_IDX, - CONSOLE_IDX=3, - CONSOLE=1 << CONSOLE_IDX, - MAX_IDX=4 - }; - - static TS* ptr(); - - // initialize test system before running the first test - virtual void init( const string& modulename ); - - // low-level printing functions that are used by individual tests and by the system itself - virtual void printf( int streams, const char* fmt, ... ); - virtual void vprintf( int streams, const char* fmt, va_list arglist ); - - // updates the context: current test, test case, rng state - virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context ); - - const TestInfo* get_current_test_info() { return ¤t_test_info; } - - // sets information about a failed test - virtual void set_failed_test_info( int fail_code ); - - virtual void set_gtest_status(); - - // test error codes - enum - { - // everything is Ok - OK=0, - - // generic error: stub value to be used - // temporarily if the error's cause is unknown - FAIL_GENERIC=-1, - - // the test is missing some essential data to proceed further - FAIL_MISSING_TEST_DATA=-2, - - // the tested function raised an error via cxcore error handler - FAIL_ERROR_IN_CALLED_FUNC=-3, - - // an exception has been raised; - // for memory and arithmetic exception - // there are two specialized codes (see below...) - FAIL_EXCEPTION=-4, - - // a memory exception - // (access violation, access to missed page, stack overflow etc.) - FAIL_MEMORY_EXCEPTION=-5, - - // arithmetic exception (overflow, division by zero etc.) - FAIL_ARITHM_EXCEPTION=-6, - - // the tested function corrupted memory (no exception have been raised) - FAIL_MEMORY_CORRUPTION_BEGIN=-7, - FAIL_MEMORY_CORRUPTION_END=-8, - - // the tested function (or test ifself) do not deallocate some memory - FAIL_MEMORY_LEAK=-9, - - // the tested function returned invalid object, e.g. matrix, containing NaNs, - // structure with NULL or out-of-range fields (while it should not) - FAIL_INVALID_OUTPUT=-10, - - // the tested function returned valid object, but it does not match to - // the original (or produced by the test) object - FAIL_MISMATCH=-11, - - // the tested function returned valid object (a single number or numerical array), - // but it differs too much from the original (or produced by the test) object - FAIL_BAD_ACCURACY=-12, - - // the tested function hung. Sometimes, can be determined by unexpectedly long - // processing time (in this case there should be possibility to interrupt such a function - FAIL_HANG=-13, - - // unexpected responce on passing bad arguments to the tested function - // (the function crashed, proceed succesfully (while it should not), or returned - // error code that is different from what is expected) - FAIL_BAD_ARG_CHECK=-14, - - // the test data (in whole or for the particular test case) is invalid - FAIL_INVALID_TEST_DATA=-15, - - // the test has been skipped because it is not in the selected subset of the tests to run, - // because it has been run already within the same run with the same parameters, or because - // of some other reason and this is not considered as an error. - // Normally TS::run() (or overrided method in the derived class) takes care of what - // needs to be run, so this code should not occur. - SKIPPED=1 - }; - - // get file storage - CvFileStorage* get_file_storage(); - - // get RNG to generate random input data for a test - RNG& get_rng() { return rng; } - - // returns the current error code - int get_err_code() { return current_test_info.code; } - - // returns the test extensivity scale - double get_test_case_count_scale() { return params.test_case_count_scale; } - - const string& get_data_path() const { return data_path; } - - // returns textual description of failure code - static string str_from_code( int code ); - -protected: - - // these are allocated within a test to try keep them valid in case of stack corruption - RNG rng; - - // information about the current test - TestInfo current_test_info; - - // the path to data files used by tests - string data_path; - - TSParams params; - std::string output_buf[MAX_IDX]; -}; - - -/*****************************************************************************************\ -* Subclass of BaseTest for testing functions that process dense arrays * -\*****************************************************************************************/ - -class CV_EXPORTS ArrayTest : public BaseTest -{ -public: - // constructor(s) and destructor - ArrayTest(); - virtual ~ArrayTest(); - - virtual void clear(); - -protected: - - virtual int read_params( CvFileStorage* fs ); - virtual int prepare_test_case( int test_case_idx ); - virtual int validate_test_results( int test_case_idx ); - - virtual void prepare_to_validation( int test_case_idx ); - virtual void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - virtual void fill_array( int test_case_idx, int i, int j, Mat& arr ); - virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ); - virtual double get_success_error_level( int test_case_idx, int i, int j ); - - bool cvmat_allowed; - bool iplimage_allowed; - bool optional_mask; - bool element_wise_relative_error; - - int min_log_array_size; - int max_log_array_size; - - enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR }; - - vector > test_array; - vector > test_mat; - float buf[4]; -}; - - -class CV_EXPORTS BadArgTest : public BaseTest -{ -public: - // constructor(s) and destructor - BadArgTest(); - virtual ~BadArgTest(); - -protected: - virtual int run_test_case( int expected_code, const string& descr ); - virtual void run_func(void) = 0; - int test_case_idx; - int progress; - double t, freq; - - template - int run_test_case( int expected_code, const string& _descr, F f) - { - double new_t = (double)cv::getTickCount(), dt; - if( test_case_idx < 0 ) - { - test_case_idx = 0; - progress = 0; - dt = 0; - } - else - { - dt = (new_t - t)/(freq*1000); - t = new_t; - } - progress = update_progress(progress, test_case_idx, 0, dt); - - int errcount = 0; - bool thrown = false; - const char* descr = _descr.c_str() ? _descr.c_str() : ""; - - try - { - f(); - } - catch(const cv::Exception& e) - { - thrown = true; - if( e.code != expected_code ) - { - ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n", - descr, test_case_idx, e.code, expected_code); - errcount = 1; - } - } - catch(...) - { - thrown = true; - ts->printf(TS::LOG, "%s (test case #%d): unknown exception was thrown (the function has likely crashed)\n", - descr, test_case_idx); - errcount = 1; - } - if(!thrown) - { - ts->printf(TS::LOG, "%s (test case #%d): no expected exception was thrown\n", - descr, test_case_idx); - errcount = 1; - } - test_case_idx++; - - return errcount; - } -}; - -struct CV_EXPORTS DefaultRngAuto -{ - const uint64 old_state; - - DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; } - ~DefaultRngAuto() { cv::theRNG().state = old_state; } - - DefaultRngAuto& operator=(const DefaultRngAuto&); -}; - -} - -// fills c with zeros -CV_EXPORTS void cvTsZero( CvMat* c, const CvMat* mask=0 ); - -// copies a to b (whole matrix or only the selected region) -CV_EXPORTS void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask=0 ); - -// converts one array to another -CV_EXPORTS void cvTsConvert( const CvMat* src, CvMat* dst ); - -CV_EXPORTS void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha, - const CvMat* c, double beta, CvMat* d, int flags ); - -#define CV_TEST_MAIN(resourcesubdir) \ -int main(int argc, char **argv) \ -{ \ - cvtest::TS::ptr()->init(resourcesubdir); \ - ::testing::InitGoogleTest(&argc, argv); \ - return RUN_ALL_TESTS(); \ -} - -#endif - -#include "ts_perf.hpp" diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_gtest.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_gtest.h deleted file mode 100755 index 4d49fdc..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_gtest.h +++ /dev/null @@ -1,19545 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the public API for Google Test. It should be -// included by any test program that uses Google Test. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! -// -// Acknowledgment: Google Test borrowed the idea of automatic test -// registration from Barthelemy Dagenais' (barthelemy@prologique.com) -// easyUnit framework. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_H_ - -#include -#include - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file declares functions and macros used internally by -// Google Test. They are subject to change without notice. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan) -// -// Low-level types and utilities for porting Google Test to various -// platforms. They are subject to change without notice. DO NOT USE -// THEM IN USER CODE. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -// The user can define the following macros in the build script to -// control Google Test's behavior. If the user doesn't define a macro -// in this list, Google Test will define it. -// -// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) -// is/isn't available. -// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions -// are enabled. -// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string -// is/isn't available (some systems define -// ::string, which is different to std::string). -// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string -// is/isn't available (some systems define -// ::wstring, which is different to std::wstring). -// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular -// expressions are/aren't available. -// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that -// is/isn't available. -// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't -// enabled. -// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that -// std::wstring does/doesn't work (Google Test can -// be used where std::wstring is unavailable). -// GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple -// is/isn't available. -// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the -// compiler supports Microsoft's "Structured -// Exception Handling". -// GTEST_HAS_STREAM_REDIRECTION -// - Define it to 1/0 to indicate whether the -// platform supports I/O stream redirection using -// dup() and dup2(). -// GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google -// Test's own tr1 tuple implementation should be -// used. Unused when the user sets -// GTEST_HAS_TR1_TUPLE to 0. -// GTEST_LINKED_AS_SHARED_LIBRARY -// - Define to 1 when compiling tests that use -// Google Test as a shared library (known as -// DLL on Windows). -// GTEST_CREATE_SHARED_LIBRARY -// - Define to 1 when compiling Google Test itself -// as a shared library. - -// This header defines the following utilities: -// -// Macros indicating the current platform (defined to 1 if compiled on -// the given platform; otherwise undefined): -// GTEST_OS_AIX - IBM AIX -// GTEST_OS_CYGWIN - Cygwin -// GTEST_OS_HPUX - HP-UX -// GTEST_OS_LINUX - Linux -// GTEST_OS_LINUX_ANDROID - Google Android -// GTEST_OS_MAC - Mac OS X -// GTEST_OS_NACL - Google Native Client (NaCl) -// GTEST_OS_SOLARIS - Sun Solaris -// GTEST_OS_SYMBIAN - Symbian -// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) -// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop -// GTEST_OS_WINDOWS_MINGW - MinGW -// GTEST_OS_WINDOWS_MOBILE - Windows Mobile -// GTEST_OS_ZOS - z/OS -// -// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the -// most stable support. Since core members of the Google Test project -// don't have access to other platforms, support for them may be less -// stable. If you notice any problems on your platform, please notify -// googletestframework@googlegroups.com (patches for fixing them are -// even more welcome!). -// -// Note that it is possible that none of the GTEST_OS_* macros are defined. -// -// Macros indicating available Google Test features (defined to 1 if -// the corresponding feature is supported; otherwise undefined): -// GTEST_HAS_COMBINE - the Combine() function (for value-parameterized -// tests) -// GTEST_HAS_DEATH_TEST - death tests -// GTEST_HAS_PARAM_TEST - value-parameterized tests -// GTEST_HAS_TYPED_TEST - typed tests -// GTEST_HAS_TYPED_TEST_P - type-parameterized tests -// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with -// GTEST_HAS_POSIX_RE (see above) which users can -// define themselves. -// GTEST_USES_SIMPLE_RE - our own simple regex is used; -// the above two are mutually exclusive. -// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). -// -// Macros for basic C++ coding: -// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. -// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a -// variable don't have to be used. -// GTEST_DISALLOW_ASSIGN_ - disables operator=. -// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. -// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. -// -// Synchronization: -// Mutex, MutexLock, ThreadLocal, GetThreadCount() -// - synchronization primitives. -// GTEST_IS_THREADSAFE - defined to 1 to indicate that the above -// synchronization primitives have real implementations -// and Google Test is thread-safe; or 0 otherwise. -// -// Template meta programming: -// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. -// IteratorTraits - partial implementation of std::iterator_traits, which -// is not available in libCstd when compiled with Sun C++. -// -// Smart pointers: -// scoped_ptr - as in TR2. -// -// Regular expressions: -// RE - a simple regular expression class using the POSIX -// Extended Regular Expression syntax on UNIX-like -// platforms, or a reduced regular exception syntax on -// other platforms, including Windows. -// -// Logging: -// GTEST_LOG_() - logs messages at the specified severity level. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. -// -// Stdout and stderr capturing: -// CaptureStdout() - starts capturing stdout. -// GetCapturedStdout() - stops capturing stdout and returns the captured -// string. -// CaptureStderr() - starts capturing stderr. -// GetCapturedStderr() - stops capturing stderr and returns the captured -// string. -// -// Integer types: -// TypeWithSize - maps an integer to a int type. -// Int32, UInt32, Int64, UInt64, TimeInMillis -// - integers of known sizes. -// BiggestInt - the biggest signed integer type. -// -// Command-line utilities: -// GTEST_FLAG() - references a flag. -// GTEST_DECLARE_*() - declares a flag. -// GTEST_DEFINE_*() - defines a flag. -// GetArgvs() - returns the command line as a vector of strings. -// -// Environment variable utilities: -// GetEnv() - gets the value of an environment variable. -// BoolFromGTestEnv() - parses a bool environment variable. -// Int32FromGTestEnv() - parses an Int32 environment variable. -// StringFromGTestEnv() - parses a string environment variable. - -#include // for isspace, etc -#include // for ptrdiff_t -#include -#include -#include -#ifndef _WIN32_WCE -# include -# include -#endif // !_WIN32_WCE - -#include // NOLINT -#include // NOLINT -#include // NOLINT - -#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -#define GTEST_FLAG_PREFIX_ "gtest_" -#define GTEST_FLAG_PREFIX_DASH_ "gtest-" -#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -#define GTEST_NAME_ "Google Test" -#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" - -// Determines the version of gcc that is used to compile this. -#ifdef __GNUC__ -// 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) -#endif // __GNUC__ - -// Determines the platform on which Google Test is compiled. -#ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 -#elif defined __SYMBIAN32__ -# define GTEST_OS_SYMBIAN 1 -#elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(__MINGW__) || defined(__MINGW32__) -# define GTEST_OS_WINDOWS_MINGW 1 -# else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE -#elif defined __APPLE__ -# define GTEST_OS_MAC 1 -# include -# if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -# define GTEST_OS_MAC_IOS 1 -# endif -#include -#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -#define GTEST_OS_MAC_IOS 1 -#endif -#elif defined __linux__ -# define GTEST_OS_LINUX 1 -# ifdef ANDROID -# define GTEST_OS_LINUX_ANDROID 1 -# endif // ANDROID -#elif defined __MVS__ -# define GTEST_OS_ZOS 1 -#elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 -#elif defined(_AIX) -# define GTEST_OS_AIX 1 -#elif defined(__hpux) -# define GTEST_OS_HPUX 1 -#elif defined __native_client__ -# define GTEST_OS_NACL 1 -#endif // __CYGWIN__ - -// Brings in definitions for functions used in the testing::internal::posix -// namespace (read, write, close, chdir, isatty, stat). We do not currently -// use them on Windows Mobile. -#if !GTEST_OS_WINDOWS -// This assumes that non-Windows OSes provide unistd.h. For OSes where this -// is not the case, we need to include headers that provide the functions -// mentioned above. -# include -# if !GTEST_OS_NACL -// TODO(vladl@google.com): Remove this condition when Native Client SDK adds -// strings.h (tracked in -// http://code.google.com/p/nativeclient/issues/detail?id=1175). -# include // Native Client doesn't provide strings.h. -# endif -#elif !GTEST_OS_WINDOWS_MOBILE -# include -# include -#endif - -// Defines this to true iff Google Test can use POSIX regular expressions. -#ifndef GTEST_HAS_POSIX_RE -# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) -#endif - -#if GTEST_HAS_POSIX_RE - -// On some platforms, needs someone to define size_t, and -// won't compile otherwise. We can #include it here as we already -// included , which is guaranteed to define size_t through -// . -# include // NOLINT - -# define GTEST_USES_POSIX_RE 1 - -#elif GTEST_OS_WINDOWS - -// is not available on Windows. Use our own simple regex -// implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#else - -// may not be available on this platform. Use our own -// simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#endif // GTEST_HAS_POSIX_RE - -#ifndef GTEST_HAS_EXCEPTIONS -// The user didn't tell us whether exceptions are enabled, so we need -// to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) -// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS -// macro to enable exceptions, so we'll do the same. -// Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__GNUC__) && __EXCEPTIONS -// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) -// Sun Pro CC supports exceptions. However, there is no compile-time way of -// detecting whether they are enabled or not. Therefore, we assume that -// they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS -// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) -// Exception handling is in effect by default in HP aCC compiler. It has to -// be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else -// For other compilers, we assume exceptions are disabled to be -// conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) -#endif // GTEST_HAS_EXCEPTIONS - -#if !defined(GTEST_HAS_STD_STRING) -// Even though we don't use this macro any longer, we keep it in case -// some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 -#elif !GTEST_HAS_STD_STRING -// The user told us that ::std::string isn't available. -# error "Google Test cannot be used where ::std::string isn't available." -#endif // !defined(GTEST_HAS_STD_STRING) - -#ifndef GTEST_HAS_GLOBAL_STRING -// The user didn't tell us whether ::string is available, so we need -// to figure it out. - -# define GTEST_HAS_GLOBAL_STRING 0 - -#endif // GTEST_HAS_GLOBAL_STRING - -#ifndef GTEST_HAS_STD_WSTRING -// The user didn't tell us whether ::std::wstring is available, so we need -// to figure it out. -// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring -// is available. - -// Cygwin 1.7 and below doesn't support ::std::wstring. -// Solaris' libc++ doesn't support it either. Android has -// no support for it at least as recent as Froyo (2.2). -# define GTEST_HAS_STD_WSTRING \ - (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) - -#endif // GTEST_HAS_STD_WSTRING - -#ifndef GTEST_HAS_GLOBAL_WSTRING -// The user didn't tell us whether ::wstring is available, so we need -// to figure it out. -# define GTEST_HAS_GLOBAL_WSTRING \ - (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) -#endif // GTEST_HAS_GLOBAL_WSTRING - -// Determines whether RTTI is available. -#ifndef GTEST_HAS_RTTI -// The user didn't tell us whether RTTI is enabled, so we need to -// figure it out. - -# ifdef _MSC_VER - -# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) - -# ifdef __GXX_RTTI -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI - -// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if -// both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) - -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -# else - -// For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 - -# endif // _MSC_VER - -#endif // GTEST_HAS_RTTI - -// It's this header's responsibility to #include when RTTI -// is enabled. -#if GTEST_HAS_RTTI -# include -#endif - -// Determines whether Google Test can use the pthreads library. -#ifndef GTEST_HAS_PTHREAD -// The user didn't tell us explicitly, so we assume pthreads support is -// available on Linux and Mac. -// -// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 -// to your compiler flags. -# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX) -#endif // GTEST_HAS_PTHREAD - -#if GTEST_HAS_PTHREAD -// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is -// true. -# include // NOLINT - -// For timespec and nanosleep, used below. -# include // NOLINT -#endif - -// Determines whether Google Test can use tr1/tuple. You can define -// this macro to 0 to prevent Google Test from using tuple (any -// feature depending on tuple with be disabled in this mode). -#ifndef GTEST_HAS_TR1_TUPLE -// The user didn't tell us not to do it, so we assume it's OK. -# define GTEST_HAS_TR1_TUPLE 1 -#endif // GTEST_HAS_TR1_TUPLE - -// Determines whether Google Test's own tr1 tuple implementation -// should be used. -#ifndef GTEST_USE_OWN_TR1_TUPLE -// The user didn't tell us, so we need to figure it out. - -// We use our own TR1 tuple if we aren't sure the user has an -// implementation of it already. At this time, GCC 4.0.0+ and MSVC -// 2010 are the only mainstream compilers that come with a TR1 tuple -// implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by -// defining __GNUC__ and friends, but cannot compile GCC's tuple -// implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB -// Feature Pack download, which we cannot assume the user has. -# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000)) \ - || _MSC_VER >= 1600 -# define GTEST_USE_OWN_TR1_TUPLE 0 -# else -# define GTEST_USE_OWN_TR1_TUPLE 1 -# endif - -#endif // GTEST_USE_OWN_TR1_TUPLE - -// To avoid conditional compilation everywhere, we make it -// gtest-port.h's responsibility to #include the header implementing -// tr1/tuple. -#if GTEST_HAS_TR1_TUPLE - -# if GTEST_USE_OWN_TR1_TUPLE -// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! - -// Copyright 2009 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Implements a subset of TR1 tuple needed by Google Test and Google Mock. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ - -#include // For ::std::pair. - -// The compiler used in Symbian has a bug that prevents us from declaring the -// tuple template as a friend (it complains that tuple is redefined). This -// hack bypasses the bug by declaring the members that should otherwise be -// private as public. -// Sun Studio versions < 12 also have the above bug. -#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: -#else -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ - template friend class tuple; \ - private: -#endif - -// GTEST_n_TUPLE_(T) is the type of an n-tuple. -#define GTEST_0_TUPLE_(T) tuple<> -#define GTEST_1_TUPLE_(T) tuple -#define GTEST_2_TUPLE_(T) tuple -#define GTEST_3_TUPLE_(T) tuple -#define GTEST_4_TUPLE_(T) tuple -#define GTEST_5_TUPLE_(T) tuple -#define GTEST_6_TUPLE_(T) tuple -#define GTEST_7_TUPLE_(T) tuple -#define GTEST_8_TUPLE_(T) tuple -#define GTEST_9_TUPLE_(T) tuple -#define GTEST_10_TUPLE_(T) tuple - -// GTEST_n_TYPENAMES_(T) declares a list of n typenames. -#define GTEST_0_TYPENAMES_(T) -#define GTEST_1_TYPENAMES_(T) typename T##0 -#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 -#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 -#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3 -#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4 -#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5 -#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6 -#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 -#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8 -#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8, typename T##9 - -// In theory, defining stuff in the ::std namespace is undefined -// behavior. We can do this as we are playing the role of a standard -// library vendor. -namespace std { -namespace tr1 { - -template -class tuple; - -// Anything in namespace gtest_internal is Google Test's INTERNAL -// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. -namespace gtest_internal { - -// ByRef::type is T if T is a reference; otherwise it's const T&. -template -struct ByRef { typedef const T& type; }; // NOLINT -template -struct ByRef { typedef T& type; }; // NOLINT - -// A handy wrapper for ByRef. -#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type - -// AddRef::type is T if T is a reference; otherwise it's T&. This -// is the same as tr1::add_reference::type. -template -struct AddRef { typedef T& type; }; // NOLINT -template -struct AddRef { typedef T& type; }; // NOLINT - -// A handy wrapper for AddRef. -#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type - -// A helper for implementing get(). -template class Get; - -// A helper for implementing tuple_element. kIndexValid is true -// iff k < the number of fields in tuple type T. -template -struct TupleElement; - -template -struct TupleElement { typedef T0 type; }; - -template -struct TupleElement { typedef T1 type; }; - -template -struct TupleElement { typedef T2 type; }; - -template -struct TupleElement { typedef T3 type; }; - -template -struct TupleElement { typedef T4 type; }; - -template -struct TupleElement { typedef T5 type; }; - -template -struct TupleElement { typedef T6 type; }; - -template -struct TupleElement { typedef T7 type; }; - -template -struct TupleElement { typedef T8 type; }; - -template -struct TupleElement { typedef T9 type; }; - -} // namespace gtest_internal - -template <> -class tuple<> { - public: - tuple() {} - tuple(const tuple& /* t */) {} - tuple& operator=(const tuple& /* t */) { return *this; } -}; - -template -class GTEST_1_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} - - tuple(const tuple& t) : f0_(t.f0_) {} - - template - tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_1_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { - f0_ = t.f0_; - return *this; - } - - T0 f0_; -}; - -template -class GTEST_2_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), - f1_(f1) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} - - template - tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} - template - tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_2_TUPLE_(U)& t) { - return CopyFrom(t); - } - template - tuple& operator=(const ::std::pair& p) { - f0_ = p.first; - f1_ = p.second; - return *this; - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - return *this; - } - - T0 f0_; - T1 f1_; -}; - -template -class GTEST_3_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} - - template - tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_3_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; -}; - -template -class GTEST_4_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} - - template - tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_4_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; -}; - -template -class GTEST_5_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, - GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_) {} - - template - tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_5_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; -}; - -template -class GTEST_6_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_) {} - - template - tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_6_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; -}; - -template -class GTEST_7_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} - - template - tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_7_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; -}; - -template -class GTEST_8_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, - GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} - - template - tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_8_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; -}; - -template -class GTEST_9_TUPLE_(T) { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} - - template - tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_9_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - f8_ = t.f8_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; - T8 f8_; -}; - -template -class tuple { - public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), - f9_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} - - template - tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), - f9_(t.f9_) {} - - tuple& operator=(const tuple& t) { return CopyFrom(t); } - - template - tuple& operator=(const GTEST_10_TUPLE_(U)& t) { - return CopyFrom(t); - } - - GTEST_DECLARE_TUPLE_AS_FRIEND_ - - template - tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { - f0_ = t.f0_; - f1_ = t.f1_; - f2_ = t.f2_; - f3_ = t.f3_; - f4_ = t.f4_; - f5_ = t.f5_; - f6_ = t.f6_; - f7_ = t.f7_; - f8_ = t.f8_; - f9_ = t.f9_; - return *this; - } - - T0 f0_; - T1 f1_; - T2 f2_; - T3 f3_; - T4 f4_; - T5 f5_; - T6 f6_; - T7 f7_; - T8 f8_; - T9 f9_; -}; - -// 6.1.3.2 Tuple creation functions. - -// Known limitations: we don't support passing an -// std::tr1::reference_wrapper to make_tuple(). And we don't -// implement tie(). - -inline tuple<> make_tuple() { return tuple<>(); } - -template -inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { - return GTEST_1_TUPLE_(T)(f0); -} - -template -inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { - return GTEST_2_TUPLE_(T)(f0, f1); -} - -template -inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { - return GTEST_3_TUPLE_(T)(f0, f1, f2); -} - -template -inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3) { - return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); -} - -template -inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4) { - return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); -} - -template -inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5) { - return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); -} - -template -inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6) { - return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); -} - -template -inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { - return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); -} - -template -inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8) { - return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); -} - -template -inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8, const T9& f9) { - return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); -} - -// 6.1.3.3 Tuple helper classes. - -template struct tuple_size; - -template -struct tuple_size { static const int value = 0; }; - -template -struct tuple_size { static const int value = 1; }; - -template -struct tuple_size { static const int value = 2; }; - -template -struct tuple_size { static const int value = 3; }; - -template -struct tuple_size { static const int value = 4; }; - -template -struct tuple_size { static const int value = 5; }; - -template -struct tuple_size { static const int value = 6; }; - -template -struct tuple_size { static const int value = 7; }; - -template -struct tuple_size { static const int value = 8; }; - -template -struct tuple_size { static const int value = 9; }; - -template -struct tuple_size { static const int value = 10; }; - -template -struct tuple_element { - typedef typename gtest_internal::TupleElement< - k < (tuple_size::value), k, Tuple>::type type; -}; - -#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type - -// 6.1.3.4 Element access. - -namespace gtest_internal { - -template <> -class Get<0> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - Field(Tuple& t) { return t.f0_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - ConstField(const Tuple& t) { return t.f0_; } -}; - -template <> -class Get<1> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - Field(Tuple& t) { return t.f1_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - ConstField(const Tuple& t) { return t.f1_; } -}; - -template <> -class Get<2> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - Field(Tuple& t) { return t.f2_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - ConstField(const Tuple& t) { return t.f2_; } -}; - -template <> -class Get<3> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - Field(Tuple& t) { return t.f3_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - ConstField(const Tuple& t) { return t.f3_; } -}; - -template <> -class Get<4> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - Field(Tuple& t) { return t.f4_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - ConstField(const Tuple& t) { return t.f4_; } -}; - -template <> -class Get<5> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - Field(Tuple& t) { return t.f5_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - ConstField(const Tuple& t) { return t.f5_; } -}; - -template <> -class Get<6> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - Field(Tuple& t) { return t.f6_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - ConstField(const Tuple& t) { return t.f6_; } -}; - -template <> -class Get<7> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - Field(Tuple& t) { return t.f7_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - ConstField(const Tuple& t) { return t.f7_; } -}; - -template <> -class Get<8> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - Field(Tuple& t) { return t.f8_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - ConstField(const Tuple& t) { return t.f8_; } -}; - -template <> -class Get<9> { - public: - template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - Field(Tuple& t) { return t.f9_; } // NOLINT - - template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - ConstField(const Tuple& t) { return t.f9_; } -}; - -} // namespace gtest_internal - -template -GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(GTEST_10_TUPLE_(T)& t) { - return gtest_internal::Get::Field(t); -} - -template -GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(const GTEST_10_TUPLE_(T)& t) { - return gtest_internal::Get::ConstField(t); -} - -// 6.1.3.5 Relational operators - -// We only implement == and !=, as we don't have a need for the rest yet. - -namespace gtest_internal { - -// SameSizeTuplePrefixComparator::Eq(t1, t2) returns true if the -// first k fields of t1 equals the first k fields of t2. -// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if -// k1 != k2. -template -struct SameSizeTuplePrefixComparator; - -template <> -struct SameSizeTuplePrefixComparator<0, 0> { - template - static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { - return true; - } -}; - -template -struct SameSizeTuplePrefixComparator { - template - static bool Eq(const Tuple1& t1, const Tuple2& t2) { - return SameSizeTuplePrefixComparator::Eq(t1, t2) && - ::std::tr1::get(t1) == ::std::tr1::get(t2); - } -}; - -} // namespace gtest_internal - -template -inline bool operator==(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { - return gtest_internal::SameSizeTuplePrefixComparator< - tuple_size::value, - tuple_size::value>::Eq(t, u); -} - -template -inline bool operator!=(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { return !(t == u); } - -// 6.1.4 Pairs. -// Unimplemented. - -} // namespace tr1 -} // namespace std - -#undef GTEST_0_TUPLE_ -#undef GTEST_1_TUPLE_ -#undef GTEST_2_TUPLE_ -#undef GTEST_3_TUPLE_ -#undef GTEST_4_TUPLE_ -#undef GTEST_5_TUPLE_ -#undef GTEST_6_TUPLE_ -#undef GTEST_7_TUPLE_ -#undef GTEST_8_TUPLE_ -#undef GTEST_9_TUPLE_ -#undef GTEST_10_TUPLE_ - -#undef GTEST_0_TYPENAMES_ -#undef GTEST_1_TYPENAMES_ -#undef GTEST_2_TYPENAMES_ -#undef GTEST_3_TYPENAMES_ -#undef GTEST_4_TYPENAMES_ -#undef GTEST_5_TYPENAMES_ -#undef GTEST_6_TYPENAMES_ -#undef GTEST_7_TYPENAMES_ -#undef GTEST_8_TYPENAMES_ -#undef GTEST_9_TYPENAMES_ -#undef GTEST_10_TYPENAMES_ - -#undef GTEST_DECLARE_TUPLE_AS_FRIEND_ -#undef GTEST_BY_REF_ -#undef GTEST_ADD_REF_ -#undef GTEST_TUPLE_ELEMENT_ - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ -# elif GTEST_OS_SYMBIAN - -// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to -// use STLport's tuple implementation, which unfortunately doesn't -// work as the copy of STLport distributed with Symbian is incomplete. -// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to -// use its own tuple implementation. -# ifdef BOOST_HAS_TR1_TUPLE -# undef BOOST_HAS_TR1_TUPLE -# endif // BOOST_HAS_TR1_TUPLE - -// This prevents , which defines -// BOOST_HAS_TR1_TUPLE, from being #included by Boost's . -# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED -# include - -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) -// GCC 4.0+ implements tr1/tuple in the header. This does -// not conform to the TR1 spec, which requires the header to be . - -# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 -// Until version 4.3.2, gcc has a bug that causes , -// which is #included by , to not compile when RTTI is -// disabled. _TR1_FUNCTIONAL is the header guard for -// . Hence the following #define is a hack to prevent -// from being included. -# define _TR1_FUNCTIONAL 1 -# include -# undef _TR1_FUNCTIONAL // Allows the user to #include - // if he chooses to. -# else -# include // NOLINT -# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 - -# else -// If the compiler is not GCC 4.0+, we assume the user is using a -// spec-conforming TR1 implementation. -# include // NOLINT -# endif // GTEST_USE_OWN_TR1_TUPLE - -#endif // GTEST_HAS_TR1_TUPLE - -// Determines whether clone(2) is supported. -// Usually it will only be available on Linux, excluding -// Linux on the Itanium architecture. -// Also see http://linux.die.net/man/2/clone. -#ifndef GTEST_HAS_CLONE -// The user didn't tell us, so we need to figure it out. - -# if GTEST_OS_LINUX && !defined(__ia64__) -# define GTEST_HAS_CLONE 1 -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) - -#endif // GTEST_HAS_CLONE - -// Determines whether to support stream redirection. This is used to test -// output correctness and to implement death tests. -#ifndef GTEST_HAS_STREAM_REDIRECTION -// By default, we assume that stream redirection is supported on all -// platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN -#endif // GTEST_HAS_STREAM_REDIRECTION - -// Determines whether to support death tests. -// Google Test does not support death tests for VC 7.1 and earlier as -// abort() in a VC 7.1 application compiled as GUI in debug config -// pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ - GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX) -# define GTEST_HAS_DEATH_TEST 1 -# include // NOLINT -#endif - -// We don't support MSVC 7.1 with exceptions disabled now. Therefore -// all the compilers we care about are adequate for supporting -// value-parameterized tests. -#define GTEST_HAS_PARAM_TEST 1 - -// Determines whether to support type-driven tests. - -// Typed tests need and variadic macros, which GCC, VC++ 8.0, -// Sun Pro CC, IBM Visual Age, and HP aCC support. -#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ - defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 -#endif - -// Determines whether to support Combine(). This only makes sense when -// value-parameterized tests are enabled. The implementation doesn't -// work on Sun Studio since it doesn't understand templated conversion -// operators. -#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) -# define GTEST_HAS_COMBINE 1 -#endif - -// Determines whether the system compiler uses UTF-16 for encoding wide strings. -#define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) - -// Determines whether test results can be streamed to a socket. -#if GTEST_OS_LINUX -# define GTEST_CAN_STREAM_RESULTS_ 1 -#endif - -// Defines some utility macros. - -// The GNU compiler emits a warning if nested "if" statements are followed by -// an "else" statement and braces are not used to explicitly disambiguate the -// "else" binding. This leads to problems with code like: -// -// if (gate) -// ASSERT_*(condition) << "Some message"; -// -// The "switch (0) case 0:" idiom is used to suppress this. -#ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ -#else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT -#endif - -// Use this annotation at the end of a struct/class definition to -// prevent the compiler from optimizing away instances that are never -// used. This is useful when all interesting logic happens inside the -// c'tor and / or d'tor. Example: -// -// struct Foo { -// Foo() { ... } -// } GTEST_ATTRIBUTE_UNUSED_; -// -// Also use it after a variable or parameter declaration to tell the -// compiler the variable/parameter does not have to be used. -#if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -#else -# define GTEST_ATTRIBUTE_UNUSED_ -#endif - -// A macro to disallow operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_ASSIGN_(type)\ - void operator=(type const &) - -// A macro to disallow copy constructor and operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ - type(type const &);\ - GTEST_DISALLOW_ASSIGN_(type) - -// Tell the compiler to warn about unused return values for functions declared -// with this macro. The macro should be used on function declarations -// following the argument list: -// -// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; -#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) -#else -# define GTEST_MUST_USE_RESULT_ -#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC - -// Determine whether the compiler supports Microsoft's Structured Exception -// Handling. This is supported by several Windows compilers but generally -// does not exist on any other system. -#ifndef GTEST_HAS_SEH -// The user didn't tell us, so we need to figure it out. - -# if defined(_MSC_VER) || defined(__BORLANDC__) -// These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else -// Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif - -#endif // GTEST_HAS_SEH - -#ifdef _MSC_VER - -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif - -#endif // _MSC_VER - -#ifndef GTEST_API_ -# define GTEST_API_ -#endif - -#ifdef __GNUC__ -// Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) -#else -# define GTEST_NO_INLINE_ -#endif - -namespace testing { - -class Message; - -namespace internal { - -class String; - -// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time -// expression is true. For example, you could use it to verify the -// size of a static array: -// -// GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, -// content_type_names_incorrect_size); -// -// or to make sure a struct is smaller than a certain size: -// -// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); -// -// The second argument to the macro is the name of the variable. If -// the expression is false, most compilers will issue a warning/error -// containing the name of the variable. - -template -struct CompileAssert { -}; - -#define GTEST_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1] - -// Implementation details of GTEST_COMPILE_ASSERT_: -// -// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 -// elements (and thus is invalid) when the expression is false. -// -// - The simpler definition -// -// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] -// -// does not work, as gcc supports variable-length arrays whose sizes -// are determined at run-time (this is gcc's extension and not part -// of the C++ standard). As a result, gcc fails to reject the -// following code with the simple definition: -// -// int foo; -// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is -// // not a compile-time constant. -// -// - By using the type CompileAssert<(bool(expr))>, we ensures that -// expr is a compile-time constant. (Template arguments must be -// determined at compile-time.) -// -// - The outter parentheses in CompileAssert<(bool(expr))> are necessary -// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written -// -// CompileAssert -// -// instead, these compilers will refuse to compile -// -// GTEST_COMPILE_ASSERT_(5 > 0, some_message); -// -// (They seem to think the ">" in "5 > 0" marks the end of the -// template argument list.) -// -// - The array size is (bool(expr) ? 1 : -1), instead of simply -// -// ((expr) ? 1 : -1). -// -// This is to avoid running into a bug in MS VC 7.1, which -// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. - -// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. -// -// This template is declared, but intentionally undefined. -template -struct StaticAssertTypeEqHelper; - -template -struct StaticAssertTypeEqHelper {}; - -#if GTEST_HAS_GLOBAL_STRING -typedef ::string string; -#else -typedef ::std::string string; -#endif // GTEST_HAS_GLOBAL_STRING - -#if GTEST_HAS_GLOBAL_WSTRING -typedef ::wstring wstring; -#elif GTEST_HAS_STD_WSTRING -typedef ::std::wstring wstring; -#endif // GTEST_HAS_GLOBAL_WSTRING - -// A helper for suppressing warnings on constant condition. It just -// returns 'condition'. -GTEST_API_ bool IsTrue(bool condition); - -// Defines scoped_ptr. - -// This implementation of scoped_ptr is PARTIAL - it only contains -// enough stuff to satisfy Google Test's need. -template -class scoped_ptr { - public: - typedef T element_type; - - explicit scoped_ptr(T* p = NULL) : ptr_(p) {} - ~scoped_ptr() { reset(); } - - T& operator*() const { return *ptr_; } - T* operator->() const { return ptr_; } - T* get() const { return ptr_; } - - T* release() { - T* const ptr = ptr_; - ptr_ = NULL; - return ptr; - } - - void reset(T* p = NULL) { - if (p != ptr_) { - if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. - delete ptr_; - } - ptr_ = p; - } - } - private: - T* ptr_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); -}; - -// Defines RE. - -// A simple C++ wrapper for . It uses the POSIX Extended -// Regular Expression syntax. -class GTEST_API_ RE { - public: - // A copy constructor is required by the Standard to initialize object - // references from r-values. - RE(const RE& other) { Init(other.pattern()); } - - // Constructs an RE from a string. - RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT - -#if GTEST_HAS_GLOBAL_STRING - - RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT - -#endif // GTEST_HAS_GLOBAL_STRING - - RE(const char* regex) { Init(regex); } // NOLINT - ~RE(); - - // Returns the string representation of the regex. - const char* pattern() const { return pattern_; } - - // FullMatch(str, re) returns true iff regular expression re matches - // the entire str. - // PartialMatch(str, re) returns true iff regular expression re - // matches a substring of str (including str itself). - // - // TODO(wan@google.com): make FullMatch() and PartialMatch() work - // when str contains NUL characters. - static bool FullMatch(const ::std::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::std::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } - -#if GTEST_HAS_GLOBAL_STRING - - static bool FullMatch(const ::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } - -#endif // GTEST_HAS_GLOBAL_STRING - - static bool FullMatch(const char* str, const RE& re); - static bool PartialMatch(const char* str, const RE& re); - - private: - void Init(const char* regex); - - // We use a const char* instead of a string, as Google Test may be used - // where string is not available. We also do not use Google Test's own - // String type here, in order to simplify dependencies between the - // files. - const char* pattern_; - bool is_valid_; - -#if GTEST_USES_POSIX_RE - - regex_t full_regex_; // For FullMatch(). - regex_t partial_regex_; // For PartialMatch(). - -#else // GTEST_USES_SIMPLE_RE - - const char* full_pattern_; // For FullMatch(); - -#endif - - GTEST_DISALLOW_ASSIGN_(RE); -}; - -// Formats a source file path and a line number as they would appear -// in an error message from the compiler used to compile this code. -GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); - -// Formats a file location for compiler-independent XML output. -// Although this function is not platform dependent, we put it next to -// FormatFileLocation in order to contrast the two functions. -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, - int line); - -// Defines logging utilities: -// GTEST_LOG_(severity) - logs messages at the specified severity level. The -// message itself is streamed into the macro. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. - -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; - -// Formats log entry severity, provides a stream object for streaming the -// log message, and terminates the message with a newline when going out of -// scope. -class GTEST_API_ GTestLog { - public: - GTestLog(GTestLogSeverity severity, const char* file, int line); - - // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. - ~GTestLog(); - - ::std::ostream& GetStream() { return ::std::cerr; } - - private: - const GTestLogSeverity severity_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); -}; - -#define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() - -inline void LogToStderr() {} -inline void FlushInfoLog() { fflush(NULL); } - -// INTERNAL IMPLEMENTATION - DO NOT USE. -// -// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition -// is not satisfied. -// Synopsys: -// GTEST_CHECK_(boolean_condition); -// or -// GTEST_CHECK_(boolean_condition) << "Additional message"; -// -// This checks the condition and if the condition is not satisfied -// it prints message about the condition violation, including the -// condition itself, plus additional message streamed into it, if any, -// and then it aborts the program. It aborts the program irrespective of -// whether it is built in the debug mode or not. -#define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " - -// An all-mode assert to verify that the given POSIX-style function -// call returns 0 (indicating success). Known limitation: this -// doesn't expand to a balanced 'if' statement, so enclose the macro -// in {} if you need to use it as the only statement in an 'if' -// branch. -#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Use ImplicitCast_ as a safe version of static_cast for upcasting in -// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a -// const Foo*). When you use ImplicitCast_, the compiler checks that -// the cast is safe. Such explicit ImplicitCast_s are necessary in -// surprisingly many situations where C++ demands an exact type match -// instead of an argument type convertable to a target type. -// -// The syntax for using ImplicitCast_ is the same as for static_cast: -// -// ImplicitCast_(expr) -// -// ImplicitCast_ would have been part of the C++ standard library, -// but the proposal was submitted too late. It will probably make -// its way into the language in the future. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., implicit_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template -inline To ImplicitCast_(To x) { return x; } - -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts -// always succeed. When you downcast (that is, cast a pointer from -// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because -// how do you know the pointer is really of type SubclassOfFoo? It -// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, -// when you downcast, you should use this macro. In debug mode, we -// use dynamic_cast<> to double-check the downcast is legal (we die -// if it's not). In normal mode, we do the efficient static_cast<> -// instead. Thus, it's important to test in debug mode to make sure -// the cast is legal! -// This is the only place in the code we should use dynamic_cast<>. -// In particular, you SHOULDN'T be using dynamic_cast<> in order to -// do RTTI (eg code like this: -// if (dynamic_cast(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(foo)) HandleASubclass2Object(foo); -// You should design the code some other way not to need this. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., down_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers - // Ensures that To is a sub-type of From *. This test is here only - // for compile-time type checking, and has no overhead in an - // optimized build at run-time, as it will be optimized away - // completely. - if (false) { - const To to = NULL; - ::testing::internal::ImplicitCast_(to); - } - -#if GTEST_HAS_RTTI - // RTTI: debug mode only! - GTEST_CHECK_(f == NULL || dynamic_cast(f) != NULL); -#endif - return static_cast(f); -} - -// Downcasts the pointer of type Base to Derived. -// Derived must be a subclass of Base. The parameter MUST -// point to a class of type Derived, not any subclass of it. -// When RTTI is available, the function performs a runtime -// check to enforce this. -template -Derived* CheckedDowncastToActualType(Base* base) { -#if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); - return dynamic_cast(base); // NOLINT -#else - return static_cast(base); // Poor man's downcast. -#endif -} - -#if GTEST_HAS_STREAM_REDIRECTION - -// Defines the stderr capturer: -// CaptureStdout - starts capturing stdout. -// GetCapturedStdout - stops capturing stdout and returns the captured string. -// CaptureStderr - starts capturing stderr. -// GetCapturedStderr - stops capturing stderr and returns the captured string. -// -GTEST_API_ void CaptureStdout(); -GTEST_API_ String GetCapturedStdout(); -GTEST_API_ void CaptureStderr(); -GTEST_API_ String GetCapturedStderr(); - -#endif // GTEST_HAS_STREAM_REDIRECTION - - -#if GTEST_HAS_DEATH_TEST - -// A copy of all command line arguments. Set by InitGoogleTest(). -extern ::std::vector g_argvs; - -// GTEST_HAS_DEATH_TEST implies we have ::std::string. -const ::std::vector& GetArgvs(); - -#endif // GTEST_HAS_DEATH_TEST - -// Defines synchronization primitives. - -#if GTEST_HAS_PTHREAD - -// Sleeps for (roughly) n milli-seconds. This function is only for -// testing Google Test's own constructs. Don't use it in user tests, -// either directly or indirectly. -inline void SleepMilliseconds(int n) { - const timespec time = { - 0, // 0 seconds. - n * 1000L * 1000L, // And n ms. - }; - nanosleep(&time, NULL); -} - -// Allows a controller thread to pause execution of newly created -// threads until notified. Instances of this class must be created -// and destroyed in the controller thread. -// -// This class is only for testing Google Test's own constructs. Do not -// use it in user tests, either directly or indirectly. -class Notification { - public: - Notification() : notified_(false) {} - - // Notifies all threads created with this notification to start. Must - // be called from the controller thread. - void Notify() { notified_ = true; } - - // Blocks until the controller thread notifies. Must be called from a test - // thread. - void WaitForNotification() { - while(!notified_) { - SleepMilliseconds(10); - } - } - - private: - volatile bool notified_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); -}; - -// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. -// Consequently, it cannot select a correct instantiation of ThreadWithParam -// in order to call its Run(). Introducing ThreadWithParamBase as a -// non-templated base class for ThreadWithParam allows us to bypass this -// problem. -class ThreadWithParamBase { - public: - virtual ~ThreadWithParamBase() {} - virtual void Run() = 0; -}; - -// pthread_create() accepts a pointer to a function type with the C linkage. -// According to the Standard (7.5/1), function types with different linkages -// are different even if they are otherwise identical. Some compilers (for -// example, SunStudio) treat them as different types. Since class methods -// cannot be defined with C-linkage we need to define a free C-function to -// pass into pthread_create(). -extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { - static_cast(thread)->Run(); - return NULL; -} - -// Helper class for testing Google Test's multi-threading constructs. -// To use it, write: -// -// void ThreadFunc(int param) { /* Do things with param */ } -// Notification thread_can_start; -// ... -// // The thread_can_start parameter is optional; you can supply NULL. -// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); -// thread_can_start.Notify(); -// -// These classes are only for testing Google Test's own constructs. Do -// not use them in user tests, either directly or indirectly. -template -class ThreadWithParam : public ThreadWithParamBase { - public: - typedef void (*UserThreadFunc)(T); - - ThreadWithParam( - UserThreadFunc func, T param, Notification* thread_can_start) - : func_(func), - param_(param), - thread_can_start_(thread_can_start), - finished_(false) { - ThreadWithParamBase* const base = this; - // The thread can be created only after all fields except thread_ - // have been initialized. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); - } - ~ThreadWithParam() { Join(); } - - void Join() { - if (!finished_) { - GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); - finished_ = true; - } - } - - virtual void Run() { - if (thread_can_start_ != NULL) - thread_can_start_->WaitForNotification(); - func_(param_); - } - - private: - const UserThreadFunc func_; // User-supplied thread function. - const T param_; // User-supplied parameter to the thread function. - // When non-NULL, used to block execution until the controller thread - // notifies. - Notification* const thread_can_start_; - bool finished_; // true iff we know that the thread function has finished. - pthread_t thread_; // The native thread object. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); -}; - -// MutexBase and Mutex implement mutex on pthreads-based platforms. They -// are used in conjunction with class MutexLock: -// -// Mutex mutex; -// ... -// MutexLock lock(&mutex); // Acquires the mutex and releases it at the end -// // of the current scope. -// -// MutexBase implements behavior for both statically and dynamically -// allocated mutexes. Do not use MutexBase directly. Instead, write -// the following to define a static mutex: -// -// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); -// -// You can forward declare a static mutex like this: -// -// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); -// -// To create a dynamic mutex, just define an object of type Mutex. -class MutexBase { - public: - // Acquires this mutex. - void Lock() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); - owner_ = pthread_self(); - } - - // Releases this mutex. - void Unlock() { - // We don't protect writing to owner_ here, as it's the caller's - // responsibility to ensure that the current thread holds the - // mutex when this is called. - owner_ = 0; - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); - } - - // Does nothing if the current thread holds the mutex. Otherwise, crashes - // with high probability. - void AssertHeld() const { - GTEST_CHECK_(owner_ == pthread_self()) - << "The current thread is not holding the mutex @" << this; - } - - // A static mutex may be used before main() is entered. It may even - // be used before the dynamic initialization stage. Therefore we - // must be able to initialize a static mutex object at link time. - // This means MutexBase has to be a POD and its member variables - // have to be public. - public: - pthread_mutex_t mutex_; // The underlying pthread mutex. - pthread_t owner_; // The thread holding the mutex; 0 means no one holds it. -}; - -// Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex - -// Defines and statically (i.e. at link time) initializes a static mutex. -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, 0 } - -// The Mutex class can only be used for mutexes created at runtime. It -// shares its API with MutexBase otherwise. -class Mutex : public MutexBase { - public: - Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); - owner_ = 0; - } - ~Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); -}; - -// We cannot name this class MutexLock as the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. Hence the typedef trick below. -class GTestMutexLock { - public: - explicit GTestMutexLock(MutexBase* mutex) - : mutex_(mutex) { mutex_->Lock(); } - - ~GTestMutexLock() { mutex_->Unlock(); } - - private: - MutexBase* const mutex_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); -}; - -typedef GTestMutexLock MutexLock; - -// Helpers for ThreadLocal. - -// pthread_key_create() requires DeleteThreadLocalValue() to have -// C-linkage. Therefore it cannot be templatized to access -// ThreadLocal. Hence the need for class -// ThreadLocalValueHolderBase. -class ThreadLocalValueHolderBase { - public: - virtual ~ThreadLocalValueHolderBase() {} -}; - -// Called by pthread to delete thread-local data stored by -// pthread_setspecific(). -extern "C" inline void DeleteThreadLocalValue(void* value_holder) { - delete static_cast(value_holder); -} - -// Implements thread-local storage on pthreads-based systems. -// -// // Thread 1 -// ThreadLocal tl(100); // 100 is the default value for each thread. -// -// // Thread 2 -// tl.set(150); // Changes the value for thread 2 only. -// EXPECT_EQ(150, tl.get()); -// -// // Thread 1 -// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. -// tl.set(200); -// EXPECT_EQ(200, tl.get()); -// -// The template type argument T must have a public copy constructor. -// In addition, the default ThreadLocal constructor requires T to have -// a public default constructor. -// -// An object managed for a thread by a ThreadLocal instance is deleted -// when the thread exits. Or, if the ThreadLocal instance dies in -// that thread, when the ThreadLocal dies. It's the user's -// responsibility to ensure that all other threads using a ThreadLocal -// have exited when it dies, or the per-thread objects for those -// threads will not be deleted. -// -// Google Test only uses global ThreadLocal objects. That means they -// will die after main() has returned. Therefore, no per-thread -// object managed by Google Test will be leaked as long as all threads -// using Google Test have exited when main() returns. -template -class ThreadLocal { - public: - ThreadLocal() : key_(CreateKey()), - default_() {} - explicit ThreadLocal(const T& value) : key_(CreateKey()), - default_(value) {} - - ~ThreadLocal() { - // Destroys the managed object for the current thread, if any. - DeleteThreadLocalValue(pthread_getspecific(key_)); - - // Releases resources associated with the key. This will *not* - // delete managed objects for other threads. - GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); - } - - T* pointer() { return GetOrCreateValue(); } - const T* pointer() const { return GetOrCreateValue(); } - const T& get() const { return *pointer(); } - void set(const T& value) { *pointer() = value; } - - private: - // Holds a value of type T. - class ValueHolder : public ThreadLocalValueHolderBase { - public: - explicit ValueHolder(const T& value) : value_(value) {} - - T* pointer() { return &value_; } - - private: - T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); - }; - - static pthread_key_t CreateKey() { - pthread_key_t key; - // When a thread exits, DeleteThreadLocalValue() will be called on - // the object managed for that thread. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_key_create(&key, &DeleteThreadLocalValue)); - return key; - } - - T* GetOrCreateValue() const { - ThreadLocalValueHolderBase* const holder = - static_cast(pthread_getspecific(key_)); - if (holder != NULL) { - return CheckedDowncastToActualType(holder)->pointer(); - } - - ValueHolder* const new_holder = new ValueHolder(default_); - ThreadLocalValueHolderBase* const holder_base = new_holder; - GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); - return new_holder->pointer(); - } - - // A key pthreads uses for looking up per-thread values. - const pthread_key_t key_; - const T default_; // The default value for each thread. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); -}; - -# define GTEST_IS_THREADSAFE 1 - -#else // GTEST_HAS_PTHREAD - -// A dummy implementation of synchronization primitives (mutex, lock, -// and thread-local variable). Necessary for compiling Google Test where -// mutex is not supported - using Google Test in multiple threads is not -// supported on such platforms. - -class Mutex { - public: - Mutex() {} - void AssertHeld() const {} -}; - -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex - -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex - -class GTestMutexLock { - public: - explicit GTestMutexLock(Mutex*) {} // NOLINT -}; - -typedef GTestMutexLock MutexLock; - -template -class ThreadLocal { - public: - ThreadLocal() : value_() {} - explicit ThreadLocal(const T& value) : value_(value) {} - T* pointer() { return &value_; } - const T* pointer() const { return &value_; } - const T& get() const { return value_; } - void set(const T& value) { value_ = value; } - private: - T value_; -}; - -// The above synchronization primitives have dummy implementations. -// Therefore Google Test is not thread-safe. -# define GTEST_IS_THREADSAFE 0 - -#endif // GTEST_HAS_PTHREAD - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -GTEST_API_ size_t GetThreadCount(); - -// Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler and generates a warning in Sun Studio. The Nokia Symbian -// and the IBM XL C/C++ compiler try to instantiate a copy constructor -// for objects passed through ellipsis (...), failing for uncopyable -// objects. We define this to ensure that only POD is passed through -// ellipsis on these systems. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_ELLIPSIS_NEEDS_POD_ 1 -#else -# define GTEST_CAN_COMPARE_NULL 1 -#endif - -// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between -// const T& and const T* in a function template. These compilers -// _can_ decide between class template specializations for T and T*, -// so a tr1::type_traits-like is_pointer works. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) -# define GTEST_NEEDS_IS_POINTER_ 1 -#endif - -template -struct bool_constant { - typedef bool_constant type; - static const bool value = bool_value; -}; -template const bool bool_constant::value; - -typedef bool_constant false_type; -typedef bool_constant true_type; - -template -struct is_pointer : public false_type {}; - -template -struct is_pointer : public true_type {}; - -template -struct IteratorTraits { - typedef typename Iterator::value_type value_type; -}; - -template -struct IteratorTraits { - typedef T value_type; -}; - -template -struct IteratorTraits { - typedef T value_type; -}; - -#if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 -// The biggest signed integer type the compiler supports. -typedef __int64 BiggestInt; -#else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 -typedef long long BiggestInt; // NOLINT -#endif // GTEST_OS_WINDOWS - -// Utilities for char. - -// isspace(int ch) and friends accept an unsigned char or EOF. char -// may be signed, depending on the compiler (or compiler flags). -// Therefore we need to cast a char to unsigned char before calling -// isspace(), etc. - -inline bool IsAlpha(char ch) { - return isalpha(static_cast(ch)) != 0; -} -inline bool IsAlNum(char ch) { - return isalnum(static_cast(ch)) != 0; -} -inline bool IsDigit(char ch) { - return isdigit(static_cast(ch)) != 0; -} -inline bool IsLower(char ch) { - return islower(static_cast(ch)) != 0; -} -inline bool IsSpace(char ch) { - return isspace(static_cast(ch)) != 0; -} -inline bool IsUpper(char ch) { - return isupper(static_cast(ch)) != 0; -} -inline bool IsXDigit(char ch) { - return isxdigit(static_cast(ch)) != 0; -} - -inline char ToLower(char ch) { - return static_cast(tolower(static_cast(ch))); -} -inline char ToUpper(char ch) { - return static_cast(toupper(static_cast(ch))); -} - -// The testing::internal::posix namespace holds wrappers for common -// POSIX functions. These wrappers hide the differences between -// Windows/MSVC and POSIX systems. Since some compilers define these -// standard functions as macros, the wrapper cannot have the same name -// as the wrapped function. - -namespace posix { - -// Functions with a different name on Windows. - -#if GTEST_OS_WINDOWS - -typedef struct _stat StatStruct; - -# ifdef __BORLANDC__ -inline int IsATTY(int fd) { return isatty(fd); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE -inline int IsATTY(int /* fd */) { return 0; } -# else -inline int IsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE -inline int StrCaseCmp(const char* s1, const char* s2) { - return _stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ - -# if GTEST_OS_WINDOWS_MOBILE -inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } -// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this -// time and thus not defined there. -# else -inline int FileNo(FILE* file) { return _fileno(file); } -inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } -inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE - -#else - -typedef struct stat StatStruct; - -inline int FileNo(FILE* file) { return fileno(file); } -inline int IsATTY(int fd) { return isatty(fd); } -inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return strcasecmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -inline int RmDir(const char* dir) { return rmdir(dir); } -inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } - -#endif // GTEST_OS_WINDOWS - -// Functions deprecated by MSVC 8.0. - -#ifdef _MSC_VER -// Temporarily disable warning 4996 (deprecated function). -# pragma warning(push) -# pragma warning(disable:4996) -#endif - -inline const char* StrNCpy(char* dest, const char* src, size_t n) { - return strncpy(dest, src, n); -} - -// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and -// StrError() aren't needed on Windows CE at this time and thus not -// defined there. - -#if !GTEST_OS_WINDOWS_MOBILE -inline int ChDir(const char* dir) { return chdir(dir); } -#endif -inline FILE* FOpen(const char* path, const char* mode) { - return fopen(path, mode); -} -#if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { - return freopen(path, mode, stream); -} -inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } -#endif -inline int FClose(FILE* fp) { return fclose(fp); } -#if !GTEST_OS_WINDOWS_MOBILE -inline int Read(int fd, void* buf, unsigned int count) { - return static_cast(read(fd, buf, count)); -} -inline int Write(int fd, const void* buf, unsigned int count) { - return static_cast(write(fd, buf, count)); -} -inline int Close(int fd) { return close(fd); } -inline const char* StrError(int errnum) { return strerror(errnum); } -#endif -inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE - // We are on Windows CE, which has no environment variables. - return NULL; -#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) - // Environment variables which we programmatically clear will be set to the - // empty string rather than unset (NULL). Handle that case. - const char* const env = getenv(name); - return (env != NULL && env[0] != '\0') ? env : NULL; -#else - return getenv(name); -#endif -} - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif - -#if GTEST_OS_WINDOWS_MOBILE -// Windows CE has no C library. The abort() function is used in -// several places in Google Test. This implementation provides a reasonable -// imitation of standard behaviour. -void Abort(); -#else -inline void Abort() { abort(); } -#endif // GTEST_OS_WINDOWS_MOBILE - -} // namespace posix - -// The maximum number a BiggestInt can represent. This definition -// works no matter BiggestInt is represented in one's complement or -// two's complement. -// -// We cannot rely on numeric_limits in STL, as __int64 and long long -// are not part of standard C++ and numeric_limits doesn't need to be -// defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); - -// This template class serves as a compile-time function from size to -// type. It maps a size in bytes to a primitive type with that -// size. e.g. -// -// TypeWithSize<4>::UInt -// -// is typedef-ed to be unsigned int (unsigned integer made up of 4 -// bytes). -// -// Such functionality should belong to STL, but I cannot find it -// there. -// -// Google Test uses this class in the implementation of floating-point -// comparison. -// -// For now it only handles UInt (unsigned int) as that's all Google Test -// needs. Other types can be easily added in the future if need -// arises. -template -class TypeWithSize { - public: - // This prevents the user from using TypeWithSize with incorrect - // values of N. - typedef void UInt; -}; - -// The specialization for size 4. -template <> -class TypeWithSize<4> { - public: - // unsigned int has size 4 in both gcc and MSVC. - // - // As base/basictypes.h doesn't compile on Windows, we cannot use - // uint32, uint64, and etc here. - typedef int Int; - typedef unsigned int UInt; -}; - -// The specialization for size 8. -template <> -class TypeWithSize<8> { - public: - -#if GTEST_OS_WINDOWS - typedef __int64 Int; - typedef unsigned __int64 UInt; -#else - typedef long long Int; // NOLINT - typedef unsigned long long UInt; // NOLINT -#endif // GTEST_OS_WINDOWS -}; - -// Integer types of known sizes. -typedef TypeWithSize<4>::Int Int32; -typedef TypeWithSize<4>::UInt UInt32; -typedef TypeWithSize<8>::Int Int64; -typedef TypeWithSize<8>::UInt UInt64; -typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. - -// Utilities for command line flags and environment variables. - -// Macro for referencing flags. -#define GTEST_FLAG(name) FLAGS_gtest_##name - -// Macros for declaring flags. -#define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -#define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) -#define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::testing::internal::String GTEST_FLAG(name) - -// Macros for defining flags. -#define GTEST_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::String GTEST_FLAG(name) = (default_val) - -// Parses 'str' for a 32-bit signed integer. If successful, writes the result -// to *value and returns true; otherwise leaves *value unchanged and returns -// false. -// TODO(chandlerc): Find a better way to refactor flag and environment parsing -// out of both gtest-port.cc and gtest.cc to avoid exporting this utility -// function. -bool ParseInt32(const Message& src_text, const char* str, Int32* value); - -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromGTestEnv(const char* flag, bool default_val); -GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); -const char* StringFromGTestEnv(const char* flag, const char* default_val); - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -#if GTEST_OS_LINUX -# include -# include -# include -# include -#endif // GTEST_OS_LINUX - -#include -#include -#include -#include -#include - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file declares the String class and functions used internally by -// Google Test. They are subject to change without notice. They should not used -// by code external to Google Test. -// -// This header file is #included by . -// It should not be #included by other files. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ - -#ifdef __BORLANDC__ -// string.h is not guaranteed to provide strcpy on C++ Builder. -# include -#endif - -#include - -#include - -namespace testing { -namespace internal { - -// String - a UTF-8 string class. -// -// For historic reasons, we don't use std::string. -// -// TODO(wan@google.com): replace this class with std::string or -// implement it in terms of the latter. -// -// Note that String can represent both NULL and the empty string, -// while std::string cannot represent NULL. -// -// NULL and the empty string are considered different. NULL is less -// than anything (including the empty string) except itself. -// -// This class only provides minimum functionality necessary for -// implementing Google Test. We do not intend to implement a full-fledged -// string class here. -// -// Since the purpose of this class is to provide a substitute for -// std::string on platforms where it cannot be used, we define a copy -// constructor and assignment operators such that we don't need -// conditional compilation in a lot of places. -// -// In order to make the representation efficient, the d'tor of String -// is not virtual. Therefore DO NOT INHERIT FROM String. -class GTEST_API_ String { - public: - // Static utility methods - - // Returns the input enclosed in double quotes if it's not NULL; - // otherwise returns "(null)". For example, "\"Hello\"" is returned - // for input "Hello". - // - // This is useful for printing a C string in the syntax of a literal. - // - // Known issue: escape sequences are not handled yet. - static String ShowCStringQuoted(const char* c_str); - - // Clones a 0-terminated C string, allocating memory using new. The - // caller is responsible for deleting the return value using - // delete[]. Returns the cloned string, or NULL if the input is - // NULL. - // - // This is different from strdup() in string.h, which allocates - // memory using malloc(). - static const char* CloneCString(const char* c_str); - -#if GTEST_OS_WINDOWS_MOBILE - // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be - // able to pass strings to Win32 APIs on CE we need to convert them - // to 'Unicode', UTF-16. - - // Creates a UTF-16 wide string from the given ANSI string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the wide string, or NULL if the - // input is NULL. - // - // The wide string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static LPCWSTR AnsiToUtf16(const char* c_str); - - // Creates an ANSI string from the given wide string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the ANSI string, or NULL if the - // input is NULL. - // - // The returned string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static const char* Utf16ToAnsi(LPCWSTR utf16_str); -#endif - - // Compares two C strings. Returns true iff they have the same content. - // - // Unlike strcmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CStringEquals(const char* lhs, const char* rhs); - - // Converts a wide C string to a String using the UTF-8 encoding. - // NULL will be converted to "(null)". If an error occurred during - // the conversion, "(failed to convert from wide string)" is - // returned. - static String ShowWideCString(const wchar_t* wide_c_str); - - // Similar to ShowWideCString(), except that this function encloses - // the converted string in double quotes. - static String ShowWideCStringQuoted(const wchar_t* wide_c_str); - - // Compares two wide C strings. Returns true iff they have the same - // content. - // - // Unlike wcscmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - - // Compares two C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike strcasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); - - // Compares two wide C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. - static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs); - - // Formats a list of arguments to a String, using the same format - // spec string as for printf. - // - // We do not use the StringPrintf class as it is not universally - // available. - // - // The result is limited to 4096 characters (including the tailing - // 0). If 4096 characters are not enough to format the input, - // "" is returned. - static String Format(const char* format, ...); - - // C'tors - - // The default c'tor constructs a NULL string. - String() : c_str_(NULL), length_(0) {} - - // Constructs a String by cloning a 0-terminated C string. - String(const char* a_c_str) { // NOLINT - if (a_c_str == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(a_c_str, strlen(a_c_str)); - } - } - - // Constructs a String by copying a given number of chars from a - // buffer. E.g. String("hello", 3) creates the string "hel", - // String("a\0bcd", 4) creates "a\0bc", String(NULL, 0) creates "", - // and String(NULL, 1) results in access violation. - String(const char* buffer, size_t a_length) { - ConstructNonNull(buffer, a_length); - } - - // The copy c'tor creates a new copy of the string. The two - // String objects do not share content. - String(const String& str) : c_str_(NULL), length_(0) { *this = str; } - - // D'tor. String is intended to be a final class, so the d'tor - // doesn't need to be virtual. - ~String() { delete[] c_str_; } - - // Allows a String to be implicitly converted to an ::std::string or - // ::string, and vice versa. Converting a String containing a NULL - // pointer to ::std::string or ::string is undefined behavior. - // Converting a ::std::string or ::string containing an embedded NUL - // character to a String will result in the prefix up to the first - // NUL character. - String(const ::std::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::std::string() const { return ::std::string(c_str(), length()); } - -#if GTEST_HAS_GLOBAL_STRING - String(const ::string& str) { - ConstructNonNull(str.c_str(), str.length()); - } - - operator ::string() const { return ::string(c_str(), length()); } -#endif // GTEST_HAS_GLOBAL_STRING - - // Returns true iff this is an empty string (i.e. ""). - bool empty() const { return (c_str() != NULL) && (length() == 0); } - - // Compares this with another String. - // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0 - // if this is greater than rhs. - int Compare(const String& rhs) const; - - // Returns true iff this String equals the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator==(const char* a_c_str) const { return Compare(a_c_str) == 0; } - - // Returns true iff this String is less than the given String. A - // NULL string is considered less than "". - bool operator<(const String& rhs) const { return Compare(rhs) < 0; } - - // Returns true iff this String doesn't equal the given C string. A NULL - // string and a non-NULL string are considered not equal. - bool operator!=(const char* a_c_str) const { return !(*this == a_c_str); } - - // Returns true iff this String ends with the given suffix. *Any* - // String is considered to end with a NULL or empty suffix. - bool EndsWith(const char* suffix) const; - - // Returns true iff this String ends with the given suffix, not considering - // case. Any String is considered to end with a NULL or empty suffix. - bool EndsWithCaseInsensitive(const char* suffix) const; - - // Returns the length of the encapsulated string, or 0 if the - // string is NULL. - size_t length() const { return length_; } - - // Gets the 0-terminated C string this String object represents. - // The String object still owns the string. Therefore the caller - // should NOT delete the return value. - const char* c_str() const { return c_str_; } - - // Assigns a C string to this object. Self-assignment works. - const String& operator=(const char* a_c_str) { - return *this = String(a_c_str); - } - - // Assigns a String object to this object. Self-assignment works. - const String& operator=(const String& rhs) { - if (this != &rhs) { - delete[] c_str_; - if (rhs.c_str() == NULL) { - c_str_ = NULL; - length_ = 0; - } else { - ConstructNonNull(rhs.c_str(), rhs.length()); - } - } - - return *this; - } - - private: - // Constructs a non-NULL String from the given content. This - // function can only be called when c_str_ has not been allocated. - // ConstructNonNull(NULL, 0) results in an empty string (""). - // ConstructNonNull(NULL, non_zero) is undefined behavior. - void ConstructNonNull(const char* buffer, size_t a_length) { - char* const str = new char[a_length + 1]; - memcpy(str, buffer, a_length); - str[a_length] = '\0'; - c_str_ = str; - length_ = a_length; - } - - const char* c_str_; - size_t length_; -}; // class String - -// Streams a String to an ostream. Each '\0' character in the String -// is replaced with "\\0". -inline ::std::ostream& operator<<(::std::ostream& os, const String& str) { - if (str.c_str() == NULL) { - os << "(null)"; - } else { - const char* const c_str = str.c_str(); - for (size_t i = 0; i != str.length(); i++) { - if (c_str[i] == '\0') { - os << "\\0"; - } else { - os << c_str[i]; - } - } - } - return os; -} - -// Gets the content of the stringstream's buffer as a String. Each '\0' -// character in the buffer is replaced with "\\0". -GTEST_API_ String StringStreamToString(::std::stringstream* stream); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". - -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable); - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: keith.ray@gmail.com (Keith Ray) -// -// Google Test filepath utilities -// -// This header file declares classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included in . -// Do not include this header file separately! - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ - - -namespace testing { -namespace internal { - -// FilePath - a class for file and directory pathname manipulation which -// handles platform-specific conventions (like the pathname separator). -// Used for helper functions for naming files in a directory for xml output. -// Except for Set methods, all methods are const or static, which provides an -// "immutable value object" -- useful for peace of mind. -// A FilePath with a value ending in a path separator ("like/this/") represents -// a directory, otherwise it is assumed to represent a file. In either case, -// it may or may not represent an actual file or directory in the file system. -// Names are NOT checked for syntax correctness -- no checking for illegal -// characters, malformed paths, etc. - -class GTEST_API_ FilePath { - public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } - - explicit FilePath(const char* pathname) : pathname_(pathname) { - Normalize(); - } - - explicit FilePath(const String& pathname) : pathname_(pathname) { - Normalize(); - } - - FilePath& operator=(const FilePath& rhs) { - Set(rhs); - return *this; - } - - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } - - String ToString() const { return pathname_; } - const char* c_str() const { return pathname_.c_str(); } - - // Returns the current working directory, or "" if unsuccessful. - static FilePath GetCurrentDir(); - - // Given directory = "dir", base_name = "test", number = 0, - // extension = "xml", returns "dir/test.xml". If number is greater - // than zero (e.g., 12), returns "dir/test_12.xml". - // On Windows platform, uses \ as the separator rather than /. - static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension); - - // Given directory = "dir", relative_path = "test.xml", - // returns "dir/test.xml". - // On Windows, uses \ as the separator rather than /. - static FilePath ConcatPaths(const FilePath& directory, - const FilePath& relative_path); - - // Returns a pathname for a file that does not currently exist. The pathname - // will be directory/base_name.extension or - // directory/base_name_.extension if directory/base_name.extension - // already exists. The number will be incremented until a pathname is found - // that does not already exist. - // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. - // There could be a race condition if two or more processes are calling this - // function at the same time -- they could both pick the same filename. - static FilePath GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension); - - // Returns true iff the path is NULL or "". - bool IsEmpty() const { return c_str() == NULL || *c_str() == '\0'; } - - // If input name has a trailing separator character, removes it and returns - // the name, otherwise return the name string unmodified. - // On Windows platform, uses \ as the separator, other platforms use /. - FilePath RemoveTrailingPathSeparator() const; - - // Returns a copy of the FilePath with the directory part removed. - // Example: FilePath("path/to/file").RemoveDirectoryName() returns - // FilePath("file"). If there is no directory part ("just_a_file"), it returns - // the FilePath unmodified. If there is no file part ("just_a_dir/") it - // returns an empty FilePath (""). - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveDirectoryName() const; - - // RemoveFileName returns the directory path with the filename removed. - // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". - // If the FilePath is "a_file" or "/a_file", RemoveFileName returns - // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does - // not have a file, like "just/a/dir/", it returns the FilePath unmodified. - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveFileName() const; - - // Returns a copy of the FilePath with the case-insensitive extension removed. - // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns - // FilePath("dir/file"). If a case-insensitive extension is not - // found, returns a copy of the original FilePath. - FilePath RemoveExtension(const char* extension) const; - - // Creates directories so that path exists. Returns true if successful or if - // the directories already exist; returns false if unable to create - // directories for any reason. Will also return false if the FilePath does - // not represent a directory (that is, it doesn't end with a path separator). - bool CreateDirectoriesRecursively() const; - - // Create the directory so that path exists. Returns true if successful or - // if the directory already exists; returns false if unable to create the - // directory for any reason, including if the parent directory does not - // exist. Not named "CreateDirectory" because that's a macro on Windows. - bool CreateFolder() const; - - // Returns true if FilePath describes something in the file-system, - // either a file, directory, or whatever, and that something exists. - bool FileOrDirectoryExists() const; - - // Returns true if pathname describes a directory in the file-system - // that exists. - bool DirectoryExists() const; - - // Returns true if FilePath ends with a path separator, which indicates that - // it is intended to represent a directory. Returns false otherwise. - // This does NOT check that a directory (or file) actually exists. - bool IsDirectory() const; - - // Returns true if pathname describes a root directory. (Windows has one - // root directory per disk drive.) - bool IsRootDirectory() const; - - // Returns true if pathname describes an absolute path. - bool IsAbsolutePath() const; - - private: - // Replaces multiple consecutive separators with a single separator. - // For example, "bar///foo" becomes "bar/foo". Does not eliminate other - // redundancies that might be in a pathname involving "." or "..". - // - // A pathname with multiple consecutive separators may occur either through - // user error or as a result of some scripts or APIs that generate a pathname - // with a trailing separator. On other platforms the same API or script - // may NOT generate a pathname with a trailing "/". Then elsewhere that - // pathname may have another "/" and pathname components added to it, - // without checking for the separator already being there. - // The script language and operating system may allow paths like "foo//bar" - // but some of the functions in FilePath will not handle that correctly. In - // particular, RemoveTrailingPathSeparator() only removes one separator, and - // it is called in CreateDirectoriesRecursively() assuming that it will change - // a pathname from directory syntax (trailing separator) to filename syntax. - // - // On Windows this method also replaces the alternate path separator '/' with - // the primary path separator '\\', so that for example "bar\\/\\foo" becomes - // "bar\\foo". - - void Normalize(); - - // Returns a pointer to the last occurence of a valid path separator in - // the FilePath. On Windows, for example, both '/' and '\' are valid path - // separators. Returns NULL if no path separator was found. - const char* FindLastPathSeparator() const; - - String pathname_; -}; // class FilePath - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -// This file was GENERATED by command: -// pump.py gtest-type-util.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Type utilities needed for implementing typed and type-parameterized -// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently we support at most 50 types in a list, and at most 50 -// type-parameterized tests in one type-parameterized test case. -// Please contact googletestframework@googlegroups.com if you need -// more. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - - -// #ifdef __GNUC__ is too general here. It is possible to use gcc without using -// libstdc++ (which is where cxxabi.h comes from). -# ifdef __GLIBCXX__ -# include -# elif defined(__HP_aCC) -# include -# endif // __GLIBCXX__ - -namespace testing { -namespace internal { - -// GetTypeName() returns a human-readable name of type T. -// NB: This function is also used in Google Mock, so don't move it inside of -// the typed-test-only section below. -template -String GetTypeName() { -# if GTEST_HAS_RTTI - - const char* const name = typeid(T).name(); -# if defined(__GLIBCXX__) || defined(__HP_aCC) - int status = 0; - // gcc's implementation of typeid(T).name() mangles the type name, - // so we have to demangle it. -# ifdef __GLIBCXX__ - using abi::__cxa_demangle; -# endif // __GLIBCXX__ - char* const readable_name = __cxa_demangle(name, 0, 0, &status); - const String name_str(status == 0 ? readable_name : name); - free(readable_name); - return name_str; -# else - return name; -# endif // __GLIBCXX__ || __HP_aCC - -# else - - return ""; - -# endif // GTEST_HAS_RTTI -} - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// AssertyTypeEq::type is defined iff T1 and T2 are the same -// type. This can be used as a compile-time assertion to ensure that -// two types are equal. - -template -struct AssertTypeEq; - -template -struct AssertTypeEq { - typedef bool type; -}; - -// A unique type used as the default value for the arguments of class -// template Types. This allows us to simulate variadic templates -// (e.g. Types, Type, and etc), which C++ doesn't -// support directly. -struct None {}; - -// The following family of struct and struct templates are used to -// represent type lists. In particular, TypesN -// represents a type list with N types (T1, T2, ..., and TN) in it. -// Except for Types0, every struct in the family has two member types: -// Head for the first type in the list, and Tail for the rest of the -// list. - -// The empty type list. -struct Types0 {}; - -// Type lists of length 1, 2, 3, and so on. - -template -struct Types1 { - typedef T1 Head; - typedef Types0 Tail; -}; -template -struct Types2 { - typedef T1 Head; - typedef Types1 Tail; -}; - -template -struct Types3 { - typedef T1 Head; - typedef Types2 Tail; -}; - -template -struct Types4 { - typedef T1 Head; - typedef Types3 Tail; -}; - -template -struct Types5 { - typedef T1 Head; - typedef Types4 Tail; -}; - -template -struct Types6 { - typedef T1 Head; - typedef Types5 Tail; -}; - -template -struct Types7 { - typedef T1 Head; - typedef Types6 Tail; -}; - -template -struct Types8 { - typedef T1 Head; - typedef Types7 Tail; -}; - -template -struct Types9 { - typedef T1 Head; - typedef Types8 Tail; -}; - -template -struct Types10 { - typedef T1 Head; - typedef Types9 Tail; -}; - -template -struct Types11 { - typedef T1 Head; - typedef Types10 Tail; -}; - -template -struct Types12 { - typedef T1 Head; - typedef Types11 Tail; -}; - -template -struct Types13 { - typedef T1 Head; - typedef Types12 Tail; -}; - -template -struct Types14 { - typedef T1 Head; - typedef Types13 Tail; -}; - -template -struct Types15 { - typedef T1 Head; - typedef Types14 Tail; -}; - -template -struct Types16 { - typedef T1 Head; - typedef Types15 Tail; -}; - -template -struct Types17 { - typedef T1 Head; - typedef Types16 Tail; -}; - -template -struct Types18 { - typedef T1 Head; - typedef Types17 Tail; -}; - -template -struct Types19 { - typedef T1 Head; - typedef Types18 Tail; -}; - -template -struct Types20 { - typedef T1 Head; - typedef Types19 Tail; -}; - -template -struct Types21 { - typedef T1 Head; - typedef Types20 Tail; -}; - -template -struct Types22 { - typedef T1 Head; - typedef Types21 Tail; -}; - -template -struct Types23 { - typedef T1 Head; - typedef Types22 Tail; -}; - -template -struct Types24 { - typedef T1 Head; - typedef Types23 Tail; -}; - -template -struct Types25 { - typedef T1 Head; - typedef Types24 Tail; -}; - -template -struct Types26 { - typedef T1 Head; - typedef Types25 Tail; -}; - -template -struct Types27 { - typedef T1 Head; - typedef Types26 Tail; -}; - -template -struct Types28 { - typedef T1 Head; - typedef Types27 Tail; -}; - -template -struct Types29 { - typedef T1 Head; - typedef Types28 Tail; -}; - -template -struct Types30 { - typedef T1 Head; - typedef Types29 Tail; -}; - -template -struct Types31 { - typedef T1 Head; - typedef Types30 Tail; -}; - -template -struct Types32 { - typedef T1 Head; - typedef Types31 Tail; -}; - -template -struct Types33 { - typedef T1 Head; - typedef Types32 Tail; -}; - -template -struct Types34 { - typedef T1 Head; - typedef Types33 Tail; -}; - -template -struct Types35 { - typedef T1 Head; - typedef Types34 Tail; -}; - -template -struct Types36 { - typedef T1 Head; - typedef Types35 Tail; -}; - -template -struct Types37 { - typedef T1 Head; - typedef Types36 Tail; -}; - -template -struct Types38 { - typedef T1 Head; - typedef Types37 Tail; -}; - -template -struct Types39 { - typedef T1 Head; - typedef Types38 Tail; -}; - -template -struct Types40 { - typedef T1 Head; - typedef Types39 Tail; -}; - -template -struct Types41 { - typedef T1 Head; - typedef Types40 Tail; -}; - -template -struct Types42 { - typedef T1 Head; - typedef Types41 Tail; -}; - -template -struct Types43 { - typedef T1 Head; - typedef Types42 Tail; -}; - -template -struct Types44 { - typedef T1 Head; - typedef Types43 Tail; -}; - -template -struct Types45 { - typedef T1 Head; - typedef Types44 Tail; -}; - -template -struct Types46 { - typedef T1 Head; - typedef Types45 Tail; -}; - -template -struct Types47 { - typedef T1 Head; - typedef Types46 Tail; -}; - -template -struct Types48 { - typedef T1 Head; - typedef Types47 Tail; -}; - -template -struct Types49 { - typedef T1 Head; - typedef Types48 Tail; -}; - -template -struct Types50 { - typedef T1 Head; - typedef Types49 Tail; -}; - - -} // namespace internal - -// We don't want to require the users to write TypesN<...> directly, -// as that would require them to count the length. Types<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Types -// will appear as Types in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Types, and Google Test will translate -// that to TypesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Types template. -template -struct Types { - typedef internal::Types50 type; -}; - -template <> -struct Types { - typedef internal::Types0 type; -}; -template -struct Types { - typedef internal::Types1 type; -}; -template -struct Types { - typedef internal::Types2 type; -}; -template -struct Types { - typedef internal::Types3 type; -}; -template -struct Types { - typedef internal::Types4 type; -}; -template -struct Types { - typedef internal::Types5 type; -}; -template -struct Types { - typedef internal::Types6 type; -}; -template -struct Types { - typedef internal::Types7 type; -}; -template -struct Types { - typedef internal::Types8 type; -}; -template -struct Types { - typedef internal::Types9 type; -}; -template -struct Types { - typedef internal::Types10 type; -}; -template -struct Types { - typedef internal::Types11 type; -}; -template -struct Types { - typedef internal::Types12 type; -}; -template -struct Types { - typedef internal::Types13 type; -}; -template -struct Types { - typedef internal::Types14 type; -}; -template -struct Types { - typedef internal::Types15 type; -}; -template -struct Types { - typedef internal::Types16 type; -}; -template -struct Types { - typedef internal::Types17 type; -}; -template -struct Types { - typedef internal::Types18 type; -}; -template -struct Types { - typedef internal::Types19 type; -}; -template -struct Types { - typedef internal::Types20 type; -}; -template -struct Types { - typedef internal::Types21 type; -}; -template -struct Types { - typedef internal::Types22 type; -}; -template -struct Types { - typedef internal::Types23 type; -}; -template -struct Types { - typedef internal::Types24 type; -}; -template -struct Types { - typedef internal::Types25 type; -}; -template -struct Types { - typedef internal::Types26 type; -}; -template -struct Types { - typedef internal::Types27 type; -}; -template -struct Types { - typedef internal::Types28 type; -}; -template -struct Types { - typedef internal::Types29 type; -}; -template -struct Types { - typedef internal::Types30 type; -}; -template -struct Types { - typedef internal::Types31 type; -}; -template -struct Types { - typedef internal::Types32 type; -}; -template -struct Types { - typedef internal::Types33 type; -}; -template -struct Types { - typedef internal::Types34 type; -}; -template -struct Types { - typedef internal::Types35 type; -}; -template -struct Types { - typedef internal::Types36 type; -}; -template -struct Types { - typedef internal::Types37 type; -}; -template -struct Types { - typedef internal::Types38 type; -}; -template -struct Types { - typedef internal::Types39 type; -}; -template -struct Types { - typedef internal::Types40 type; -}; -template -struct Types { - typedef internal::Types41 type; -}; -template -struct Types { - typedef internal::Types42 type; -}; -template -struct Types { - typedef internal::Types43 type; -}; -template -struct Types { - typedef internal::Types44 type; -}; -template -struct Types { - typedef internal::Types45 type; -}; -template -struct Types { - typedef internal::Types46 type; -}; -template -struct Types { - typedef internal::Types47 type; -}; -template -struct Types { - typedef internal::Types48 type; -}; -template -struct Types { - typedef internal::Types49 type; -}; - -namespace internal { - -# define GTEST_TEMPLATE_ template class - -// The template "selector" struct TemplateSel is used to -// represent Tmpl, which must be a class template with one type -// parameter, as a type. TemplateSel::Bind::type is defined -// as the type Tmpl. This allows us to actually instantiate the -// template "selected" by TemplateSel. -// -// This trick is necessary for simulating typedef for class templates, -// which C++ doesn't support directly. -template -struct TemplateSel { - template - struct Bind { - typedef Tmpl type; - }; -}; - -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type - -// A unique struct template used as the default value for the -// arguments of class template Templates. This allows us to simulate -// variadic templates (e.g. Templates, Templates, -// and etc), which C++ doesn't support directly. -template -struct NoneT {}; - -// The following family of struct and struct templates are used to -// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except -// for Templates0, every struct in the family has two member types: -// Head for the selector of the first template in the list, and Tail -// for the rest of the list. - -// The empty template list. -struct Templates0 {}; - -// Template lists of length 1, 2, 3, and so on. - -template -struct Templates1 { - typedef TemplateSel Head; - typedef Templates0 Tail; -}; -template -struct Templates2 { - typedef TemplateSel Head; - typedef Templates1 Tail; -}; - -template -struct Templates3 { - typedef TemplateSel Head; - typedef Templates2 Tail; -}; - -template -struct Templates4 { - typedef TemplateSel Head; - typedef Templates3 Tail; -}; - -template -struct Templates5 { - typedef TemplateSel Head; - typedef Templates4 Tail; -}; - -template -struct Templates6 { - typedef TemplateSel Head; - typedef Templates5 Tail; -}; - -template -struct Templates7 { - typedef TemplateSel Head; - typedef Templates6 Tail; -}; - -template -struct Templates8 { - typedef TemplateSel Head; - typedef Templates7 Tail; -}; - -template -struct Templates9 { - typedef TemplateSel Head; - typedef Templates8 Tail; -}; - -template -struct Templates10 { - typedef TemplateSel Head; - typedef Templates9 Tail; -}; - -template -struct Templates11 { - typedef TemplateSel Head; - typedef Templates10 Tail; -}; - -template -struct Templates12 { - typedef TemplateSel Head; - typedef Templates11 Tail; -}; - -template -struct Templates13 { - typedef TemplateSel Head; - typedef Templates12 Tail; -}; - -template -struct Templates14 { - typedef TemplateSel Head; - typedef Templates13 Tail; -}; - -template -struct Templates15 { - typedef TemplateSel Head; - typedef Templates14 Tail; -}; - -template -struct Templates16 { - typedef TemplateSel Head; - typedef Templates15 Tail; -}; - -template -struct Templates17 { - typedef TemplateSel Head; - typedef Templates16 Tail; -}; - -template -struct Templates18 { - typedef TemplateSel Head; - typedef Templates17 Tail; -}; - -template -struct Templates19 { - typedef TemplateSel Head; - typedef Templates18 Tail; -}; - -template -struct Templates20 { - typedef TemplateSel Head; - typedef Templates19 Tail; -}; - -template -struct Templates21 { - typedef TemplateSel Head; - typedef Templates20 Tail; -}; - -template -struct Templates22 { - typedef TemplateSel Head; - typedef Templates21 Tail; -}; - -template -struct Templates23 { - typedef TemplateSel Head; - typedef Templates22 Tail; -}; - -template -struct Templates24 { - typedef TemplateSel Head; - typedef Templates23 Tail; -}; - -template -struct Templates25 { - typedef TemplateSel Head; - typedef Templates24 Tail; -}; - -template -struct Templates26 { - typedef TemplateSel Head; - typedef Templates25 Tail; -}; - -template -struct Templates27 { - typedef TemplateSel Head; - typedef Templates26 Tail; -}; - -template -struct Templates28 { - typedef TemplateSel Head; - typedef Templates27 Tail; -}; - -template -struct Templates29 { - typedef TemplateSel Head; - typedef Templates28 Tail; -}; - -template -struct Templates30 { - typedef TemplateSel Head; - typedef Templates29 Tail; -}; - -template -struct Templates31 { - typedef TemplateSel Head; - typedef Templates30 Tail; -}; - -template -struct Templates32 { - typedef TemplateSel Head; - typedef Templates31 Tail; -}; - -template -struct Templates33 { - typedef TemplateSel Head; - typedef Templates32 Tail; -}; - -template -struct Templates34 { - typedef TemplateSel Head; - typedef Templates33 Tail; -}; - -template -struct Templates35 { - typedef TemplateSel Head; - typedef Templates34 Tail; -}; - -template -struct Templates36 { - typedef TemplateSel Head; - typedef Templates35 Tail; -}; - -template -struct Templates37 { - typedef TemplateSel Head; - typedef Templates36 Tail; -}; - -template -struct Templates38 { - typedef TemplateSel Head; - typedef Templates37 Tail; -}; - -template -struct Templates39 { - typedef TemplateSel Head; - typedef Templates38 Tail; -}; - -template -struct Templates40 { - typedef TemplateSel Head; - typedef Templates39 Tail; -}; - -template -struct Templates41 { - typedef TemplateSel Head; - typedef Templates40 Tail; -}; - -template -struct Templates42 { - typedef TemplateSel Head; - typedef Templates41 Tail; -}; - -template -struct Templates43 { - typedef TemplateSel Head; - typedef Templates42 Tail; -}; - -template -struct Templates44 { - typedef TemplateSel Head; - typedef Templates43 Tail; -}; - -template -struct Templates45 { - typedef TemplateSel Head; - typedef Templates44 Tail; -}; - -template -struct Templates46 { - typedef TemplateSel Head; - typedef Templates45 Tail; -}; - -template -struct Templates47 { - typedef TemplateSel Head; - typedef Templates46 Tail; -}; - -template -struct Templates48 { - typedef TemplateSel Head; - typedef Templates47 Tail; -}; - -template -struct Templates49 { - typedef TemplateSel Head; - typedef Templates48 Tail; -}; - -template -struct Templates50 { - typedef TemplateSel Head; - typedef Templates49 Tail; -}; - - -// We don't want to require the users to write TemplatesN<...> directly, -// as that would require them to count the length. Templates<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Templates -// will appear as Templates in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Templates, and Google Test will translate -// that to TemplatesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Templates template. -template -struct Templates { - typedef Templates50 type; -}; - -template <> -struct Templates { - typedef Templates0 type; -}; -template -struct Templates { - typedef Templates1 type; -}; -template -struct Templates { - typedef Templates2 type; -}; -template -struct Templates { - typedef Templates3 type; -}; -template -struct Templates { - typedef Templates4 type; -}; -template -struct Templates { - typedef Templates5 type; -}; -template -struct Templates { - typedef Templates6 type; -}; -template -struct Templates { - typedef Templates7 type; -}; -template -struct Templates { - typedef Templates8 type; -}; -template -struct Templates { - typedef Templates9 type; -}; -template -struct Templates { - typedef Templates10 type; -}; -template -struct Templates { - typedef Templates11 type; -}; -template -struct Templates { - typedef Templates12 type; -}; -template -struct Templates { - typedef Templates13 type; -}; -template -struct Templates { - typedef Templates14 type; -}; -template -struct Templates { - typedef Templates15 type; -}; -template -struct Templates { - typedef Templates16 type; -}; -template -struct Templates { - typedef Templates17 type; -}; -template -struct Templates { - typedef Templates18 type; -}; -template -struct Templates { - typedef Templates19 type; -}; -template -struct Templates { - typedef Templates20 type; -}; -template -struct Templates { - typedef Templates21 type; -}; -template -struct Templates { - typedef Templates22 type; -}; -template -struct Templates { - typedef Templates23 type; -}; -template -struct Templates { - typedef Templates24 type; -}; -template -struct Templates { - typedef Templates25 type; -}; -template -struct Templates { - typedef Templates26 type; -}; -template -struct Templates { - typedef Templates27 type; -}; -template -struct Templates { - typedef Templates28 type; -}; -template -struct Templates { - typedef Templates29 type; -}; -template -struct Templates { - typedef Templates30 type; -}; -template -struct Templates { - typedef Templates31 type; -}; -template -struct Templates { - typedef Templates32 type; -}; -template -struct Templates { - typedef Templates33 type; -}; -template -struct Templates { - typedef Templates34 type; -}; -template -struct Templates { - typedef Templates35 type; -}; -template -struct Templates { - typedef Templates36 type; -}; -template -struct Templates { - typedef Templates37 type; -}; -template -struct Templates { - typedef Templates38 type; -}; -template -struct Templates { - typedef Templates39 type; -}; -template -struct Templates { - typedef Templates40 type; -}; -template -struct Templates { - typedef Templates41 type; -}; -template -struct Templates { - typedef Templates42 type; -}; -template -struct Templates { - typedef Templates43 type; -}; -template -struct Templates { - typedef Templates44 type; -}; -template -struct Templates { - typedef Templates45 type; -}; -template -struct Templates { - typedef Templates46 type; -}; -template -struct Templates { - typedef Templates47 type; -}; -template -struct Templates { - typedef Templates48 type; -}; -template -struct Templates { - typedef Templates49 type; -}; - -// The TypeList template makes it possible to use either a single type -// or a Types<...> list in TYPED_TEST_CASE() and -// INSTANTIATE_TYPED_TEST_CASE_P(). - -template -struct TypeList { typedef Types1 type; }; - -template -struct TypeList > { - typedef typename Types::type type; -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - -// Due to C++ preprocessor weirdness, we need double indirection to -// concatenate two tokens when one of them is __LINE__. Writing -// -// foo ## __LINE__ -// -// will result in the token foo__LINE__, instead of foo followed by -// the current line number. For more details, see -// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 -#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar - -// Google Test defines the testing::Message class to allow construction of -// test messages via the << operator. The idea is that anything -// streamable to std::ostream can be streamed to a testing::Message. -// This allows a user to use his own types in Google Test assertions by -// overloading the << operator. -// -// util/gtl/stl_logging-inl.h overloads << for STL containers. These -// overloads cannot be defined in the std namespace, as that will be -// undefined behavior. Therefore, they are defined in the global -// namespace instead. -// -// C++'s symbol lookup rule (i.e. Koenig lookup) says that these -// overloads are visible in either the std namespace or the global -// namespace, but not other namespaces, including the testing -// namespace which Google Test's Message class is in. -// -// To allow STL containers (and other types that has a << operator -// defined in the global namespace) to be used in Google Test assertions, -// testing::Message must access the custom << operator from the global -// namespace. Hence this helper function. -// -// Note: Jeffrey Yasskin suggested an alternative fix by "using -// ::operator<<;" in the definition of Message's operator<<. That fix -// doesn't require a helper function, but unfortunately doesn't -// compile with MSVC. -template -inline void GTestStreamToHelper(std::ostream* os, const T& val) { - *os << val; -} - -class ProtocolMessage; -namespace proto2 { class Message; } - -namespace testing { - -// Forward declarations. - -class AssertionResult; // Result of an assertion. -class Message; // Represents a failure message. -class Test; // Represents a test. -class TestInfo; // Information about a test. -class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test cases. - -template -::std::string PrintToString(const T& value); - -namespace internal { - -struct TraceInfo; // Information about a trace point. -class ScopedTrace; // Implements scoped trace. -class TestInfoImpl; // Opaque implementation of TestInfo -class UnitTestImpl; // Opaque implementation of UnitTest - -// How many times InitGoogleTest() has been called. -extern int g_init_gtest_count; - -// The text used in failure messages to indicate the start of the -// stack trace. -GTEST_API_ extern const char kStackTraceMarker[]; - -// A secret type that Google Test users don't know about. It has no -// definition on purpose. Therefore it's impossible to create a -// Secret object, which is what we want. -class Secret; - -// Two overloaded helpers for checking at compile time whether an -// expression is a null pointer literal (i.e. NULL or any 0-valued -// compile-time integral constant). Their return values have -// different sizes, so we can use sizeof() to test which version is -// picked by the compiler. These helpers have no implementations, as -// we only need their signatures. -// -// Given IsNullLiteralHelper(x), the compiler will pick the first -// version if x can be implicitly converted to Secret*, and pick the -// second version otherwise. Since Secret is a secret and incomplete -// type, the only expression a user can write that has type Secret* is -// a null pointer literal. Therefore, we know that x is a null -// pointer literal if and only if the first version is picked by the -// compiler. -char IsNullLiteralHelper(Secret* p); -char (&IsNullLiteralHelper(...))[2]; // NOLINT - -// A compile-time bool constant that is true if and only if x is a -// null pointer literal (i.e. NULL or any 0-valued compile-time -// integral constant). -#ifdef GTEST_ELLIPSIS_NEEDS_POD_ -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_IS_NULL_LITERAL_(x) false -#else -# define GTEST_IS_NULL_LITERAL_(x) \ - (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) -#endif // GTEST_ELLIPSIS_NEEDS_POD_ - -// Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ String AppendUserMessage(const String& gtest_msg, - const Message& user_msg); - -// A helper class for creating scoped traces in user programs. -class GTEST_API_ ScopedTrace { - public: - // The c'tor pushes the given source file location and message onto - // a trace stack maintained by Google Test. - ScopedTrace(const char* file, int line, const Message& message); - - // The d'tor pops the info pushed by the c'tor. - // - // Note that the d'tor is not virtual in order to be efficient. - // Don't inherit from ScopedTrace! - ~ScopedTrace(); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); -} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its - // c'tor and d'tor. Therefore it doesn't - // need to be used otherwise. - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared here but defined in gtest.h, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable); - -// The Symbian compiler has a bug that prevents it from selecting the -// correct overload of FormatForComparisonFailureMessage (see below) -// unless we pass the first argument by reference. If we do that, -// however, Visual Age C++ 10.1 generates a compiler error. Therefore -// we only apply the work-around for Symbian. -#if defined(__SYMBIAN32__) -# define GTEST_CREF_WORKAROUND_ const& -#else -# define GTEST_CREF_WORKAROUND_ -#endif - -// When this operand is a const char* or char*, if the other operand -// is a ::std::string or ::string, we print this operand as a C string -// rather than a pointer (we do the same for wide strings); otherwise -// we print it as a pointer to be safe. - -// This internal macro is used to avoid duplicated code. -#define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ -inline String FormatForComparisonFailureMessage(\ - operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -}\ -inline String FormatForComparisonFailureMessage(\ - const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ - const operand2_type& /*operand2*/) {\ - return operand1_printer(str);\ -} - -GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) -#if GTEST_HAS_STD_WSTRING -GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_STRING -GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) -#endif // GTEST_HAS_GLOBAL_STRING -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) -#endif // GTEST_HAS_GLOBAL_WSTRING - -#undef GTEST_FORMAT_IMPL_ - -// The next four overloads handle the case where the operand being -// printed is a char/wchar_t pointer and the other operand is not a -// string/wstring object. In such cases, we just print the operand as -// a pointer to be safe. -#define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ - template \ - String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \ - const T&) { \ - return PrintToString(static_cast(p)); \ - } - -GTEST_FORMAT_CHAR_PTR_IMPL_(char) -GTEST_FORMAT_CHAR_PTR_IMPL_(const char) -GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t) -GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) - -#undef GTEST_FORMAT_CHAR_PTR_IMPL_ - -// Constructs and returns the message for an equality assertion -// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. -// -// The first four parameters are the expressions used in the assertion -// and their values, as strings. For example, for ASSERT_EQ(foo, bar) -// where foo is 5 and bar is 6, we have: -// -// expected_expression: "foo" -// actual_expression: "bar" -// expected_value: "5" -// actual_value: "6" -// -// The ignoring_case parameter is true iff the assertion is a -// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will -// be inserted into the message. -GTEST_API_ AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const String& expected_value, - const String& actual_value, - bool ignoring_case); - -// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -GTEST_API_ String GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); - -// This template class represents an IEEE floating-point number -// (either single-precision or double-precision, depending on the -// template parameters). -// -// The purpose of this class is to do more sophisticated number -// comparison. (Due to round-off error, etc, it's very unlikely that -// two floating-points will be equal exactly. Hence a naive -// comparison by the == operation often doesn't work.) -// -// Format of IEEE floating-point: -// -// The most-significant bit being the leftmost, an IEEE -// floating-point looks like -// -// sign_bit exponent_bits fraction_bits -// -// Here, sign_bit is a single bit that designates the sign of the -// number. -// -// For float, there are 8 exponent bits and 23 fraction bits. -// -// For double, there are 11 exponent bits and 52 fraction bits. -// -// More details can be found at -// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -template -class FloatingPoint { - public: - // Defines the unsigned integer type that has the same size as the - // floating point number. - typedef typename TypeWithSize::UInt Bits; - - // Constants. - - // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); - - // # of fraction bits in a number. - static const size_t kFractionBitCount = - std::numeric_limits::digits - 1; - - // # of exponent bits in a number. - static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; - - // The mask for the sign bit. - static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); - - // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast(0) >> (kExponentBitCount + 1); - - // The mask for the exponent bits. - static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); - - // How many ULP's (Units in the Last Place) we want to tolerate when - // comparing two numbers. The larger the value, the more error we - // allow. A 0 value means that two numbers must be exactly the same - // to be considered equal. - // - // The maximum error of a single floating-point operation is 0.5 - // units in the last place. On Intel CPU's, all floating-point - // calculations are done with 80-bit precision, while double has 64 - // bits. Therefore, 4 should be enough for ordinary use. - // - // See the following article for more details on ULP: - // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. - static const size_t kMaxUlps = 4; - - // Constructs a FloatingPoint from a raw floating-point number. - // - // On an Intel CPU, passing a non-normalized NAN (Not a Number) - // around may change its bits, although the new value is guaranteed - // to be also a NAN. Therefore, don't expect this constructor to - // preserve the bits in x when x is a NAN. - explicit FloatingPoint(const RawType& x) { u_.value_ = x; } - - // Static methods - - // Reinterprets a bit pattern as a floating-point number. - // - // This function is needed to test the AlmostEquals() method. - static RawType ReinterpretBits(const Bits bits) { - FloatingPoint fp(0); - fp.u_.bits_ = bits; - return fp.u_.value_; - } - - // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } - - // Non-static methods - - // Returns the bits that represents this number. - const Bits &bits() const { return u_.bits_; } - - // Returns the exponent bits of this number. - Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } - - // Returns the fraction bits of this number. - Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } - - // Returns the sign bit of this number. - Bits sign_bit() const { return kSignBitMask & u_.bits_; } - - // Returns true iff this is NAN (not a number). - bool is_nan() const { - // It's a NAN if the exponent bits are all ones and the fraction - // bits are not entirely zeros. - return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); - } - - // Returns true iff this number is at most kMaxUlps ULP's away from - // rhs. In particular, this function: - // - // - returns false if either number is (or both are) NAN. - // - treats really large numbers as almost equal to infinity. - // - thinks +0.0 and -0.0 are 0 DLP's apart. - bool AlmostEquals(const FloatingPoint& rhs) const { - // The IEEE standard says that any comparison operation involving - // a NAN must return false. - if (is_nan() || rhs.is_nan()) return false; - - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; - } - - private: - // The data type used to store the actual floating-point number. - union FloatingPointUnion { - RawType value_; // The raw floating-point number. - Bits bits_; // The bits that represent the number. - }; - - // Converts an integer from the sign-and-magnitude representation to - // the biased representation. More precisely, let N be 2 to the - // power of (kBitCount - 1), an integer x is represented by the - // unsigned number x + N. - // - // For instance, - // - // -N + 1 (the most negative number representable using - // sign-and-magnitude) is represented by 1; - // 0 is represented by N; and - // N - 1 (the biggest number representable using - // sign-and-magnitude) is represented by 2N - 1. - // - // Read http://en.wikipedia.org/wiki/Signed_number_representations - // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { - if (kSignBitMask & sam) { - // sam represents a negative number. - return ~sam + 1; - } else { - // sam represents a positive number. - return kSignBitMask | sam; - } - } - - // Given two numbers in the sign-and-magnitude representation, - // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { - const Bits biased1 = SignAndMagnitudeToBiased(sam1); - const Bits biased2 = SignAndMagnitudeToBiased(sam2); - return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); - } - - FloatingPointUnion u_; -}; - -// Typedefs the instances of the FloatingPoint template class that we -// care to use. -typedef FloatingPoint Float; -typedef FloatingPoint Double; - -// In order to catch the mistake of putting tests that use different -// test fixture classes in the same test case, we need to assign -// unique IDs to fixture classes and compare them. The TypeId type is -// used to hold such IDs. The user should treat TypeId as an opaque -// type: the only operation allowed on TypeId values is to compare -// them for equality using the == operator. -typedef const void* TypeId; - -template -class TypeIdHelper { - public: - // dummy_ must not have a const type. Otherwise an overly eager - // compiler (e.g. MSVC 7.1 & 8.0) may try to merge - // TypeIdHelper::dummy_ for different Ts as an "optimization". - static bool dummy_; -}; - -template -bool TypeIdHelper::dummy_ = false; - -// GetTypeId() returns the ID of type T. Different values will be -// returned for different types. Calling the function twice with the -// same type argument is guaranteed to return the same ID. -template -TypeId GetTypeId() { - // The compiler is required to allocate a different - // TypeIdHelper::dummy_ variable for each T used to instantiate - // the template. Therefore, the address of dummy_ is guaranteed to - // be unique. - return &(TypeIdHelper::dummy_); -} - -// Returns the type ID of ::testing::Test. Always call this instead -// of GetTypeId< ::testing::Test>() to get the type ID of -// ::testing::Test, as the latter may give the wrong result due to a -// suspected linker bug when compiling Google Test as a Mac OS X -// framework. -GTEST_API_ TypeId GetTestTypeId(); - -// Defines the abstract factory interface that creates instances -// of a Test object. -class TestFactoryBase { - public: - virtual ~TestFactoryBase() {} - - // Creates a test instance to run. The instance is both created and destroyed - // within TestInfoImpl::Run() - virtual Test* CreateTest() = 0; - - protected: - TestFactoryBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); -}; - -// This class provides implementation of TeastFactoryBase interface. -// It is used in TEST and TEST_F macros. -template -class TestFactoryImpl : public TestFactoryBase { - public: - virtual Test* CreateTest() { return new TestClass; } -}; - -#if GTEST_OS_WINDOWS - -// Predicate-formatters for implementing the HRESULT checking macros -// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} -// We pass a long instead of HRESULT to avoid causing an -// include dependency for the HRESULT type. -GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, - long hr); // NOLINT -GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, - long hr); // NOLINT - -#endif // GTEST_OS_WINDOWS - -// Types of SetUpTestCase() and TearDownTestCase() functions. -typedef void (*SetUpTestCaseFunc)(); -typedef void (*TearDownTestCaseFunc)(); - -// Creates a new TestInfo object and registers it with Google Test; -// returns the created object. -// -// Arguments: -// -// test_case_name: name of the test case -// name: name of the test -// type_param the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. -// value_param text representation of the test's value parameter, -// or NULL if this is not a type-parameterized test. -// fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -// factory: pointer to the factory that creates a test object. -// The newly created TestInfo instance will assume -// ownership of the factory object. -GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, - const char* type_param, - const char* value_param, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory); - -// If *pstr starts with the given prefix, modifies *pstr to be right -// past the prefix and returns true; otherwise leaves *pstr unchanged -// and returns false. None of pstr, *pstr, and prefix can be NULL. -GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// State of the definition of a type-parameterized test case. -class GTEST_API_ TypedTestCasePState { - public: - TypedTestCasePState() : registered_(false) {} - - // Adds the given test name to defined_test_names_ and return true - // if the test case hasn't been registered; otherwise aborts the - // program. - bool AddTestName(const char* file, int line, const char* case_name, - const char* test_name) { - if (registered_) { - fprintf(stderr, "%s Test %s must be defined before " - "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", - FormatFileLocation(file, line).c_str(), test_name, case_name); - fflush(stderr); - posix::Abort(); - } - defined_test_names_.insert(test_name); - return true; - } - - // Verifies that registered_tests match the test names in - // defined_test_names_; returns registered_tests if successful, or - // aborts the program otherwise. - const char* VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests); - - private: - bool registered_; - ::std::set defined_test_names_; -}; - -// Skips to the first non-space char after the first comma in 'str'; -// returns NULL if no comma is found in 'str'. -inline const char* SkipComma(const char* str) { - const char* comma = strchr(str, ','); - if (comma == NULL) { - return NULL; - } - while (IsSpace(*(++comma))) {} - return comma; -} - -// Returns the prefix of 'str' before the first comma in it; returns -// the entire string if it contains no comma. -inline String GetPrefixUntilComma(const char* str) { - const char* comma = strchr(str, ','); - return comma == NULL ? String(str) : String(str, comma - str); -} - -// TypeParameterizedTest::Register() -// registers a list of type-parameterized tests with Google Test. The -// return value is insignificant - we just need to return something -// such that we can call this function in a namespace scope. -// -// Implementation note: The GTEST_TEMPLATE_ macro declares a template -// template parameter. It's defined in gtest-type-util.h. -template -class TypeParameterizedTest { - public: - // 'index' is the index of the test in the type list 'Types' - // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, - // Types). Valid values for 'index' are [0, N - 1] where N is the - // length of Types. - static bool Register(const char* prefix, const char* case_name, - const char* test_names, int index) { - typedef typename Types::Head Type; - typedef Fixture FixtureClass; - typedef typename GTEST_BIND_(TestSel, Type) TestClass; - - // First, registers the first type-parameterized test in the type - // list. - MakeAndRegisterTestInfo( - String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", - case_name, index).c_str(), - GetPrefixUntilComma(test_names).c_str(), - GetTypeName().c_str(), - NULL, // No value parameter. - GetTypeId(), - TestClass::SetUpTestCase, - TestClass::TearDownTestCase, - new TestFactoryImpl); - - // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest - ::Register(prefix, case_name, test_names, index + 1); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTest { - public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/, int /*index*/) { - return true; - } -}; - -// TypeParameterizedTestCase::Register() -// registers *all combinations* of 'Tests' and 'Types' with Google -// Test. The return value is insignificant - we just need to return -// something such that we can call this function in a namespace scope. -template -class TypeParameterizedTestCase { - public: - static bool Register(const char* prefix, const char* case_name, - const char* test_names) { - typedef typename Tests::Head Head; - - // First, register the first test in 'Test' for each type in 'Types'. - TypeParameterizedTest::Register( - prefix, case_name, test_names, 0); - - // Next, recurses (at compile time) with the tail of the test list. - return TypeParameterizedTestCase - ::Register(prefix, case_name, SkipComma(test_names)); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTestCase { - public: - static bool Register(const char* /*prefix*/, const char* /*case_name*/, - const char* /*test_names*/) { - return true; - } -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// Returns the current OS stack trace as a String. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in -// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, - int skip_count); - -// Helpers for suppressing warnings on unreachable code or constant -// condition. - -// Always returns true. -GTEST_API_ bool AlwaysTrue(); - -// Always returns false. -inline bool AlwaysFalse() { return !AlwaysTrue(); } - -// Helper for suppressing false warning from Clang on a const char* -// variable declared in a conditional expression always being NULL in -// the else branch. -struct GTEST_API_ ConstCharPtr { - ConstCharPtr(const char* str) : value(str) {} - operator bool() const { return true; } - const char* value; -}; - -// A simple Linear Congruential Generator for generating random -// numbers with a uniform distribution. Unlike rand() and srand(), it -// doesn't use global state (and therefore can't interfere with user -// code). Unlike rand_r(), it's portable. An LCG isn't very random, -// but it's good enough for our purposes. -class GTEST_API_ Random { - public: - static const UInt32 kMaxRange = 1u << 31; - - explicit Random(UInt32 seed) : state_(seed) {} - - void Reseed(UInt32 seed) { state_ = seed; } - - // Generates a random number from [0, range). Crashes if 'range' is - // 0 or greater than kMaxRange. - UInt32 Generate(UInt32 range); - - private: - UInt32 state_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); -}; - -// Defining a variable of type CompileAssertTypesEqual will cause a -// compiler error iff T1 and T2 are different types. -template -struct CompileAssertTypesEqual; - -template -struct CompileAssertTypesEqual { -}; - -// Removes the reference from a type if it is a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::remove_reference, which is not widely available yet. -template -struct RemoveReference { typedef T type; }; // NOLINT -template -struct RemoveReference { typedef T type; }; // NOLINT - -// A handy wrapper around RemoveReference that works when the argument -// T depends on template parameters. -#define GTEST_REMOVE_REFERENCE_(T) \ - typename ::testing::internal::RemoveReference::type - -// Removes const from a type if it is a const type, otherwise leaves -// it unchanged. This is the same as tr1::remove_const, which is not -// widely available yet. -template -struct RemoveConst { typedef T type; }; // NOLINT -template -struct RemoveConst { typedef T type; }; // NOLINT - -// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above -// definition to fail to remove the const in 'const int[3]' and 'const -// char[3][4]'. The following specialization works around the bug. -// However, it causes trouble with GCC and thus needs to be -// conditionally compiled. -#if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) -template -struct RemoveConst { - typedef typename RemoveConst::type type[N]; -}; -#endif - -// A handy wrapper around RemoveConst that works when the argument -// T depends on template parameters. -#define GTEST_REMOVE_CONST_(T) \ - typename ::testing::internal::RemoveConst::type - -// Turns const U&, U&, const U, and U all into U. -#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ - GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) - -// Adds reference to a type if it is not a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::add_reference, which is not widely available yet. -template -struct AddReference { typedef T& type; }; // NOLINT -template -struct AddReference { typedef T& type; }; // NOLINT - -// A handy wrapper around AddReference that works when the argument T -// depends on template parameters. -#define GTEST_ADD_REFERENCE_(T) \ - typename ::testing::internal::AddReference::type - -// Adds a reference to const on top of T as necessary. For example, -// it transforms -// -// char ==> const char& -// const char ==> const char& -// char& ==> const char& -// const char& ==> const char& -// -// The argument T must depend on some template parameters. -#define GTEST_REFERENCE_TO_CONST_(T) \ - GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) - -// ImplicitlyConvertible::value is a compile-time bool -// constant that's true iff type From can be implicitly converted to -// type To. -template -class ImplicitlyConvertible { - private: - // We need the following helper functions only for their types. - // They have no implementations. - - // MakeFrom() is an expression whose type is From. We cannot simply - // use From(), as the type From may not have a public default - // constructor. - static From MakeFrom(); - - // These two functions are overloaded. Given an expression - // Helper(x), the compiler will pick the first version if x can be - // implicitly converted to type To; otherwise it will pick the - // second version. - // - // The first version returns a value of size 1, and the second - // version returns a value of size 2. Therefore, by checking the - // size of Helper(x), which can be done at compile time, we can tell - // which version of Helper() is used, and hence whether x can be - // implicitly converted to type To. - static char Helper(To); - static char (&Helper(...))[2]; // NOLINT - - // We have to put the 'public' section after the 'private' section, - // or MSVC refuses to compile the code. - public: - // MSVC warns about implicitly converting from double to int for - // possible loss of data, so we need to temporarily disable the - // warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4244) // Temporarily disables warning 4244. - - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -# pragma warning(pop) // Restores the warning state. -#elif defined(__BORLANDC__) - // C++Builder cannot use member overload resolution during template - // instantiation. The simplest workaround is to use its C++0x type traits - // functions (C++Builder 2009 and above only). - static const bool value = __is_convertible(From, To); -#else - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -#endif // _MSV_VER -}; -template -const bool ImplicitlyConvertible::value; - -// IsAProtocolMessage::value is a compile-time bool constant that's -// true iff T is type ProtocolMessage, proto2::Message, or a subclass -// of those. -template -struct IsAProtocolMessage - : public bool_constant< - ImplicitlyConvertible::value || - ImplicitlyConvertible::value> { -}; - -// When the compiler sees expression IsContainerTest(0), if C is an -// STL-style container class, the first overload of IsContainerTest -// will be viable (since both C::iterator* and C::const_iterator* are -// valid types and NULL can be implicitly converted to them). It will -// be picked over the second overload as 'int' is a perfect match for -// the type of argument 0. If C::iterator or C::const_iterator is not -// a valid type, the first overload is not viable, and the second -// overload will be picked. Therefore, we can determine whether C is -// a container class by checking the type of IsContainerTest(0). -// The value of the expression is insignificant. -// -// Note that we look for both C::iterator and C::const_iterator. The -// reason is that C++ injects the name of a class as a member of the -// class itself (e.g. you can refer to class iterator as either -// 'iterator' or 'iterator::iterator'). If we look for C::iterator -// only, for example, we would mistakenly think that a class named -// iterator is an STL container. -// -// Also note that the simpler approach of overloading -// IsContainerTest(typename C::const_iterator*) and -// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. -typedef int IsContainer; -template -IsContainer IsContainerTest(int /* dummy */, - typename C::iterator* /* it */ = NULL, - typename C::const_iterator* /* const_it */ = NULL) { - return 0; -} - -typedef char IsNotContainer; -template -IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } - -// EnableIf::type is void when 'Cond' is true, and -// undefined when 'Cond' is false. To use SFINAE to make a function -// overload only apply when a particular expression is true, add -// "typename EnableIf::type* = 0" as the last parameter. -template struct EnableIf; -template<> struct EnableIf { typedef void type; }; // NOLINT - -// Utilities for native arrays. - -// ArrayEq() compares two k-dimensional native arrays using the -// elements' operator==, where k can be any integer >= 0. When k is -// 0, ArrayEq() degenerates into comparing a single pair of values. - -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs); - -// This generic version is used when k is 0. -template -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } - -// This overload is used when k >= 1. -template -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { - return internal::ArrayEq(lhs, N, rhs); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous ArrayEq() function, arrays with different sizes would -// lead to different copies of the template code. -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs) { - for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; - } - return true; -} - -// Finds the first element in the iterator range [begin, end) that -// equals elem. Element may be a native array type itself. -template -Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { - for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; - } - return end; -} - -// CopyArray() copies a k-dimensional native array using the elements' -// operator=, where k can be any integer >= 0. When k is 0, -// CopyArray() degenerates into copying a single value. - -template -void CopyArray(const T* from, size_t size, U* to); - -// This generic version is used when k is 0. -template -inline void CopyArray(const T& from, U* to) { *to = from; } - -// This overload is used when k >= 1. -template -inline void CopyArray(const T(&from)[N], U(*to)[N]) { - internal::CopyArray(from, N, *to); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous CopyArray() function, arrays with different sizes -// would lead to different copies of the template code. -template -void CopyArray(const T* from, size_t size, U* to) { - for (size_t i = 0; i != size; i++) { - internal::CopyArray(from[i], to + i); - } -} - -// The relation between an NativeArray object (see below) and the -// native array it represents. -enum RelationToSource { - kReference, // The NativeArray references the native array. - kCopy // The NativeArray makes a copy of the native array and - // owns the copy. -}; - -// Adapts a native array to a read-only STL-style container. Instead -// of the complete STL container concept, this adaptor only implements -// members useful for Google Mock's container matchers. New members -// should be added as needed. To simplify the implementation, we only -// support Element being a raw type (i.e. having no top-level const or -// reference modifier). It's the client's responsibility to satisfy -// this requirement. Element can be an array type itself (hence -// multi-dimensional arrays are supported). -template -class NativeArray { - public: - // STL-style container typedefs. - typedef Element value_type; - typedef Element* iterator; - typedef const Element* const_iterator; - - // Constructs from a native array. - NativeArray(const Element* array, size_t count, RelationToSource relation) { - Init(array, count, relation); - } - - // Copy constructor. - NativeArray(const NativeArray& rhs) { - Init(rhs.array_, rhs.size_, rhs.relation_to_source_); - } - - ~NativeArray() { - // Ensures that the user doesn't instantiate NativeArray with a - // const or reference type. - static_cast(StaticAssertTypeEqHelper()); - if (relation_to_source_ == kCopy) - delete[] array_; - } - - // STL-style container methods. - size_t size() const { return size_; } - const_iterator begin() const { return array_; } - const_iterator end() const { return array_ + size_; } - bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); - } - - private: - // Initializes this object; makes a copy of the input array if - // 'relation' is kCopy. - void Init(const Element* array, size_t a_size, RelationToSource relation) { - if (relation == kReference) { - array_ = array; - } else { - Element* const copy = new Element[a_size]; - CopyArray(array, a_size, copy); - array_ = copy; - } - size_ = a_size; - relation_to_source_ = relation; - } - - const Element* array_; - size_t size_; - RelationToSource relation_to_source_; - - GTEST_DISALLOW_ASSIGN_(NativeArray); -}; - -} // namespace internal -} // namespace testing - -#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() - -#define GTEST_MESSAGE_(message, result_type) \ - GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) - -#define GTEST_FATAL_FAILURE_(message) \ - return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) - -#define GTEST_NONFATAL_FAILURE_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) - -#define GTEST_SUCCESS_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) - -// Suppresses MSVC warnings 4072 (unreachable code) for the code following -// statement if it returns or throws (or doesn't return or throw in some -// situations). -#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ - if (::testing::internal::AlwaysTrue()) { statement; } - -#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::ConstCharPtr gtest_msg = "") { \ - bool gtest_caught_expected = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (expected_exception const&) { \ - gtest_caught_expected = true; \ - } \ - catch (...) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws a different type."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - if (!gtest_caught_expected) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws nothing."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ - fail(gtest_msg.value) - -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws.") - -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - - -// Implements Boolean test assertions such as EXPECT_TRUE. expression can be -// either a boolean expression or an AssertionResult. text is a textual -// represenation of expression as it was passed into the EXPECT_TRUE. -#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) - -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") - -// Expands to the name of the class that implements the given test. -#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - test_case_name##_##test_name##_Test - -// Helper macro for defining tests. -#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ -class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ - public:\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ - private:\ - virtual void TestBody();\ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ -};\ -\ -::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ - ::test_info_ =\ - ::testing::internal::MakeAndRegisterTestInfo(\ - #test_case_name, #test_name, NULL, NULL, \ - (parent_id), \ - parent_class::SetUpTestCase, \ - parent_class::TearDownTestCase, \ - new ::testing::internal::TestFactoryImpl<\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ -void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the public API for death tests. It is -// #included by gtest.h so a user doesn't need to include this -// directly. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines internal utilities needed for implementing -// death tests. They are subject to change without notice. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - - -#include - -namespace testing { -namespace internal { - -GTEST_DECLARE_string_(internal_run_death_test); - -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; -const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; - -#if GTEST_HAS_DEATH_TEST - -// DeathTest is a class that hides much of the complexity of the -// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method -// returns a concrete class that depends on the prevailing death test -// style, as defined by the --gtest_death_test_style and/or -// --gtest_internal_run_death_test flags. - -// In describing the results of death tests, these terms are used with -// the corresponding definitions: -// -// exit status: The integer exit information in the format specified -// by wait(2) -// exit code: The integer code passed to exit(3), _exit(2), or -// returned from main() -class GTEST_API_ DeathTest { - public: - // Create returns false if there was an error determining the - // appropriate action to take for the current death test; for example, - // if the gtest_death_test_style flag is set to an invalid value. - // The LastMessage method will return a more detailed message in that - // case. Otherwise, the DeathTest pointer pointed to by the "test" - // argument is set. If the death test should be skipped, the pointer - // is set to NULL; otherwise, it is set to the address of a new concrete - // DeathTest object that controls the execution of the current test. - static bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); - DeathTest(); - virtual ~DeathTest() { } - - // A helper class that aborts a death test when it's deleted. - class ReturnSentinel { - public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } - ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } - private: - DeathTest* const test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); - } GTEST_ATTRIBUTE_UNUSED_; - - // An enumeration of possible roles that may be taken when a death - // test is encountered. EXECUTE means that the death test logic should - // be executed immediately. OVERSEE means that the program should prepare - // the appropriate environment for a child process to execute the death - // test, then wait for it to complete. - enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; - - // An enumeration of the three reasons that a test might be aborted. - enum AbortReason { - TEST_ENCOUNTERED_RETURN_STATEMENT, - TEST_THREW_EXCEPTION, - TEST_DID_NOT_DIE - }; - - // Assumes one of the above roles. - virtual TestRole AssumeRole() = 0; - - // Waits for the death test to finish and returns its status. - virtual int Wait() = 0; - - // Returns true if the death test passed; that is, the test process - // exited during the test, its exit status matches a user-supplied - // predicate, and its stderr output matches a user-supplied regular - // expression. - // The user-supplied predicate may be a macro expression rather - // than a function pointer or functor, or else Wait and Passed could - // be combined. - virtual bool Passed(bool exit_status_ok) = 0; - - // Signals that the death test did not die as expected. - virtual void Abort(AbortReason reason) = 0; - - // Returns a human-readable outcome message regarding the outcome of - // the last death test. - static const char* LastMessage(); - - static void set_last_death_test_message(const String& message); - - private: - // A string containing a description of the outcome of the last death test. - static String last_death_test_message_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); -}; - -// Factory interface for death tests. May be mocked out for testing. -class DeathTestFactory { - public: - virtual ~DeathTestFactory() { } - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test) = 0; -}; - -// A concrete DeathTestFactory implementation for normal use. -class DefaultDeathTestFactory : public DeathTestFactory { - public: - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); -}; - -// Returns true if exit_status describes a process that was terminated -// by a signal, or exited normally with a nonzero exit code. -GTEST_API_ bool ExitedUnsuccessfully(int exit_status); - -// Traps C++ exceptions escaping statement and reports them as test -// failures. Note that trapping SEH exceptions is not implemented here. -# if GTEST_HAS_EXCEPTIONS -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (const ::std::exception& gtest_exception) { \ - fprintf(\ - stderr, \ - "\n%s: Caught std::exception-derived exception escaping the " \ - "death test statement. Exception message: %s\n", \ - ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ - gtest_exception.what()); \ - fflush(stderr); \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } catch (...) { \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } - -# else -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) - -# endif - -// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, -// ASSERT_EXIT*, and EXPECT_EXIT*. -# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - const ::testing::internal::RE& gtest_regex = (regex); \ - ::testing::internal::DeathTest* gtest_dt; \ - if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ - __FILE__, __LINE__, >est_dt)) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - if (gtest_dt != NULL) { \ - ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ - gtest_dt_ptr(gtest_dt); \ - switch (gtest_dt->AssumeRole()) { \ - case ::testing::internal::DeathTest::OVERSEE_TEST: \ - if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - break; \ - case ::testing::internal::DeathTest::EXECUTE_TEST: { \ - ::testing::internal::DeathTest::ReturnSentinel \ - gtest_sentinel(gtest_dt); \ - GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ - gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ - break; \ - } \ - default: \ - break; \ - } \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ - fail(::testing::internal::DeathTest::LastMessage()) -// The symbol "fail" here expands to something into which a message -// can be streamed. - -// A class representing the parsed contents of the -// --gtest_internal_run_death_test flag, as it existed when -// RUN_ALL_TESTS was called. -class InternalRunDeathTestFlag { - public: - InternalRunDeathTestFlag(const String& a_file, - int a_line, - int an_index, - int a_write_fd) - : file_(a_file), line_(a_line), index_(an_index), - write_fd_(a_write_fd) {} - - ~InternalRunDeathTestFlag() { - if (write_fd_ >= 0) - posix::Close(write_fd_); - } - - String file() const { return file_; } - int line() const { return line_; } - int index() const { return index_; } - int write_fd() const { return write_fd_; } - - private: - String file_; - int line_; - int index_; - int write_fd_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); -}; - -// Returns a newly created InternalRunDeathTestFlag object with fields -// initialized from the GTEST_FLAG(internal_run_death_test) flag if -// the flag is specified; otherwise returns NULL. -InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); - -#else // GTEST_HAS_DEATH_TEST - -// This macro is used for implementing macros such as -// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where -// death tests are not supported. Those macros must compile on such systems -// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on -// systems that support death tests. This allows one to write such a macro -// on a system that does not support death tests and be sure that it will -// compile on a death-test supporting system. -// -// Parameters: -// statement - A statement that a macro such as EXPECT_DEATH would test -// for program termination. This macro has to make sure this -// statement is compiled but not executed, to ensure that -// EXPECT_DEATH_IF_SUPPORTED compiles with a certain -// parameter iff EXPECT_DEATH compiles with it. -// regex - A regex that a macro such as EXPECT_DEATH would use to test -// the output of statement. This parameter has to be -// compiled but not evaluated by this macro, to ensure that -// this macro only accepts expressions that a macro such as -// EXPECT_DEATH would accept. -// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED -// and a return statement for ASSERT_DEATH_IF_SUPPORTED. -// This ensures that ASSERT_DEATH_IF_SUPPORTED will not -// compile inside functions where ASSERT_DEATH doesn't -// compile. -// -// The branch that has an always false condition is used to ensure that -// statement and regex are compiled (and thus syntactically correct) but -// never executed. The unreachable code macro protects the terminator -// statement from generating an 'unreachable code' warning in case -// statement unconditionally returns or throws. The Message constructor at -// the end allows the syntax of streaming additional messages into the -// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ - ::testing::Message() - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - -namespace testing { - -// This flag controls the style of death tests. Valid values are "threadsafe", -// meaning that the death test child process will re-execute the test binary -// from the start, running only a single death test, or "fast", -// meaning that the child process will execute the test logic immediately -// after forking. -GTEST_DECLARE_string_(death_test_style); - -#if GTEST_HAS_DEATH_TEST - -// The following macros are useful for writing death tests. - -// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is -// executed: -// -// 1. It generates a warning if there is more than one active -// thread. This is because it's safe to fork() or clone() only -// when there is a single thread. -// -// 2. The parent process clone()s a sub-process and runs the death -// test in it; the sub-process exits with code 0 at the end of the -// death test, if it hasn't exited already. -// -// 3. The parent process waits for the sub-process to terminate. -// -// 4. The parent process checks the exit code and error message of -// the sub-process. -// -// Examples: -// -// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); -// for (int i = 0; i < 5; i++) { -// EXPECT_DEATH(server.ProcessRequest(i), -// "Invalid request .* in ProcessRequest()") -// << "Failed to die on request " << i); -// } -// -// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); -// -// bool KilledBySIGHUP(int exit_code) { -// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; -// } -// -// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); -// -// On the regular expressions used in death tests: -// -// On POSIX-compliant systems (*nix), we use the library, -// which uses the POSIX extended regex syntax. -// -// On other platforms (e.g. Windows), we only support a simple regex -// syntax implemented as part of Google Test. This limited -// implementation should be enough most of the time when writing -// death tests; though it lacks many features you can find in PCRE -// or POSIX extended regex syntax. For example, we don't support -// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and -// repetition count ("x{5,7}"), among others. -// -// Below is the syntax that we do support. We chose it to be a -// subset of both PCRE and POSIX extended regex, so it's easy to -// learn wherever you come from. In the following: 'A' denotes a -// literal character, period (.), or a single \\ escape sequence; -// 'x' and 'y' denote regular expressions; 'm' and 'n' are for -// natural numbers. -// -// c matches any literal character c -// \\d matches any decimal digit -// \\D matches any character that's not a decimal digit -// \\f matches \f -// \\n matches \n -// \\r matches \r -// \\s matches any ASCII whitespace, including \n -// \\S matches any character that's not a whitespace -// \\t matches \t -// \\v matches \v -// \\w matches any letter, _, or decimal digit -// \\W matches any character that \\w doesn't match -// \\c matches any literal character c, which must be a punctuation -// . matches any single character except \n -// A? matches 0 or 1 occurrences of A -// A* matches 0 or many occurrences of A -// A+ matches 1 or many occurrences of A -// ^ matches the beginning of a string (not that of each line) -// $ matches the end of a string (not that of each line) -// xy matches x followed by y -// -// If you accidentally use PCRE or POSIX extended regex features -// not implemented by us, you will get a run-time failure. In that -// case, please try to rewrite your regular expression within the -// above syntax. -// -// This implementation is *not* meant to be as highly tuned or robust -// as a compiled regex library, but should perform well enough for a -// death test, which already incurs significant overhead by launching -// a child process. -// -// Known caveats: -// -// A "threadsafe" style death test obtains the path to the test -// program from argv[0] and re-executes it in the sub-process. For -// simplicity, the current implementation doesn't search the PATH -// when launching the sub-process. This means that the user must -// invoke the test program via a path that contains at least one -// path separator (e.g. path/to/foo_test and -// /absolute/path/to/bar_test are fine, but foo_test is not). This -// is rarely a problem as people usually don't put the test binary -// directory in PATH. -// -// TODO(wan@google.com): make thread-safe death tests search the PATH. - -// Asserts that a given statement causes the program to exit, with an -// integer exit status that satisfies predicate, and emitting error output -// that matches regex. -# define ASSERT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) - -// Like ASSERT_EXIT, but continues on to successive tests in the -// test case, if any: -# define EXPECT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) - -// Asserts that a given statement causes the program to exit, either by -// explicitly exiting with a nonzero exit code or being killed by a -// signal, and emitting error output that matches regex. -# define ASSERT_DEATH(statement, regex) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Like ASSERT_DEATH, but continues on to successive tests in the -// test case, if any: -# define EXPECT_DEATH(statement, regex) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: - -// Tests that an exit code describes a normal exit with a given exit code. -class GTEST_API_ ExitedWithCode { - public: - explicit ExitedWithCode(int exit_code); - bool operator()(int exit_status) const; - private: - // No implementation - assignment is unsupported. - void operator=(const ExitedWithCode& other); - - const int exit_code_; -}; - -# if !GTEST_OS_WINDOWS -// Tests that an exit code describes an exit due to termination by a -// given signal. -class GTEST_API_ KilledBySignal { - public: - explicit KilledBySignal(int signum); - bool operator()(int exit_status) const; - private: - const int signum_; -}; -# endif // !GTEST_OS_WINDOWS - -// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. -// The death testing framework causes this to have interesting semantics, -// since the sideeffects of the call are only visible in opt mode, and not -// in debug mode. -// -// In practice, this can be used to test functions that utilize the -// LOG(DFATAL) macro using the following style: -// -// int DieInDebugOr12(int* sideeffect) { -// if (sideeffect) { -// *sideeffect = 12; -// } -// LOG(DFATAL) << "death"; -// return 12; -// } -// -// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { -// int sideeffect = 0; -// // Only asserts in dbg. -// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); -// -// #ifdef NDEBUG -// // opt-mode has sideeffect visible. -// EXPECT_EQ(12, sideeffect); -// #else -// // dbg-mode no visible sideeffect. -// EXPECT_EQ(0, sideeffect); -// #endif -// } -// -// This will assert that DieInDebugReturn12InOpt() crashes in debug -// mode, usually due to a DCHECK or LOG(DFATAL), but returns the -// appropriate fallback value (12 in this case) in opt mode. If you -// need to test that a function has appropriate side-effects in opt -// mode, include assertions against the side-effects. A general -// pattern for this is: -// -// EXPECT_DEBUG_DEATH({ -// // Side-effects here will have an effect after this statement in -// // opt mode, but none in debug mode. -// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); -// }, "death"); -// -# ifdef NDEBUG - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - do { statement; } while (::testing::internal::AlwaysFalse()) - -# else - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) - -# endif // NDEBUG for EXPECT_DEBUG_DEATH -#endif // GTEST_HAS_DEATH_TEST - -// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and -// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if -// death tests are supported; otherwise they just issue a warning. This is -// useful when you are combining death test assertions with normal test -// assertions in one test. -#if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) -#else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) -#endif - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// The Google C++ Testing Framework (Google Test) -// -// This header file defines the Message class. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! - -#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ - -#include - - -namespace testing { - -// The Message class works like an ostream repeater. -// -// Typical usage: -// -// 1. You stream a bunch of values to a Message object. -// It will remember the text in a stringstream. -// 2. Then you stream the Message object to an ostream. -// This causes the text in the Message to be streamed -// to the ostream. -// -// For example; -// -// testing::Message foo; -// foo << 1 << " != " << 2; -// std::cout << foo; -// -// will print "1 != 2". -// -// Message is not intended to be inherited from. In particular, its -// destructor is not virtual. -// -// Note that stringstream behaves differently in gcc and in MSVC. You -// can stream a NULL char pointer to it in the former, but not in the -// latter (it causes an access violation if you do). The Message -// class hides this difference by treating a NULL char pointer as -// "(null)". -class GTEST_API_ Message { - private: - // The type of basic IO manipulators (endl, ends, and flush) for - // narrow streams. - typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); - - public: - // Constructs an empty Message. - // We allocate the stringstream separately because otherwise each use of - // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's - // stack frame leading to huge stack frames in some cases; gcc does not reuse - // the stack space. - Message() : ss_(new ::std::stringstream) { - // By default, we want there to be enough precision when printing - // a double to a Message. - *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); - } - - // Copy constructor. - Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT - *ss_ << msg.GetString(); - } - - // Constructs a Message from a C-string. - explicit Message(const char* str) : ss_(new ::std::stringstream) { - *ss_ << str; - } - -#if GTEST_OS_SYMBIAN - // Streams a value (either a pointer or not) to this object. - template - inline Message& operator <<(const T& value) { - StreamHelper(typename internal::is_pointer::type(), value); - return *this; - } -#else - // Streams a non-pointer value to this object. - template - inline Message& operator <<(const T& val) { - ::GTestStreamToHelper(ss_.get(), val); - return *this; - } - - // Streams a pointer value to this object. - // - // This function is an overload of the previous one. When you - // stream a pointer to a Message, this definition will be used as it - // is more specialized. (The C++ Standard, section - // [temp.func.order].) If you stream a non-pointer, then the - // previous definition will be used. - // - // The reason for this overload is that streaming a NULL pointer to - // ostream is undefined behavior. Depending on the compiler, you - // may get "0", "(nil)", "(null)", or an access violation. To - // ensure consistent result across compilers, we always treat NULL - // as "(null)". - template - inline Message& operator <<(T* const& pointer) { // NOLINT - if (pointer == NULL) { - *ss_ << "(null)"; - } else { - ::GTestStreamToHelper(ss_.get(), pointer); - } - return *this; - } -#endif // GTEST_OS_SYMBIAN - - // Since the basic IO manipulators are overloaded for both narrow - // and wide streams, we have to provide this specialized definition - // of operator <<, even though its body is the same as the - // templatized version above. Without this definition, streaming - // endl or other basic IO manipulators to Message will confuse the - // compiler. - Message& operator <<(BasicNarrowIoManip val) { - *ss_ << val; - return *this; - } - - // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } - - // These two overloads allow streaming a wide C string to a Message - // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } - Message& operator <<(wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); - } - -#if GTEST_HAS_STD_WSTRING - // Converts the given wide string to a narrow string using the UTF-8 - // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_GLOBAL_WSTRING - // Converts the given wide string to a narrow string using the UTF-8 - // encoding, and streams the result to this Message object. - Message& operator <<(const ::wstring& wstr); -#endif // GTEST_HAS_GLOBAL_WSTRING - - // Gets the text streamed to this object so far as a String. - // Each '\0' character in the buffer is replaced with "\\0". - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::String GetString() const { - return internal::StringStreamToString(ss_.get()); - } - - private: - -#if GTEST_OS_SYMBIAN - // These are needed as the Nokia Symbian Compiler cannot decide between - // const T& and const T* in a function template. The Nokia compiler _can_ - // decide between class template specializations for T and T*, so a - // tr1::type_traits-like is_pointer works, and we can overload on that. - template - inline void StreamHelper(internal::true_type /*dummy*/, T* pointer) { - if (pointer == NULL) { - *ss_ << "(null)"; - } else { - ::GTestStreamToHelper(ss_.get(), pointer); - } - } - template - inline void StreamHelper(internal::false_type /*dummy*/, const T& value) { - ::GTestStreamToHelper(ss_.get(), value); - } -#endif // GTEST_OS_SYMBIAN - - // We'll hold the text streamed to this object here. - const internal::scoped_ptr< ::std::stringstream> ss_; - - // We declare (but don't implement) this to prevent the compiler - // from implementing the assignment operator. - void operator=(const Message&); -}; - -// Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { - return os << sb.GetString(); -} - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -// This file was GENERATED by command: -// pump.py gtest-param-test.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: vladl@google.com (Vlad Losev) -// -// Macros and functions for implementing parameterized tests -// in Google C++ Testing Framework (Google Test) -// -// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ - - -// Value-parameterized tests allow you to test your code with different -// parameters without writing multiple copies of the same test. -// -// Here is how you use value-parameterized tests: - -#if 0 - -// To write value-parameterized tests, first you should define a fixture -// class. It is usually derived from testing::TestWithParam (see below for -// another inheritance scheme that's sometimes useful in more complicated -// class hierarchies), where the type of your parameter values. -// TestWithParam is itself derived from testing::Test. T can be any -// copyable type. If it's a raw pointer, you are responsible for managing the -// lifespan of the pointed values. - -class FooTest : public ::testing::TestWithParam { - // You can implement all the usual class fixture members here. -}; - -// Then, use the TEST_P macro to define as many parameterized tests -// for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. - -TEST_P(FooTest, DoesBlah) { - // Inside a test, access the test parameter with the GetParam() method - // of the TestWithParam class: - EXPECT_TRUE(foo.Blah(GetParam())); - ... -} - -TEST_P(FooTest, HasBlahBlah) { - ... -} - -// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test -// case with any set of parameters you want. Google Test defines a number -// of functions for generating test parameters. They return what we call -// (surprise!) parameter generators. Here is a summary of them, which -// are all in the testing namespace: -// -// -// Range(begin, end [, step]) - Yields values {begin, begin+step, -// begin+step+step, ...}. The values do not -// include end. step defaults to 1. -// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. -// ValuesIn(container) - Yields values from a C-style array, an STL -// ValuesIn(begin,end) container, or an iterator range [begin, end). -// Bool() - Yields sequence {false, true}. -// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product -// for the math savvy) of the values generated -// by the N generators. -// -// For more details, see comments at the definitions of these functions below -// in this file. -// -// The following statement will instantiate tests from the FooTest test case -// each with parameter values "meeny", "miny", and "moe". - -INSTANTIATE_TEST_CASE_P(InstantiationName, - FooTest, - Values("meeny", "miny", "moe")); - -// To distinguish different instances of the pattern, (yes, you -// can instantiate it more then once) the first argument to the -// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the -// actual test case name. Remember to pick unique prefixes for different -// instantiations. The tests from the instantiation above will have -// these names: -// -// * InstantiationName/FooTest.DoesBlah/0 for "meeny" -// * InstantiationName/FooTest.DoesBlah/1 for "miny" -// * InstantiationName/FooTest.DoesBlah/2 for "moe" -// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" -// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" -// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" -// -// You can use these names in --gtest_filter. -// -// This statement will instantiate all tests from FooTest again, each -// with parameter values "cat" and "dog": - -const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); - -// The tests from the instantiation above will have these names: -// -// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" -// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" -// -// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests -// in the given test case, whether their definitions come before or -// AFTER the INSTANTIATE_TEST_CASE_P statement. -// -// Please also note that generator expressions (including parameters to the -// generators) are evaluated in InitGoogleTest(), after main() has started. -// This allows the user on one hand, to adjust generator parameters in order -// to dynamically determine a set of tests to run and on the other hand, -// give the user a chance to inspect the generated tests with Google Test -// reflection API before RUN_ALL_TESTS() is executed. -// -// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc -// for more examples. -// -// In the future, we plan to publish the API for defining new parameter -// generators. But for now this interface remains part of the internal -// implementation and is subject to change. -// -// -// A parameterized test fixture must be derived from testing::Test and from -// testing::WithParamInterface, where T is the type of the parameter -// values. Inheriting from TestWithParam satisfies that requirement because -// TestWithParam inherits from both Test and WithParamInterface. In more -// complicated hierarchies, however, it is occasionally useful to inherit -// separately from Test and WithParamInterface. For example: - -class BaseTest : public ::testing::Test { - // You can inherit all the usual members for a non-parameterized test - // fixture here. -}; - -class DerivedTest : public BaseTest, public ::testing::WithParamInterface { - // The usual test fixture members go here too. -}; - -TEST_F(BaseTest, HasFoo) { - // This is an ordinary non-parameterized test. -} - -TEST_P(DerivedTest, DoesBlah) { - // GetParam works just the same here as if you inherit from TestWithParam. - EXPECT_TRUE(foo.Blah(GetParam())); -} - -#endif // 0 - - -#if !GTEST_OS_SYMBIAN -# include -#endif - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: vladl@google.com (Vlad Losev) - -// Type and function utilities for implementing parameterized tests. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ - -#include -#include -#include - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. -// Copyright 2003 Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Authors: Dan Egnor (egnor@google.com) -// -// A "smart" pointer type with reference tracking. Every pointer to a -// particular object is kept on a circular linked list. When the last pointer -// to an object is destroyed or reassigned, the object is deleted. -// -// Used properly, this deletes the object when the last reference goes away. -// There are several caveats: -// - Like all reference counting schemes, cycles lead to leaks. -// - Each smart pointer is actually two pointers (8 bytes instead of 4). -// - Every time a pointer is assigned, the entire list of pointers to that -// object is traversed. This class is therefore NOT SUITABLE when there -// will often be more than two or three pointers to a particular object. -// - References are only tracked as long as linked_ptr<> objects are copied. -// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS -// will happen (double deletion). -// -// A good use of this class is storing object references in STL containers. -// You can safely put linked_ptr<> in a vector<>. -// Other uses may not be as good. -// -// Note: If you use an incomplete type with linked_ptr<>, the class -// *containing* linked_ptr<> must have a constructor and destructor (even -// if they do nothing!). -// -// Bill Gibbons suggested we use something like this. -// -// Thread Safety: -// Unlike other linked_ptr implementations, in this implementation -// a linked_ptr object is thread-safe in the sense that: -// - it's safe to copy linked_ptr objects concurrently, -// - it's safe to copy *from* a linked_ptr and read its underlying -// raw pointer (e.g. via get()) concurrently, and -// - it's safe to write to two linked_ptrs that point to the same -// shared object concurrently. -// TODO(wan@google.com): rename this to safe_linked_ptr to avoid -// confusion with normal linked_ptr. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ - -#include -#include - - -namespace testing { -namespace internal { - -// Protects copying of all linked_ptr objects. -GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); - -// This is used internally by all instances of linked_ptr<>. It needs to be -// a non-template class because different types of linked_ptr<> can refer to -// the same object (linked_ptr(obj) vs linked_ptr(obj)). -// So, it needs to be possible for different types of linked_ptr to participate -// in the same circular linked list, so we need a single class type here. -// -// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr. -class linked_ptr_internal { - public: - // Create a new circle that includes only this instance. - void join_new() { - next_ = this; - } - - // Many linked_ptr operations may change p.link_ for some linked_ptr - // variable p in the same circle as this object. Therefore we need - // to prevent two such operations from occurring concurrently. - // - // Note that different types of linked_ptr objects can coexist in a - // circle (e.g. linked_ptr, linked_ptr, and - // linked_ptr). Therefore we must use a single mutex to - // protect all linked_ptr objects. This can create serious - // contention in production code, but is acceptable in a testing - // framework. - - // Join an existing circle. - // L < g_linked_ptr_mutex - void join(linked_ptr_internal const* ptr) { - MutexLock lock(&g_linked_ptr_mutex); - - linked_ptr_internal const* p = ptr; - while (p->next_ != ptr) p = p->next_; - p->next_ = this; - next_ = ptr; - } - - // Leave whatever circle we're part of. Returns true if we were the - // last member of the circle. Once this is done, you can join() another. - // L < g_linked_ptr_mutex - bool depart() { - MutexLock lock(&g_linked_ptr_mutex); - - if (next_ == this) return true; - linked_ptr_internal const* p = next_; - while (p->next_ != this) p = p->next_; - p->next_ = next_; - return false; - } - - private: - mutable linked_ptr_internal const* next_; -}; - -template -class linked_ptr { - public: - typedef T element_type; - - // Take over ownership of a raw pointer. This should happen as soon as - // possible after the object is created. - explicit linked_ptr(T* ptr = NULL) { capture(ptr); } - ~linked_ptr() { depart(); } - - // Copy an existing linked_ptr<>, adding ourselves to the list of references. - template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } - linked_ptr(linked_ptr const& ptr) { // NOLINT - assert(&ptr != this); - copy(&ptr); - } - - // Assignment releases the old value and acquires the new. - template linked_ptr& operator=(linked_ptr const& ptr) { - depart(); - copy(&ptr); - return *this; - } - - linked_ptr& operator=(linked_ptr const& ptr) { - if (&ptr != this) { - depart(); - copy(&ptr); - } - return *this; - } - - // Smart pointer members. - void reset(T* ptr = NULL) { - depart(); - capture(ptr); - } - T* get() const { return value_; } - T* operator->() const { return value_; } - T& operator*() const { return *value_; } - - bool operator==(T* p) const { return value_ == p; } - bool operator!=(T* p) const { return value_ != p; } - template - bool operator==(linked_ptr const& ptr) const { - return value_ == ptr.get(); - } - template - bool operator!=(linked_ptr const& ptr) const { - return value_ != ptr.get(); - } - - private: - template - friend class linked_ptr; - - T* value_; - linked_ptr_internal link_; - - void depart() { - if (link_.depart()) delete value_; - } - - void capture(T* ptr) { - value_ = ptr; - link_.join_new(); - } - - template void copy(linked_ptr const* ptr) { - value_ = ptr->get(); - if (value_) - link_.join(&ptr->link_); - else - link_.join_new(); - } -}; - -template inline -bool operator==(T* ptr, const linked_ptr& x) { - return ptr == x.get(); -} - -template inline -bool operator!=(T* ptr, const linked_ptr& x) { - return ptr != x.get(); -} - -// A function to convert T* into linked_ptr -// Doing e.g. make_linked_ptr(new FooBarBaz(arg)) is a shorter notation -// for linked_ptr >(new FooBarBaz(arg)) -template -linked_ptr make_linked_ptr(T* ptr) { - return linked_ptr(ptr); -} - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Test - The Google C++ Testing Framework -// -// This file implements a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); -// -// A user can teach this function how to print a class type T by -// defining either operator<<() or PrintTo() in the namespace that -// defines T. More specifically, the FIRST defined function in the -// following list will be used (assuming T is defined in namespace -// foo): -// -// 1. foo::PrintTo(const T&, ostream*) -// 2. operator<<(ostream&, const T&) defined in either foo or the -// global namespace. -// -// If none of the above is defined, it will print the debug string of -// the value if it is a protocol buffer, or print the raw bytes in the -// value otherwise. -// -// To aid debugging: when T is a reference type, the address of the -// value is also printed; when T is a (const) char pointer, both the -// pointer value and the NUL-terminated string it points to are -// printed. -// -// We also provide some convenient wrappers: -// -// // Prints a value to a string. For a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// std::string ::testing::PrintToString(const T& value); -// -// // Prints a value tersely: for a reference type, the referenced -// // value (but not the address) is printed; for a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); -// -// // Prints value using the type inferred by the compiler. The difference -// // from UniversalTersePrint() is that this function prints both the -// // pointer and the NUL-terminated string for a (const or not) char pointer. -// void ::testing::internal::UniversalPrint(const T& value, ostream*); -// -// // Prints the fields of a tuple tersely to a string vector, one -// // element for each field. Tuple support must be enabled in -// // gtest-port.h. -// std::vector UniversalTersePrintTupleFieldsToStrings( -// const Tuple& value); -// -// Known limitation: -// -// The print primitives print the elements of an STL-style container -// using the compiler-inferred type of *iter where iter is a -// const_iterator of the container. When const_iterator is an input -// iterator but not a forward iterator, this inferred type may not -// match value_type, and the print output may be incorrect. In -// practice, this is rarely a problem as for most containers -// const_iterator is a forward iterator. We'll fix this if there's an -// actual need for it. Note that this fix cannot rely on value_type -// being defined as many user-defined container types don't have -// value_type. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -#include // NOLINT -#include -#include -#include -#include - -namespace testing { - -// Definitions in the 'internal' and 'internal2' name spaces are -// subject to change without notice. DO NOT USE THEM IN USER CODE! -namespace internal2 { - -// Prints the given number of bytes in the given object to the given -// ostream. -GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); - -// For selecting which printer to use when a given type has neither << -// nor PrintTo(). -enum TypeKind { - kProtobuf, // a protobuf type - kConvertibleToInteger, // a type implicitly convertible to BiggestInt - // (e.g. a named or unnamed enum type) - kOtherType // anything else -}; - -// TypeWithoutFormatter::PrintValue(value, os) is called -// by the universal printer to print a value of type T when neither -// operator<< nor PrintTo() is defined for T, where kTypeKind is the -// "kind" of T as defined by enum TypeKind. -template -class TypeWithoutFormatter { - public: - // This default version is called when kTypeKind is kOtherType. - static void PrintValue(const T& value, ::std::ostream* os) { - PrintBytesInObjectTo(reinterpret_cast(&value), - sizeof(value), os); - } -}; - -// We print a protobuf using its ShortDebugString() when the string -// doesn't exceed this many characters; otherwise we print it using -// DebugString() for better readability. -const size_t kProtobufOneLinerMaxLength = 50; - -template -class TypeWithoutFormatter { - public: - static void PrintValue(const T& value, ::std::ostream* os) { - const ::testing::internal::string short_str = value.ShortDebugString(); - const ::testing::internal::string pretty_str = - short_str.length() <= kProtobufOneLinerMaxLength ? - short_str : ("\n" + value.DebugString()); - *os << ("<" + pretty_str + ">"); - } -}; - -template -class TypeWithoutFormatter { - public: - // Since T has no << operator or PrintTo() but can be implicitly - // converted to BiggestInt, we print it as a BiggestInt. - // - // Most likely T is an enum type (either named or unnamed), in which - // case printing it as an integer is the desired behavior. In case - // T is not an enum, printing it as an integer is the best we can do - // given that it has no user-defined printer. - static void PrintValue(const T& value, ::std::ostream* os) { - const internal::BiggestInt kBigInt = value; - *os << kBigInt; - } -}; - -// Prints the given value to the given ostream. If the value is a -// protocol message, its debug string is printed; if it's an enum or -// of a type implicitly convertible to BiggestInt, it's printed as an -// integer; otherwise the bytes in the value are printed. This is -// what UniversalPrinter::Print() does when it knows nothing about -// type T and T has neither << operator nor PrintTo(). -// -// A user can override this behavior for a class type Foo by defining -// a << operator in the namespace where Foo is defined. -// -// We put this operator in namespace 'internal2' instead of 'internal' -// to simplify the implementation, as much code in 'internal' needs to -// use << in STL, which would conflict with our own << were it defined -// in 'internal'. -// -// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If -// we define it to take an std::ostream instead, we'll get an -// "ambiguous overloads" compiler error when trying to print a type -// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether -// operator<<(std::ostream&, const T&) or -// operator<<(std::basic_stream, const Foo&) is more -// specific. -template -::std::basic_ostream& operator<<( - ::std::basic_ostream& os, const T& x) { - TypeWithoutFormatter::value ? kProtobuf : - internal::ImplicitlyConvertible::value ? - kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); - return os; -} - -} // namespace internal2 -} // namespace testing - -// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up -// magic needed for implementing UniversalPrinter won't work. -namespace testing_internal { - -// Used to print a value that is not an STL-style container when the -// user doesn't define PrintTo() for it. -template -void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { - // With the following statement, during unqualified name lookup, - // testing::internal2::operator<< appears as if it was declared in - // the nearest enclosing namespace that contains both - // ::testing_internal and ::testing::internal2, i.e. the global - // namespace. For more details, refer to the C++ Standard section - // 7.3.4-1 [namespace.udir]. This allows us to fall back onto - // testing::internal2::operator<< in case T doesn't come with a << - // operator. - // - // We cannot write 'using ::testing::internal2::operator<<;', which - // gcc 3.3 fails to compile due to a compiler bug. - using namespace ::testing::internal2; // NOLINT - - // Assuming T is defined in namespace foo, in the next statement, - // the compiler will consider all of: - // - // 1. foo::operator<< (thanks to Koenig look-up), - // 2. ::operator<< (as the current namespace is enclosed in ::), - // 3. testing::internal2::operator<< (thanks to the using statement above). - // - // The operator<< whose type matches T best will be picked. - // - // We deliberately allow #2 to be a candidate, as sometimes it's - // impossible to define #1 (e.g. when foo is ::std, defining - // anything in it is undefined behavior unless you are a compiler - // vendor.). - *os << value; -} - -} // namespace testing_internal - -namespace testing { -namespace internal { - -// UniversalPrinter::Print(value, ostream_ptr) prints the given -// value to the given ostream. The caller must ensure that -// 'ostream_ptr' is not NULL, or the behavior is undefined. -// -// We define UniversalPrinter as a class template (as opposed to a -// function template), as we need to partially specialize it for -// reference types, which cannot be done with function templates. -template -class UniversalPrinter; - -template -void UniversalPrint(const T& value, ::std::ostream* os); - -// Used to print an STL-style container when the user doesn't define -// a PrintTo() for it. -template -void DefaultPrintTo(IsContainer /* dummy */, - false_type /* is not a pointer */, - const C& container, ::std::ostream* os) { - const size_t kMaxCount = 32; // The maximum number of elements to print. - *os << '{'; - size_t count = 0; - for (typename C::const_iterator it = container.begin(); - it != container.end(); ++it, ++count) { - if (count > 0) { - *os << ','; - if (count == kMaxCount) { // Enough has been printed. - *os << " ..."; - break; - } - } - *os << ' '; - // We cannot call PrintTo(*it, os) here as PrintTo() doesn't - // handle *it being a native array. - internal::UniversalPrint(*it, os); - } - - if (count > 0) { - *os << ' '; - } - *os << '}'; -} - -// Used to print a pointer that is neither a char pointer nor a member -// pointer, when the user doesn't define PrintTo() for it. (A member -// variable pointer or member function pointer doesn't really point to -// a location in the address space. Their representation is -// implementation-defined. Therefore they will be printed as raw -// bytes.) -template -void DefaultPrintTo(IsNotContainer /* dummy */, - true_type /* is a pointer */, - T* p, ::std::ostream* os) { - if (p == NULL) { - *os << "NULL"; - } else { - // C++ doesn't allow casting from a function pointer to any object - // pointer. - // - // IsTrue() silences warnings: "Condition is always true", - // "unreachable code". - if (IsTrue(ImplicitlyConvertible::value)) { - // T is not a function type. We just call << to print p, - // relying on ADL to pick up user-defined << for their pointer - // types, if any. - *os << p; - } else { - // T is a function type, so '*os << p' doesn't do what we want - // (it just prints p as bool). We want to print p as a const - // void*. However, we cannot cast it to const void* directly, - // even using reinterpret_cast, as earlier versions of gcc - // (e.g. 3.4.5) cannot compile the cast when p is a function - // pointer. Casting to UInt64 first solves the problem. - *os << reinterpret_cast( - reinterpret_cast(p)); - } - } -} - -// Used to print a non-container, non-pointer value when the user -// doesn't define PrintTo() for it. -template -void DefaultPrintTo(IsNotContainer /* dummy */, - false_type /* is not a pointer */, - const T& value, ::std::ostream* os) { - ::testing_internal::DefaultPrintNonContainerTo(value, os); -} - -// Prints the given value using the << operator if it has one; -// otherwise prints the bytes in it. This is what -// UniversalPrinter::Print() does when PrintTo() is not specialized -// or overloaded for type T. -// -// A user can override this behavior for a class type Foo by defining -// an overload of PrintTo() in the namespace where Foo is defined. We -// give the user this option as sometimes defining a << operator for -// Foo is not desirable (e.g. the coding style may prevent doing it, -// or there is already a << operator but it doesn't do what the user -// wants). -template -void PrintTo(const T& value, ::std::ostream* os) { - // DefaultPrintTo() is overloaded. The type of its first two - // arguments determine which version will be picked. If T is an - // STL-style container, the version for container will be called; if - // T is a pointer, the pointer version will be called; otherwise the - // generic version will be called. - // - // Note that we check for container types here, prior to we check - // for protocol message types in our operator<<. The rationale is: - // - // For protocol messages, we want to give people a chance to - // override Google Mock's format by defining a PrintTo() or - // operator<<. For STL containers, other formats can be - // incompatible with Google Mock's format for the container - // elements; therefore we check for container types here to ensure - // that our format is used. - // - // The second argument of DefaultPrintTo() is needed to bypass a bug - // in Symbian's C++ compiler that prevents it from picking the right - // overload between: - // - // PrintTo(const T& x, ...); - // PrintTo(T* x, ...); - DefaultPrintTo(IsContainerTest(0), is_pointer(), value, os); -} - -// The following list of PrintTo() overloads tells -// UniversalPrinter::Print() how to print standard types (built-in -// types, strings, plain arrays, and pointers). - -// Overloads for various char types. -GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); -GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); -inline void PrintTo(char c, ::std::ostream* os) { - // When printing a plain char, we always treat it as unsigned. This - // way, the output won't be affected by whether the compiler thinks - // char is signed or not. - PrintTo(static_cast(c), os); -} - -// Overloads for other simple built-in types. -inline void PrintTo(bool x, ::std::ostream* os) { - *os << (x ? "true" : "false"); -} - -// Overload for wchar_t type. -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. -GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); - -// Overloads for C strings. -GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); -inline void PrintTo(char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// signed/unsigned char is often used for representing binary data, so -// we print pointers to it as void* to be safe. -inline void PrintTo(const signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(const unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// MSVC can be configured to define wchar_t as a typedef of unsigned -// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native -// type. When wchar_t is a typedef, defining an overload for const -// wchar_t* would cause unsigned short* be printed as a wide string, -// possibly causing invalid memory accesses. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Overloads for wide C strings -GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); -inline void PrintTo(wchar_t* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -#endif - -// Overload for C arrays. Multi-dimensional arrays are printed -// properly. - -// Prints the given number of elements in an array, without printing -// the curly braces. -template -void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { - UniversalPrint(a[0], os); - for (size_t i = 1; i != count; i++) { - *os << ", "; - UniversalPrint(a[i], os); - } -} - -// Overloads for ::string and ::std::string. -#if GTEST_HAS_GLOBAL_STRING -GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); -inline void PrintTo(const ::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_STRING - -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); -inline void PrintTo(const ::std::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} - -// Overloads for ::wstring and ::std::wstring. -#if GTEST_HAS_GLOBAL_WSTRING -GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_TR1_TUPLE -// Overload for ::std::tr1::tuple. Needed for printing function arguments, -// which are packed as tuples. - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template -void PrintTupleTo(const T& t, ::std::ostream* os); - -// Overloaded PrintTo() for tuples of various arities. We support -// tuples of up-to 10 fields. The following implementation works -// regardless of whether tr1::tuple is implemented using the -// non-standard variadic template feature or not. - -inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template -void PrintTo( - const ::std::tr1::tuple& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} -#endif // GTEST_HAS_TR1_TUPLE - -// Overload for std::pair. -template -void PrintTo(const ::std::pair& value, ::std::ostream* os) { - *os << '('; - // We cannot use UniversalPrint(value.first, os) here, as T1 may be - // a reference type. The same for printing value.second. - UniversalPrinter::Print(value.first, os); - *os << ", "; - UniversalPrinter::Print(value.second, os); - *os << ')'; -} - -// Implements printing a non-reference type T by letting the compiler -// pick the right overload of PrintTo() for T. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - // Note: we deliberately don't call this PrintTo(), as that name - // conflicts with ::testing::internal::PrintTo in the body of the - // function. - static void Print(const T& value, ::std::ostream* os) { - // By default, ::testing::internal::PrintTo() is used for printing - // the value. - // - // Thanks to Koenig look-up, if T is a class and has its own - // PrintTo() function defined in its namespace, that function will - // be visible here. Since it is more specific than the generic ones - // in ::testing::internal, it will be picked by the compiler in the - // following statement - exactly what we want. - PrintTo(value, os); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// UniversalPrintArray(begin, len, os) prints an array of 'len' -// elements, starting at address 'begin'. -template -void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { - if (len == 0) { - *os << "{}"; - } else { - *os << "{ "; - const size_t kThreshold = 18; - const size_t kChunkSize = 8; - // If the array has more than kThreshold elements, we'll have to - // omit some details by printing only the first and the last - // kChunkSize elements. - // TODO(wan@google.com): let the user control the threshold using a flag. - if (len <= kThreshold) { - PrintRawArrayTo(begin, len, os); - } else { - PrintRawArrayTo(begin, kChunkSize, os); - *os << ", ..., "; - PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); - } - *os << " }"; - } -} -// This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray(const char* begin, - size_t len, - ::std::ostream* os); - -// Implements printing an array type T[N]. -template -class UniversalPrinter { - public: - // Prints the given array, omitting some elements when there are too - // many. - static void Print(const T (&a)[N], ::std::ostream* os) { - UniversalPrintArray(a, N, os); - } -}; - -// Implements printing a reference type T&. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - static void Print(const T& value, ::std::ostream* os) { - // Prints the address of the value. We use reinterpret_cast here - // as static_cast doesn't compile when T is a function type. - *os << "@" << reinterpret_cast(&value) << " "; - - // Then prints the value itself. - UniversalPrint(value, os); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// Prints a value tersely: for a reference type, the referenced value -// (but not the address) is printed; for a (const) char pointer, the -// NUL-terminated string (but not the pointer) is printed. -template -void UniversalTersePrint(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); -} -inline void UniversalTersePrint(const char* str, ::std::ostream* os) { - if (str == NULL) { - *os << "NULL"; - } else { - UniversalPrint(string(str), os); - } -} -inline void UniversalTersePrint(char* str, ::std::ostream* os) { - UniversalTersePrint(static_cast(str), os); -} - -// Prints a value using the type inferred by the compiler. The -// difference between this and UniversalTersePrint() is that for a -// (const) char pointer, this prints both the pointer and the -// NUL-terminated string. -template -void UniversalPrint(const T& value, ::std::ostream* os) { - UniversalPrinter::Print(value, os); -} - -#if GTEST_HAS_TR1_TUPLE -typedef ::std::vector Strings; - -// This helper template allows PrintTo() for tuples and -// UniversalTersePrintTupleFieldsToStrings() to be defined by -// induction on the number of tuple fields. The idea is that -// TuplePrefixPrinter::PrintPrefixTo(t, os) prints the first N -// fields in tuple t, and can be defined in terms of -// TuplePrefixPrinter. - -// The inductive case. -template -struct TuplePrefixPrinter { - // Prints the first N fields of a tuple. - template - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - TuplePrefixPrinter::PrintPrefixTo(t, os); - *os << ", "; - UniversalPrinter::type> - ::Print(::std::tr1::get(t), os); - } - - // Tersely prints the first N fields of a tuple to a string vector, - // one element for each field. - template - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - TuplePrefixPrinter::TersePrintPrefixToStrings(t, strings); - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Base cases. -template <> -struct TuplePrefixPrinter<0> { - template - static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} - - template - static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} -}; -// We have to specialize the entire TuplePrefixPrinter<> class -// template here, even though the definition of -// TersePrintPrefixToStrings() is the same as the generic version, as -// Embarcadero (formerly CodeGear, formerly Borland) C++ doesn't -// support specializing a method template of a class template. -template <> -struct TuplePrefixPrinter<1> { - template - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - UniversalPrinter::type>:: - Print(::std::tr1::get<0>(t), os); - } - - template - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get<0>(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template -void PrintTupleTo(const T& t, ::std::ostream* os) { - *os << "("; - TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: - PrintPrefixTo(t, os); - *os << ")"; -} - -// Prints the fields of a tuple tersely to a string vector, one -// element for each field. See the comment before -// UniversalTersePrint() for how we define "tersely". -template -Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { - Strings result; - TuplePrefixPrinter< ::std::tr1::tuple_size::value>:: - TersePrintPrefixToStrings(value, &result); - return result; -} -#endif // GTEST_HAS_TR1_TUPLE - -} // namespace internal - -template -::std::string PrintToString(const T& value) { - ::std::stringstream ss; - internal::UniversalTersePrint(value, &ss); - return ss.str(); -} - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -#if GTEST_HAS_PARAM_TEST - -namespace testing { -namespace internal { - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Outputs a message explaining invalid registration of different -// fixture class for the same test case. This may happen when -// TEST_P macro is used to define two tests with the same name -// but in different namespaces. -GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, - const char* file, int line); - -template class ParamGeneratorInterface; -template class ParamGenerator; - -// Interface for iterating over elements provided by an implementation -// of ParamGeneratorInterface. -template -class ParamIteratorInterface { - public: - virtual ~ParamIteratorInterface() {} - // A pointer to the base generator instance. - // Used only for the purposes of iterator comparison - // to make sure that two iterators belong to the same generator. - virtual const ParamGeneratorInterface* BaseGenerator() const = 0; - // Advances iterator to point to the next element - // provided by the generator. The caller is responsible - // for not calling Advance() on an iterator equal to - // BaseGenerator()->End(). - virtual void Advance() = 0; - // Clones the iterator object. Used for implementing copy semantics - // of ParamIterator. - virtual ParamIteratorInterface* Clone() const = 0; - // Dereferences the current iterator and provides (read-only) access - // to the pointed value. It is the caller's responsibility not to call - // Current() on an iterator equal to BaseGenerator()->End(). - // Used for implementing ParamGenerator::operator*(). - virtual const T* Current() const = 0; - // Determines whether the given iterator and other point to the same - // element in the sequence generated by the generator. - // Used for implementing ParamGenerator::operator==(). - virtual bool Equals(const ParamIteratorInterface& other) const = 0; -}; - -// Class iterating over elements provided by an implementation of -// ParamGeneratorInterface. It wraps ParamIteratorInterface -// and implements the const forward iterator concept. -template -class ParamIterator { - public: - typedef T value_type; - typedef const T& reference; - typedef ptrdiff_t difference_type; - - // ParamIterator assumes ownership of the impl_ pointer. - ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} - ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); - return *this; - } - - const T& operator*() const { return *impl_->Current(); } - const T* operator->() const { return impl_->Current(); } - // Prefix version of operator++. - ParamIterator& operator++() { - impl_->Advance(); - return *this; - } - // Postfix version of operator++. - ParamIterator operator++(int /*unused*/) { - ParamIteratorInterface* clone = impl_->Clone(); - impl_->Advance(); - return ParamIterator(clone); - } - bool operator==(const ParamIterator& other) const { - return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); - } - bool operator!=(const ParamIterator& other) const { - return !(*this == other); - } - - private: - friend class ParamGenerator; - explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} - scoped_ptr > impl_; -}; - -// ParamGeneratorInterface is the binary interface to access generators -// defined in other translation units. -template -class ParamGeneratorInterface { - public: - typedef T ParamType; - - virtual ~ParamGeneratorInterface() {} - - // Generator interface definition - virtual ParamIteratorInterface* Begin() const = 0; - virtual ParamIteratorInterface* End() const = 0; -}; - -// Wraps ParamGeneratorInterface and provides general generator syntax -// compatible with the STL Container concept. -// This class implements copy initialization semantics and the contained -// ParamGeneratorInterface instance is shared among all copies -// of the original object. This is possible because that instance is immutable. -template -class ParamGenerator { - public: - typedef ParamIterator iterator; - - explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} - ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} - - ParamGenerator& operator=(const ParamGenerator& other) { - impl_ = other.impl_; - return *this; - } - - iterator begin() const { return iterator(impl_->Begin()); } - iterator end() const { return iterator(impl_->End()); } - - private: - linked_ptr > impl_; -}; - -// Generates values from a range of two comparable values. Can be used to -// generate sequences of user-defined types that implement operator+() and -// operator<(). -// This class is used in the Range() function. -template -class RangeGenerator : public ParamGeneratorInterface { - public: - RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} - virtual ~RangeGenerator() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, begin_, 0, step_); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, end_, end_index_, step_); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, T value, int index, - IncrementT step) - : base_(base), value_(value), index_(index), step_(step) {} - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - virtual void Advance() { - value_ = value_ + step_; - index_++; - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const T* Current() const { return &value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const int other_index = - CheckedDowncastToActualType(&other)->index_; - return index_ == other_index; - } - - private: - Iterator(const Iterator& other) - : ParamIteratorInterface(), - base_(other.base_), value_(other.value_), index_(other.index_), - step_(other.step_) {} - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - T value_; - int index_; - const IncrementT step_; - }; // class RangeGenerator::Iterator - - static int CalculateEndIndex(const T& begin, - const T& end, - const IncrementT& step) { - int end_index = 0; - for (T i = begin; i < end; i = i + step) - end_index++; - return end_index; - } - - // No implementation - assignment is unsupported. - void operator=(const RangeGenerator& other); - - const T begin_; - const T end_; - const IncrementT step_; - // The index for the end() iterator. All the elements in the generated - // sequence are indexed (0-based) to aid iterator comparison. - const int end_index_; -}; // class RangeGenerator - - -// Generates values from a pair of STL-style iterators. Used in the -// ValuesIn() function. The elements are copied from the source range -// since the source can be located on the stack, and the generator -// is likely to persist beyond that stack frame. -template -class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { - public: - template - ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) - : container_(begin, end) {} - virtual ~ValuesInIteratorRangeGenerator() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, container_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, container_.end()); - } - - private: - typedef typename ::std::vector ContainerType; - - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - typename ContainerType::const_iterator iterator) - : base_(base), iterator_(iterator) {} - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - virtual void Advance() { - ++iterator_; - value_.reset(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - // We need to use cached value referenced by iterator_ because *iterator_ - // can return a temporary object (and of type other then T), so just - // having "return &*iterator_;" doesn't work. - // value_ is updated here and not in Advance() because Advance() - // can advance iterator_ beyond the end of the range, and we cannot - // detect that fact. The client code, on the other hand, is - // responsible for not calling Current() on an out-of-range iterator. - virtual const T* Current() const { - if (value_.get() == NULL) - value_.reset(new T(*iterator_)); - return value_.get(); - } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - return iterator_ == - CheckedDowncastToActualType(&other)->iterator_; - } - - private: - Iterator(const Iterator& other) - // The explicit constructor call suppresses a false warning - // emitted by gcc when supplied with the -Wextra option. - : ParamIteratorInterface(), - base_(other.base_), - iterator_(other.iterator_) {} - - const ParamGeneratorInterface* const base_; - typename ContainerType::const_iterator iterator_; - // A cached value of *iterator_. We keep it here to allow access by - // pointer in the wrapping iterator's operator->(). - // value_ needs to be mutable to be accessed in Current(). - // Use of scoped_ptr helps manage cached value's lifetime, - // which is bound by the lifespan of the iterator itself. - mutable scoped_ptr value_; - }; // class ValuesInIteratorRangeGenerator::Iterator - - // No implementation - assignment is unsupported. - void operator=(const ValuesInIteratorRangeGenerator& other); - - const ContainerType container_; -}; // class ValuesInIteratorRangeGenerator - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Stores a parameter value and later creates tests parameterized with that -// value. -template -class ParameterizedTestFactory : public TestFactoryBase { - public: - typedef typename TestClass::ParamType ParamType; - explicit ParameterizedTestFactory(ParamType parameter) : - parameter_(parameter) {} - virtual Test* CreateTest() { - TestClass::SetParam(¶meter_); - return new TestClass(); - } - - private: - const ParamType parameter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactoryBase is a base class for meta-factories that create -// test factories for passing into MakeAndRegisterTestInfo function. -template -class TestMetaFactoryBase { - public: - virtual ~TestMetaFactoryBase() {} - - virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactory creates test factories for passing into -// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives -// ownership of test factory pointer, same factory object cannot be passed -// into that method twice. But ParameterizedTestCaseInfo is going to call -// it for each Test/Parameter value combination. Thus it needs meta factory -// creator class. -template -class TestMetaFactory - : public TestMetaFactoryBase { - public: - typedef typename TestCase::ParamType ParamType; - - TestMetaFactory() {} - - virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { - return new ParameterizedTestFactory(parameter); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseInfoBase is a generic interface -// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase -// accumulates test information provided by TEST_P macro invocations -// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations -// and uses that information to register all resulting test instances -// in RegisterTests method. The ParameterizeTestCaseRegistry class holds -// a collection of pointers to the ParameterizedTestCaseInfo objects -// and calls RegisterTests() on each of them when asked. -class ParameterizedTestCaseInfoBase { - public: - virtual ~ParameterizedTestCaseInfoBase() {} - - // Base part of test case name for display purposes. - virtual const string& GetTestCaseName() const = 0; - // Test case id to verify identity. - virtual TypeId GetTestCaseTypeId() const = 0; - // UnitTest class invokes this method to register tests in this - // test case right before running them in RUN_ALL_TESTS macro. - // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. - virtual void RegisterTests() = 0; - - protected: - ParameterizedTestCaseInfoBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P -// macro invocations for a particular test case and generators -// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that -// test case. It registers tests with all values generated by all -// generators when asked. -template -class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { - public: - // ParamType and GeneratorCreationFunc are private types but are required - // for declarations of public methods AddTestPattern() and - // AddTestCaseInstantiation(). - typedef typename TestCase::ParamType ParamType; - // A function that returns an instance of appropriate generator type. - typedef ParamGenerator(GeneratorCreationFunc)(); - - explicit ParameterizedTestCaseInfo(const char* name) - : test_case_name_(name) {} - - // Test case base name for display purposes. - virtual const string& GetTestCaseName() const { return test_case_name_; } - // Test case id to verify identity. - virtual TypeId GetTestCaseTypeId() const { return GetTypeId(); } - // TEST_P macro uses AddTestPattern() to record information - // about a single test in a LocalTestInfo structure. - // test_case_name is the base name of the test case (without invocation - // prefix). test_base_name is the name of an individual test without - // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is - // test case base name and DoBar is test base name. - void AddTestPattern(const char* test_case_name, - const char* test_base_name, - TestMetaFactoryBase* meta_factory) { - tests_.push_back(linked_ptr(new TestInfo(test_case_name, - test_base_name, - meta_factory))); - } - // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information - // about a generator. - int AddTestCaseInstantiation(const string& instantiation_name, - GeneratorCreationFunc* func, - const char* /* file */, - int /* line */) { - instantiations_.push_back(::std::make_pair(instantiation_name, func)); - return 0; // Return value used only to run this method in namespace scope. - } - // UnitTest class invokes this method to register tests in this test case - // test cases right before running tests in RUN_ALL_TESTS macro. - // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. - // UnitTest has a guard to prevent from calling this method more then once. - virtual void RegisterTests() { - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { - linked_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); gen_it != instantiations_.end(); - ++gen_it) { - const string& instantiation_name = gen_it->first; - ParamGenerator generator((*gen_it->second)()); - - Message test_case_name_stream; - if ( !instantiation_name.empty() ) - test_case_name_stream << instantiation_name << "/"; - test_case_name_stream << test_info->test_case_base_name; - - int i = 0; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { - Message test_name_stream; - test_name_stream << test_info->test_base_name << "/" << i; - MakeAndRegisterTestInfo( - test_case_name_stream.GetString().c_str(), - test_name_stream.GetString().c_str(), - NULL, // No type parameter. - PrintToString(*param_it).c_str(), - GetTestCaseTypeId(), - TestCase::SetUpTestCase, - TestCase::TearDownTestCase, - test_info->test_meta_factory->CreateTestFactory(*param_it)); - } // for param_it - } // for gen_it - } // for test_it - } // RegisterTests - - private: - // LocalTestInfo structure keeps information about a single test registered - // with TEST_P macro. - struct TestInfo { - TestInfo(const char* a_test_case_base_name, - const char* a_test_base_name, - TestMetaFactoryBase* a_test_meta_factory) : - test_case_base_name(a_test_case_base_name), - test_base_name(a_test_base_name), - test_meta_factory(a_test_meta_factory) {} - - const string test_case_base_name; - const string test_base_name; - const scoped_ptr > test_meta_factory; - }; - typedef ::std::vector > TestInfoContainer; - // Keeps pairs of - // received from INSTANTIATE_TEST_CASE_P macros. - typedef ::std::vector > - InstantiationContainer; - - const string test_case_name_; - TestInfoContainer tests_; - InstantiationContainer instantiations_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); -}; // class ParameterizedTestCaseInfo - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase -// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P -// macros use it to locate their corresponding ParameterizedTestCaseInfo -// descriptors. -class ParameterizedTestCaseRegistry { - public: - ParameterizedTestCaseRegistry() {} - ~ParameterizedTestCaseRegistry() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - delete *it; - } - } - - // Looks up or creates and returns a structure containing information about - // tests and instantiations of a particular test case. - template - ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, - const char* file, - int line) { - ParameterizedTestCaseInfo* typed_test_info = NULL; - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - if ((*it)->GetTestCaseName() == test_case_name) { - if ((*it)->GetTestCaseTypeId() != GetTypeId()) { - // Complain about incorrect usage of Google Test facilities - // and terminate the program since we cannot guaranty correct - // test case setup and tear-down in this case. - ReportInvalidTestCaseType(test_case_name, file, line); - posix::Abort(); - } else { - // At this point we are sure that the object we found is of the same - // type we are looking for, so we downcast it to that type - // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestCaseInfo >(*it); - } - break; - } - } - if (typed_test_info == NULL) { - typed_test_info = new ParameterizedTestCaseInfo(test_case_name); - test_case_infos_.push_back(typed_test_info); - } - return typed_test_info; - } - void RegisterTests() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - (*it)->RegisterTests(); - } - } - - private: - typedef ::std::vector TestCaseInfoContainer; - - TestCaseInfoContainer test_case_infos_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); -}; - -} // namespace internal -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ -// This file was GENERATED by command: -// pump.py gtest-param-util-generated.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: vladl@google.com (Vlad Losev) - -// Type and function utilities for implementing parameterized tests. -// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently Google Test supports at most 50 arguments in Values, -// and at most 10 arguments in Combine. Please contact -// googletestframework@googlegroups.com if you need more. -// Please note that the number of arguments to Combine is limited -// by the maximum arity of the implementation of tr1::tuple which is -// currently set at 10. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ - -// scripts/fuse_gtest.py depends on gtest's own header being #included -// *unconditionally*. Therefore these #includes cannot be moved -// inside #if GTEST_HAS_PARAM_TEST. - -#if GTEST_HAS_PARAM_TEST - -namespace testing { - -// Forward declarations of ValuesIn(), which is implemented in -// include/gtest/gtest-param-test.h. -template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end); - -template -internal::ParamGenerator ValuesIn(const T (&array)[N]); - -template -internal::ParamGenerator ValuesIn( - const Container& container); - -namespace internal { - -// Used in the Values() function to provide polymorphic capabilities. -template -class ValueArray1 { - public: - explicit ValueArray1(T1 v1) : v1_(v1) {} - - template - operator ParamGenerator() const { return ValuesIn(&v1_, &v1_ + 1); } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray1& other); - - const T1 v1_; -}; - -template -class ValueArray2 { - public: - ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray2& other); - - const T1 v1_; - const T2 v2_; -}; - -template -class ValueArray3 { - public: - ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray3& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; -}; - -template -class ValueArray4 { - public: - ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray4& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; -}; - -template -class ValueArray5 { - public: - ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray5& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; -}; - -template -class ValueArray6 { - public: - ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray6& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; -}; - -template -class ValueArray7 { - public: - ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray7& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; -}; - -template -class ValueArray8 { - public: - ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray8& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; -}; - -template -class ValueArray9 { - public: - ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray9& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; -}; - -template -class ValueArray10 { - public: - ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray10& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; -}; - -template -class ValueArray11 { - public: - ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray11& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; -}; - -template -class ValueArray12 { - public: - ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray12& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; -}; - -template -class ValueArray13 { - public: - ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray13& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; -}; - -template -class ValueArray14 { - public: - ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray14& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; -}; - -template -class ValueArray15 { - public: - ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray15& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; -}; - -template -class ValueArray16 { - public: - ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray16& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; -}; - -template -class ValueArray17 { - public: - ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray17& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; -}; - -template -class ValueArray18 { - public: - ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray18& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; -}; - -template -class ValueArray19 { - public: - ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray19& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; -}; - -template -class ValueArray20 { - public: - ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray20& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; -}; - -template -class ValueArray21 { - public: - ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray21& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; -}; - -template -class ValueArray22 { - public: - ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray22& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; -}; - -template -class ValueArray23 { - public: - ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, - v23_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray23& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; -}; - -template -class ValueArray24 { - public: - ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray24& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; -}; - -template -class ValueArray25 { - public: - ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray25& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; -}; - -template -class ValueArray26 { - public: - ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray26& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; -}; - -template -class ValueArray27 { - public: - ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray27& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; -}; - -template -class ValueArray28 { - public: - ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray28& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; -}; - -template -class ValueArray29 { - public: - ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray29& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; -}; - -template -class ValueArray30 { - public: - ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray30& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; -}; - -template -class ValueArray31 { - public: - ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray31& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; -}; - -template -class ValueArray32 { - public: - ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray32& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; -}; - -template -class ValueArray33 { - public: - ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray33& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; -}; - -template -class ValueArray34 { - public: - ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray34& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; -}; - -template -class ValueArray35 { - public: - ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, - v35_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray35& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; -}; - -template -class ValueArray36 { - public: - ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray36& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; -}; - -template -class ValueArray37 { - public: - ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray37& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; -}; - -template -class ValueArray38 { - public: - ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray38& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; -}; - -template -class ValueArray39 { - public: - ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray39& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; -}; - -template -class ValueArray40 { - public: - ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray40& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; -}; - -template -class ValueArray41 { - public: - ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray41& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; -}; - -template -class ValueArray42 { - public: - ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray42& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; -}; - -template -class ValueArray43 { - public: - ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), - v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray43& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; -}; - -template -class ValueArray44 { - public: - ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), - v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), - v43_(v43), v44_(v44) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray44& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; -}; - -template -class ValueArray45 { - public: - ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), - v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray45& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; -}; - -template -class ValueArray46 { - public: - ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray46& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; -}; - -template -class ValueArray47 { - public: - ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), - v47_(v47) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, - v47_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray47& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; -}; - -template -class ValueArray48 { - public: - ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), - v46_(v46), v47_(v47), v48_(v48) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray48& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; -}; - -template -class ValueArray49 { - public: - ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, - T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray49& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; - const T49 v49_; -}; - -template -class ValueArray50 { - public: - ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, - T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} - - template - operator ParamGenerator() const { - const T array[] = {v1_, v2_, v3_, v4_, v5_, v6_, v7_, v8_, v9_, v10_, v11_, - v12_, v13_, v14_, v15_, v16_, v17_, v18_, v19_, v20_, v21_, v22_, v23_, - v24_, v25_, v26_, v27_, v28_, v29_, v30_, v31_, v32_, v33_, v34_, v35_, - v36_, v37_, v38_, v39_, v40_, v41_, v42_, v43_, v44_, v45_, v46_, v47_, - v48_, v49_, v50_}; - return ValuesIn(array); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const ValueArray50& other); - - const T1 v1_; - const T2 v2_; - const T3 v3_; - const T4 v4_; - const T5 v5_; - const T6 v6_; - const T7 v7_; - const T8 v8_; - const T9 v9_; - const T10 v10_; - const T11 v11_; - const T12 v12_; - const T13 v13_; - const T14 v14_; - const T15 v15_; - const T16 v16_; - const T17 v17_; - const T18 v18_; - const T19 v19_; - const T20 v20_; - const T21 v21_; - const T22 v22_; - const T23 v23_; - const T24 v24_; - const T25 v25_; - const T26 v26_; - const T27 v27_; - const T28 v28_; - const T29 v29_; - const T30 v30_; - const T31 v31_; - const T32 v32_; - const T33 v33_; - const T34 v34_; - const T35 v35_; - const T36 v36_; - const T37 v37_; - const T38 v38_; - const T39 v39_; - const T40 v40_; - const T41 v41_; - const T42 v42_; - const T43 v43_; - const T44 v44_; - const T45 v45_; - const T46 v46_; - const T47 v47_; - const T48 v48_; - const T49 v49_; - const T50 v50_; -}; - -# if GTEST_HAS_COMBINE -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Generates values from the Cartesian product of values produced -// by the argument generators. -// -template -class CartesianProductGenerator2 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator2(const ParamGenerator& g1, - const ParamGenerator& g2) - : g1_(g1), g2_(g2) {} - virtual ~CartesianProductGenerator2() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current2_; - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - ParamType current_value_; - }; // class CartesianProductGenerator2::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator2& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; -}; // class CartesianProductGenerator2 - - -template -class CartesianProductGenerator3 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator3(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3) - : g1_(g1), g2_(g2), g3_(g3) {} - virtual ~CartesianProductGenerator3() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current3_; - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - ParamType current_value_; - }; // class CartesianProductGenerator3::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator3& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; -}; // class CartesianProductGenerator3 - - -template -class CartesianProductGenerator4 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator4(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} - virtual ~CartesianProductGenerator4() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current4_; - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - ParamType current_value_; - }; // class CartesianProductGenerator4::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator4& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; -}; // class CartesianProductGenerator4 - - -template -class CartesianProductGenerator5 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator5(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} - virtual ~CartesianProductGenerator5() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current5_; - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - ParamType current_value_; - }; // class CartesianProductGenerator5::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator5& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; -}; // class CartesianProductGenerator5 - - -template -class CartesianProductGenerator6 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator6(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} - virtual ~CartesianProductGenerator6() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current6_; - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - ParamType current_value_; - }; // class CartesianProductGenerator6::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator6& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; -}; // class CartesianProductGenerator6 - - -template -class CartesianProductGenerator7 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator7(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} - virtual ~CartesianProductGenerator7() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current7_; - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - ParamType current_value_; - }; // class CartesianProductGenerator7::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator7& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; -}; // class CartesianProductGenerator7 - - -template -class CartesianProductGenerator8 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator8(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} - virtual ~CartesianProductGenerator8() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current8_; - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - ParamType current_value_; - }; // class CartesianProductGenerator8::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator8& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; -}; // class CartesianProductGenerator8 - - -template -class CartesianProductGenerator9 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator9(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} - virtual ~CartesianProductGenerator9() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current9_; - if (current9_ == end9_) { - current9_ = begin9_; - ++current8_; - } - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - const typename ParamGenerator::iterator begin9_; - const typename ParamGenerator::iterator end9_; - typename ParamGenerator::iterator current9_; - ParamType current_value_; - }; // class CartesianProductGenerator9::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator9& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; - const ParamGenerator g9_; -}; // class CartesianProductGenerator9 - - -template -class CartesianProductGenerator10 - : public ParamGeneratorInterface< ::std::tr1::tuple > { - public: - typedef ::std::tr1::tuple ParamType; - - CartesianProductGenerator10(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9, - const ParamGenerator& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} - virtual ~CartesianProductGenerator10() {} - - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end(), g10_, g10_.end()); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9, - const ParamGenerator& g10, - const typename ParamGenerator::iterator& current10) - : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9), - begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { - ComputeCurrentValue(); - } - virtual ~Iterator() {} - - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - virtual void Advance() { - assert(!AtEnd()); - ++current10_; - if (current10_ == end10_) { - current10_ = begin10_; - ++current9_; - } - if (current9_ == end9_) { - current9_ = begin9_; - ++current8_; - } - if (current8_ == end8_) { - current8_ = begin8_; - ++current7_; - } - if (current7_ == end7_) { - current7_ = begin7_; - ++current6_; - } - if (current6_ == end6_) { - current6_ = begin6_; - ++current5_; - } - if (current5_ == end5_) { - current5_ = begin5_; - ++current4_; - } - if (current4_ == end4_) { - current4_ = begin4_; - ++current3_; - } - if (current3_ == end3_) { - current3_ = begin3_; - ++current2_; - } - if (current2_ == end2_) { - current2_ = begin2_; - ++current1_; - } - ComputeCurrentValue(); - } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } - virtual const ParamType* Current() const { return ¤t_value_; } - virtual bool Equals(const ParamIteratorInterface& other) const { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_ && - current10_ == typed_other->current10_); - } - - private: - Iterator(const Iterator& other) - : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_), - begin10_(other.begin10_), - end10_(other.end10_), - current10_(other.current10_) { - ComputeCurrentValue(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_, *current10_); - } - bool AtEnd() const { - // We must report iterator past the end of the range when either of the - // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_ || - current10_ == end10_; - } - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. - // current[i]_ is the actual traversing iterator. - const typename ParamGenerator::iterator begin1_; - const typename ParamGenerator::iterator end1_; - typename ParamGenerator::iterator current1_; - const typename ParamGenerator::iterator begin2_; - const typename ParamGenerator::iterator end2_; - typename ParamGenerator::iterator current2_; - const typename ParamGenerator::iterator begin3_; - const typename ParamGenerator::iterator end3_; - typename ParamGenerator::iterator current3_; - const typename ParamGenerator::iterator begin4_; - const typename ParamGenerator::iterator end4_; - typename ParamGenerator::iterator current4_; - const typename ParamGenerator::iterator begin5_; - const typename ParamGenerator::iterator end5_; - typename ParamGenerator::iterator current5_; - const typename ParamGenerator::iterator begin6_; - const typename ParamGenerator::iterator end6_; - typename ParamGenerator::iterator current6_; - const typename ParamGenerator::iterator begin7_; - const typename ParamGenerator::iterator end7_; - typename ParamGenerator::iterator current7_; - const typename ParamGenerator::iterator begin8_; - const typename ParamGenerator::iterator end8_; - typename ParamGenerator::iterator current8_; - const typename ParamGenerator::iterator begin9_; - const typename ParamGenerator::iterator end9_; - typename ParamGenerator::iterator current9_; - const typename ParamGenerator::iterator begin10_; - const typename ParamGenerator::iterator end10_; - typename ParamGenerator::iterator current10_; - ParamType current_value_; - }; // class CartesianProductGenerator10::Iterator - - // No implementation - assignment is unsupported. - void operator=(const CartesianProductGenerator10& other); - - const ParamGenerator g1_; - const ParamGenerator g2_; - const ParamGenerator g3_; - const ParamGenerator g4_; - const ParamGenerator g5_; - const ParamGenerator g6_; - const ParamGenerator g7_; - const ParamGenerator g8_; - const ParamGenerator g9_; - const ParamGenerator g10_; -}; // class CartesianProductGenerator10 - - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Helper classes providing Combine() with polymorphic features. They allow -// casting CartesianProductGeneratorN to ParamGenerator if T is -// convertible to U. -// -template -class CartesianProductHolder2 { - public: -CartesianProductHolder2(const Generator1& g1, const Generator2& g2) - : g1_(g1), g2_(g2) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator2( - static_cast >(g1_), - static_cast >(g2_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder2& other); - - const Generator1 g1_; - const Generator2 g2_; -}; // class CartesianProductHolder2 - -template -class CartesianProductHolder3 { - public: -CartesianProductHolder3(const Generator1& g1, const Generator2& g2, - const Generator3& g3) - : g1_(g1), g2_(g2), g3_(g3) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator3( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder3& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; -}; // class CartesianProductHolder3 - -template -class CartesianProductHolder4 { - public: -CartesianProductHolder4(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator4( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder4& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; -}; // class CartesianProductHolder4 - -template -class CartesianProductHolder5 { - public: -CartesianProductHolder5(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator5( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder5& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; -}; // class CartesianProductHolder5 - -template -class CartesianProductHolder6 { - public: -CartesianProductHolder6(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator6( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder6& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; -}; // class CartesianProductHolder6 - -template -class CartesianProductHolder7 { - public: -CartesianProductHolder7(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator7( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder7& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; -}; // class CartesianProductHolder7 - -template -class CartesianProductHolder8 { - public: -CartesianProductHolder8(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator8( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder8& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; -}; // class CartesianProductHolder8 - -template -class CartesianProductHolder9 { - public: -CartesianProductHolder9(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator9( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder9& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; - const Generator9 g9_; -}; // class CartesianProductHolder9 - -template -class CartesianProductHolder10 { - public: -CartesianProductHolder10(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9, const Generator10& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} - template - operator ParamGenerator< ::std::tr1::tuple >() const { - return ParamGenerator< ::std::tr1::tuple >( - new CartesianProductGenerator10( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_), - static_cast >(g10_))); - } - - private: - // No implementation - assignment is unsupported. - void operator=(const CartesianProductHolder10& other); - - const Generator1 g1_; - const Generator2 g2_; - const Generator3 g3_; - const Generator4 g4_; - const Generator5 g5_; - const Generator6 g6_; - const Generator7 g7_; - const Generator8 g8_; - const Generator9 g9_; - const Generator10 g10_; -}; // class CartesianProductHolder10 - -# endif // GTEST_HAS_COMBINE - -} // namespace internal -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ - -#if GTEST_HAS_PARAM_TEST - -namespace testing { - -// Functions producing parameter generators. -// -// Google Test uses these generators to produce parameters for value- -// parameterized tests. When a parameterized test case is instantiated -// with a particular generator, Google Test creates and runs tests -// for each element in the sequence produced by the generator. -// -// In the following sample, tests from test case FooTest are instantiated -// each three times with parameter values 3, 5, and 8: -// -// class FooTest : public TestWithParam { ... }; -// -// TEST_P(FooTest, TestThis) { -// } -// TEST_P(FooTest, TestThat) { -// } -// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); -// - -// Range() returns generators providing sequences of values in a range. -// -// Synopsis: -// Range(start, end) -// - returns a generator producing a sequence of values {start, start+1, -// start+2, ..., }. -// Range(start, end, step) -// - returns a generator producing a sequence of values {start, start+step, -// start+step+step, ..., }. -// Notes: -// * The generated sequences never include end. For example, Range(1, 5) -// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) -// returns a generator producing {1, 3, 5, 7}. -// * start and end must have the same type. That type may be any integral or -// floating-point type or a user defined type satisfying these conditions: -// * It must be assignable (have operator=() defined). -// * It must have operator+() (operator+(int-compatible type) for -// two-operand version). -// * It must have operator<() defined. -// Elements in the resulting sequences will also have that type. -// * Condition start < end must be satisfied in order for resulting sequences -// to contain any elements. -// -template -internal::ParamGenerator Range(T start, T end, IncrementT step) { - return internal::ParamGenerator( - new internal::RangeGenerator(start, end, step)); -} - -template -internal::ParamGenerator Range(T start, T end) { - return Range(start, end, 1); -} - -// ValuesIn() function allows generation of tests with parameters coming from -// a container. -// -// Synopsis: -// ValuesIn(const T (&array)[N]) -// - returns a generator producing sequences with elements from -// a C-style array. -// ValuesIn(const Container& container) -// - returns a generator producing sequences with elements from -// an STL-style container. -// ValuesIn(Iterator begin, Iterator end) -// - returns a generator producing sequences with elements from -// a range [begin, end) defined by a pair of STL-style iterators. These -// iterators can also be plain C pointers. -// -// Please note that ValuesIn copies the values from the containers -// passed in and keeps them to generate tests in RUN_ALL_TESTS(). -// -// Examples: -// -// This instantiates tests from test case StringTest -// each with C-string values of "foo", "bar", and "baz": -// -// const char* strings[] = {"foo", "bar", "baz"}; -// INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); -// -// This instantiates tests from test case StlStringTest -// each with STL strings with values "a" and "b": -// -// ::std::vector< ::std::string> GetParameterStrings() { -// ::std::vector< ::std::string> v; -// v.push_back("a"); -// v.push_back("b"); -// return v; -// } -// -// INSTANTIATE_TEST_CASE_P(CharSequence, -// StlStringTest, -// ValuesIn(GetParameterStrings())); -// -// -// This will also instantiate tests from CharTest -// each with parameter values 'a' and 'b': -// -// ::std::list GetParameterChars() { -// ::std::list list; -// list.push_back('a'); -// list.push_back('b'); -// return list; -// } -// ::std::list l = GetParameterChars(); -// INSTANTIATE_TEST_CASE_P(CharSequence2, -// CharTest, -// ValuesIn(l.begin(), l.end())); -// -template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end) { - typedef typename ::testing::internal::IteratorTraits - ::value_type ParamType; - return internal::ParamGenerator( - new internal::ValuesInIteratorRangeGenerator(begin, end)); -} - -template -internal::ParamGenerator ValuesIn(const T (&array)[N]) { - return ValuesIn(array, array + N); -} - -template -internal::ParamGenerator ValuesIn( - const Container& container) { - return ValuesIn(container.begin(), container.end()); -} - -// Values() allows generating tests from explicitly specified list of -// parameters. -// -// Synopsis: -// Values(T v1, T v2, ..., T vN) -// - returns a generator producing sequences with elements v1, v2, ..., vN. -// -// For example, this instantiates tests from test case BarTest each -// with values "one", "two", and "three": -// -// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); -// -// This instantiates tests from test case BazTest each with values 1, 2, 3.5. -// The exact type of values will depend on the type of parameter in BazTest. -// -// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); -// -// Currently, Values() supports from 1 to 50 parameters. -// -template -internal::ValueArray1 Values(T1 v1) { - return internal::ValueArray1(v1); -} - -template -internal::ValueArray2 Values(T1 v1, T2 v2) { - return internal::ValueArray2(v1, v2); -} - -template -internal::ValueArray3 Values(T1 v1, T2 v2, T3 v3) { - return internal::ValueArray3(v1, v2, v3); -} - -template -internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { - return internal::ValueArray4(v1, v2, v3, v4); -} - -template -internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5) { - return internal::ValueArray5(v1, v2, v3, v4, v5); -} - -template -internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6) { - return internal::ValueArray6(v1, v2, v3, v4, v5, v6); -} - -template -internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7) { - return internal::ValueArray7(v1, v2, v3, v4, v5, - v6, v7); -} - -template -internal::ValueArray8 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { - return internal::ValueArray8(v1, v2, v3, v4, - v5, v6, v7, v8); -} - -template -internal::ValueArray9 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { - return internal::ValueArray9(v1, v2, v3, - v4, v5, v6, v7, v8, v9); -} - -template -internal::ValueArray10 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { - return internal::ValueArray10(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10); -} - -template -internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) { - return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); -} - -template -internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) { - return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); -} - -template -internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) { - return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); -} - -template -internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { - return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14); -} - -template -internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { - return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15); -} - -template -internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16) { - return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16); -} - -template -internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17) { - return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17); -} - -template -internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18) { - return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18); -} - -template -internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { - return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); -} - -template -internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { - return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); -} - -template -internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { - return internal::ValueArray21(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); -} - -template -internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22) { - return internal::ValueArray22(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22); -} - -template -internal::ValueArray23 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23) { - return internal::ValueArray23(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23); -} - -template -internal::ValueArray24 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24) { - return internal::ValueArray24(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24); -} - -template -internal::ValueArray25 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { - return internal::ValueArray25(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25); -} - -template -internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) { - return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); -} - -template -internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) { - return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); -} - -template -internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) { - return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28); -} - -template -internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) { - return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29); -} - -template -internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { - return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30); -} - -template -internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { - return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, - v25, v26, v27, v28, v29, v30, v31); -} - -template -internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32) { - return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32); -} - -template -internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33) { - return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); -} - -template -internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34) { - return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); -} - -template -internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { - return internal::ValueArray35(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); -} - -template -internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { - return internal::ValueArray36(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36); -} - -template -internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37) { - return internal::ValueArray37(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37); -} - -template -internal::ValueArray38 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38) { - return internal::ValueArray38(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, - v33, v34, v35, v36, v37, v38); -} - -template -internal::ValueArray39 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38, T39 v39) { - return internal::ValueArray39(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, - v32, v33, v34, v35, v36, v37, v38, v39); -} - -template -internal::ValueArray40 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, - T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, - T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { - return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, - v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); -} - -template -internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { - return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, - v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); -} - -template -internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) { - return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, - v42); -} - -template -internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) { - return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, - v41, v42, v43); -} - -template -internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) { - return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, - v40, v41, v42, v43, v44); -} - -template -internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { - return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, - v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, - v39, v40, v41, v42, v43, v44, v45); -} - -template -internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { - return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46); -} - -template -internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { - return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); -} - -template -internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, - T48 v48) { - return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, - v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); -} - -template -internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, - T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, - T47 v47, T48 v48, T49 v49) { - return internal::ValueArray49(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, - v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); -} - -template -internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, - T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, - T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { - return internal::ValueArray50(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, - v48, v49, v50); -} - -// Bool() allows generating tests with parameters in a set of (false, true). -// -// Synopsis: -// Bool() -// - returns a generator producing sequences with elements {false, true}. -// -// It is useful when testing code that depends on Boolean flags. Combinations -// of multiple flags can be tested when several Bool()'s are combined using -// Combine() function. -// -// In the following example all tests in the test case FlagDependentTest -// will be instantiated twice with parameters false and true. -// -// class FlagDependentTest : public testing::TestWithParam { -// virtual void SetUp() { -// external_flag = GetParam(); -// } -// } -// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); -// -inline internal::ParamGenerator Bool() { - return Values(false, true); -} - -# if GTEST_HAS_COMBINE -// Combine() allows the user to combine two or more sequences to produce -// values of a Cartesian product of those sequences' elements. -// -// Synopsis: -// Combine(gen1, gen2, ..., genN) -// - returns a generator producing sequences with elements coming from -// the Cartesian product of elements from the sequences generated by -// gen1, gen2, ..., genN. The sequence elements will have a type of -// tuple where T1, T2, ..., TN are the types -// of elements from sequences produces by gen1, gen2, ..., genN. -// -// Combine can have up to 10 arguments. This number is currently limited -// by the maximum number of elements in the tuple implementation used by Google -// Test. -// -// Example: -// -// This will instantiate tests in test case AnimalTest each one with -// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), -// tuple("dog", BLACK), and tuple("dog", WHITE): -// -// enum Color { BLACK, GRAY, WHITE }; -// class AnimalTest -// : public testing::TestWithParam > {...}; -// -// TEST_P(AnimalTest, AnimalLooksNice) {...} -// -// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, -// Combine(Values("cat", "dog"), -// Values(BLACK, WHITE))); -// -// This will instantiate tests in FlagDependentTest with all variations of two -// Boolean flags: -// -// class FlagDependentTest -// : public testing::TestWithParam > { -// virtual void SetUp() { -// // Assigns external_flag_1 and external_flag_2 values from the tuple. -// tie(external_flag_1, external_flag_2) = GetParam(); -// } -// }; -// -// TEST_P(FlagDependentTest, TestFeature1) { -// // Test your code using external_flag_1 and external_flag_2 here. -// } -// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, -// Combine(Bool(), Bool())); -// -template -internal::CartesianProductHolder2 Combine( - const Generator1& g1, const Generator2& g2) { - return internal::CartesianProductHolder2( - g1, g2); -} - -template -internal::CartesianProductHolder3 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3) { - return internal::CartesianProductHolder3( - g1, g2, g3); -} - -template -internal::CartesianProductHolder4 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4) { - return internal::CartesianProductHolder4( - g1, g2, g3, g4); -} - -template -internal::CartesianProductHolder5 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5) { - return internal::CartesianProductHolder5( - g1, g2, g3, g4, g5); -} - -template -internal::CartesianProductHolder6 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6) { - return internal::CartesianProductHolder6( - g1, g2, g3, g4, g5, g6); -} - -template -internal::CartesianProductHolder7 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7) { - return internal::CartesianProductHolder7( - g1, g2, g3, g4, g5, g6, g7); -} - -template -internal::CartesianProductHolder8 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8) { - return internal::CartesianProductHolder8( - g1, g2, g3, g4, g5, g6, g7, g8); -} - -template -internal::CartesianProductHolder9 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9) { - return internal::CartesianProductHolder9( - g1, g2, g3, g4, g5, g6, g7, g8, g9); -} - -template -internal::CartesianProductHolder10 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9, - const Generator10& g10) { - return internal::CartesianProductHolder10( - g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); -} -# endif // GTEST_HAS_COMBINE - - - -# define TEST_P(test_case_name, test_name) \ - class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - : public test_case_name { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ - virtual void TestBody(); \ - private: \ - static int AddToRegistry() { \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, __FILE__, __LINE__)->AddTestPattern(\ - #test_case_name, \ - #test_name, \ - new ::testing::internal::TestMetaFactory< \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>()); \ - return 0; \ - } \ - static int gtest_registering_dummy_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ - }; \ - int GTEST_TEST_CLASS_NAME_(test_case_name, \ - test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() - -# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator) \ - ::testing::internal::ParamGenerator \ - gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - int gtest_##prefix##test_case_name##_dummy_ = \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, __FILE__, __LINE__)->AddTestCaseInstantiation(\ - #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - __FILE__, __LINE__) - -} // namespace testing - -#endif // GTEST_HAS_PARAM_TEST - -#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Google C++ Testing Framework definitions useful in production code. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ - -// When you need to test the private or protected members of a class, -// use the FRIEND_TEST macro to declare your tests as friends of the -// class. For example: -// -// class MyClass { -// private: -// void MyMethod(); -// FRIEND_TEST(MyClassTest, MyMethod); -// }; -// -// class MyClassTest : public testing::Test { -// // ... -// }; -// -// TEST_F(MyClassTest, MyMethod) { -// // Can call MyClass::MyMethod() here. -// } - -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test - -#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: mheule@google.com (Markus Heule) -// - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ - -#include -#include - -namespace testing { - -// A copyable object representing the result of a test part (i.e. an -// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). -// -// Don't inherit from TestPartResult as its destructor is not virtual. -class GTEST_API_ TestPartResult { - public: - // The possible outcomes of a test part (i.e. an assertion or an - // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). - enum Type { - kSuccess, // Succeeded. - kNonFatalFailure, // Failed but the test can continue. - kFatalFailure // Failed and the test should be terminated. - }; - - // C'tor. TestPartResult does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestPartResult object. - TestPartResult(Type a_type, - const char* a_file_name, - int a_line_number, - const char* a_message) - : type_(a_type), - file_name_(a_file_name), - line_number_(a_line_number), - summary_(ExtractSummary(a_message)), - message_(a_message) { - } - - // Gets the outcome of the test part. - Type type() const { return type_; } - - // Gets the name of the source file where the test part took place, or - // NULL if it's unknown. - const char* file_name() const { return file_name_.c_str(); } - - // Gets the line in the source file where the test part took place, - // or -1 if it's unknown. - int line_number() const { return line_number_; } - - // Gets the summary of the failure message. - const char* summary() const { return summary_.c_str(); } - - // Gets the message associated with the test part. - const char* message() const { return message_.c_str(); } - - // Returns true iff the test part passed. - bool passed() const { return type_ == kSuccess; } - - // Returns true iff the test part failed. - bool failed() const { return type_ != kSuccess; } - - // Returns true iff the test part non-fatally failed. - bool nonfatally_failed() const { return type_ == kNonFatalFailure; } - - // Returns true iff the test part fatally failed. - bool fatally_failed() const { return type_ == kFatalFailure; } - private: - Type type_; - - // Gets the summary of the failure message by omitting the stack - // trace in it. - static internal::String ExtractSummary(const char* message); - - // The name of the source file where the test part took place, or - // NULL if the source file is unknown. - internal::String file_name_; - // The line in the source file where the test part took place, or -1 - // if the line number is unknown. - int line_number_; - internal::String summary_; // The test failure summary. - internal::String message_; // The test failure message. -}; - -// Prints a TestPartResult object. -std::ostream& operator<<(std::ostream& os, const TestPartResult& result); - -// An array of TestPartResult objects. -// -// Don't inherit from TestPartResultArray as its destructor is not -// virtual. -class GTEST_API_ TestPartResultArray { - public: - TestPartResultArray() {} - - // Appends the given TestPartResult to the array. - void Append(const TestPartResult& result); - - // Returns the TestPartResult at the given index (0-based). - const TestPartResult& GetTestPartResult(int index) const; - - // Returns the number of TestPartResult objects in the array. - int size() const; - - private: - std::vector array_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); -}; - -// This interface knows how to report a test part result. -class TestPartResultReporterInterface { - public: - virtual ~TestPartResultReporterInterface() {} - - virtual void ReportTestPartResult(const TestPartResult& result) = 0; -}; - -namespace internal { - -// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a -// statement generates new fatal failures. To do so it registers itself as the -// current test part result reporter. Besides checking if fatal failures were -// reported, it only delegates the reporting to the former result reporter. -// The original result reporter is restored in the destructor. -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -class GTEST_API_ HasNewFatalFailureHelper - : public TestPartResultReporterInterface { - public: - HasNewFatalFailureHelper(); - virtual ~HasNewFatalFailureHelper(); - virtual void ReportTestPartResult(const TestPartResult& result); - bool has_new_fatal_failure() const { return has_new_fatal_failure_; } - private: - bool has_new_fatal_failure_; - TestPartResultReporterInterface* original_reporter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); -}; - -} // namespace internal - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. -// -// Author: wan@google.com (Zhanyong Wan) - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -// This header implements typed tests and type-parameterized tests. - -// Typed (aka type-driven) tests repeat the same test for types in a -// list. You must know which types you want to test with when writing -// typed tests. Here's how you do it: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - public: - ... - typedef std::list List; - static T shared_; - T value_; -}; - -// Next, associate a list of types with the test case, which will be -// repeated for each type in the list. The typedef is necessary for -// the macro to parse correctly. -typedef testing::Types MyTypes; -TYPED_TEST_CASE(FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// TYPED_TEST_CASE(FooTest, int); - -// Then, use TYPED_TEST() instead of TEST_F() to define as many typed -// tests for this test case as you want. -TYPED_TEST(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - // Since we are inside a derived class template, C++ requires use to - // visit the members of FooTest via 'this'. - TypeParam n = this->value_; - - // To visit static members of the fixture, add the TestFixture:: - // prefix. - n += TestFixture::shared_; - - // To refer to typedefs in the fixture, add the "typename - // TestFixture::" prefix. - typename TestFixture::List values; - values.push_back(n); - ... -} - -TYPED_TEST(FooTest, HasPropertyA) { ... } - -#endif // 0 - -// Type-parameterized tests are abstract test patterns parameterized -// by a type. Compared with typed tests, type-parameterized tests -// allow you to define the test pattern without knowing what the type -// parameters are. The defined pattern can be instantiated with -// different types any number of times, in any number of translation -// units. -// -// If you are designing an interface or concept, you can define a -// suite of type-parameterized tests to verify properties that any -// valid implementation of the interface/concept should have. Then, -// each implementation can easily instantiate the test suite to verify -// that it conforms to the requirements, without having to write -// similar tests repeatedly. Here's an example: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - ... -}; - -// Next, declare that you will define a type-parameterized test case -// (the _P suffix is for "parameterized" or "pattern", whichever you -// prefer): -TYPED_TEST_CASE_P(FooTest); - -// Then, use TYPED_TEST_P() to define as many type-parameterized tests -// for this type-parameterized test case as you want. -TYPED_TEST_P(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - TypeParam n = 0; - ... -} - -TYPED_TEST_P(FooTest, HasPropertyA) { ... } - -// Now the tricky part: you need to register all test patterns before -// you can instantiate them. The first argument of the macro is the -// test case name; the rest are the names of the tests in this test -// case. -REGISTER_TYPED_TEST_CASE_P(FooTest, - DoesBlah, HasPropertyA); - -// Finally, you are free to instantiate the pattern with the types you -// want. If you put the above code in a header file, you can #include -// it in multiple C++ source files and instantiate it multiple times. -// -// To distinguish different instances of the pattern, the first -// argument to the INSTANTIATE_* macro is a prefix that will be added -// to the actual test case name. Remember to pick unique prefixes for -// different instances. -typedef testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); - -#endif // 0 - - -// Implements typed tests. - -#if GTEST_HAS_TYPED_TEST - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the typedef for the type parameters of the -// given test case. -# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ - -// The 'Types' template argument below must have spaces around it -// since some compilers may choke on '>>' when passing a template -// instance (e.g. Types) -# define TYPED_TEST_CASE(CaseName, Types) \ - typedef ::testing::internal::TypeList< Types >::type \ - GTEST_TYPE_PARAMS_(CaseName) - -# define TYPED_TEST(CaseName, TestName) \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel< \ - GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ - GTEST_TYPE_PARAMS_(CaseName)>::Register(\ - "", #CaseName, #TestName, 0); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() - -#endif // GTEST_HAS_TYPED_TEST - -// Implements type-parameterized tests. - -#if GTEST_HAS_TYPED_TEST_P - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the namespace name that the type-parameterized tests for -// the given type-parameterized test case are defined in. The exact -// name of the namespace is subject to change without notice. -# define GTEST_CASE_NAMESPACE_(TestCaseName) \ - gtest_case_##TestCaseName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the variable used to remember the names of -// the defined tests in the given test case. -# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ - gtest_typed_test_case_p_state_##TestCaseName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. -// -// Expands to the name of the variable used to remember the names of -// the registered tests in the given test case. -# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ - gtest_registered_test_names_##TestCaseName##_ - -// The variables defined in the type-parameterized test macros are -// static as typically these macros are used in a .h file that can be -// #included in multiple translation units linked together. -# define TYPED_TEST_CASE_P(CaseName) \ - static ::testing::internal::TypedTestCasePState \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) - -# define TYPED_TEST_P(CaseName, TestName) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - template \ - class TestName : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ - __FILE__, __LINE__, #CaseName, #TestName); \ - } \ - template \ - void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() - -# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ - __FILE__, __LINE__, #__VA_ARGS__) - -// The 'Types' template argument below must have spaces around it -// since some compilers may choke on '>>' when passing a template -// instance (e.g. Types) -# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ - bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestCase::type>::Register(\ - #Prefix, #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) - -#endif // GTEST_HAS_TYPED_TEST_P - -#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -// Depending on the platform, different string classes are available. -// On Linux, in addition to ::std::string, Google also makes use of -// class ::string, which has the same interface as ::std::string, but -// has a different implementation. -// -// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that -// ::string is available AND is a distinct type to ::std::string, or -// define it to 0 to indicate otherwise. -// -// If the user's ::std::string and ::string are the same class due to -// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0. -// -// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined -// heuristically. - -namespace testing { - -// Declares the flags. - -// This flag temporary enables the disabled tests. -GTEST_DECLARE_bool_(also_run_disabled_tests); - -// This flag brings the debugger on an assertion failure. -GTEST_DECLARE_bool_(break_on_failure); - -// This flag controls whether Google Test catches all test-thrown exceptions -// and logs them as failures. -GTEST_DECLARE_bool_(catch_exceptions); - -// This flag enables using colors in terminal output. Available values are -// "yes" to enable colors, "no" (disable colors), or "auto" (the default) -// to let Google Test decide. -GTEST_DECLARE_string_(color); - -// This flag sets up the filter to select by name using a glob pattern -// the tests to run. If the filter is not given all tests are executed. -GTEST_DECLARE_string_(filter); - -// This flag causes the Google Test to list tests. None of the tests listed -// are actually run if the flag is provided. -GTEST_DECLARE_bool_(list_tests); - -// This flag controls whether Google Test emits a detailed XML report to a file -// in addition to its normal textual output. -GTEST_DECLARE_string_(output); - -// This flags control whether Google Test prints the elapsed time for each -// test. -GTEST_DECLARE_bool_(print_time); - -// This flag specifies the random number seed. -GTEST_DECLARE_int32_(random_seed); - -// This flag sets how many times the tests are repeated. The default value -// is 1. If the value is -1 the tests are repeating forever. -GTEST_DECLARE_int32_(repeat); - -// This flag controls whether Google Test includes Google Test internal -// stack frames in failure stack traces. -GTEST_DECLARE_bool_(show_internal_stack_frames); - -// When this flag is specified, tests' order is randomized on every iteration. -GTEST_DECLARE_bool_(shuffle); - -// This flag specifies the maximum number of stack frames to be -// printed in a failure message. -GTEST_DECLARE_int32_(stack_trace_depth); - -// When this flag is specified, a failed assertion will throw an -// exception if exceptions are enabled, or exit the program with a -// non-zero code otherwise. -GTEST_DECLARE_bool_(throw_on_failure); - -// When this flag is set with a "host:port" string, on supported -// platforms test results are streamed to the specified port on -// the specified host machine. -GTEST_DECLARE_string_(stream_result_to); - -// The upper limit for valid stack trace depths. -const int kMaxStackTraceDepth = 100; - -namespace internal { - -class AssertHelper; -class DefaultGlobalTestPartResultReporter; -class ExecDeathTest; -class NoExecDeathTest; -class FinalSuccessChecker; -class GTestFlagSaver; -class TestResultAccessor; -class TestEventListenersAccessor; -class TestEventRepeater; -class WindowsDeathTest; -class UnitTestImpl* GetUnitTestImpl(); -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const String& message); - -// Converts a streamable value to a String. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -// Declared in gtest-internal.h but defined here, so that it has access -// to the definition of the Message class, required by the ARM -// compiler. -template -String StreamableToString(const T& streamable) { - return (Message() << streamable).GetString(); -} - -} // namespace internal - -// The friend relationship of some of these classes is cyclic. -// If we don't forward declare them the compiler might confuse the classes -// in friendship clauses with same named classes on the scope. -class Test; -class TestCase; -class TestInfo; -class UnitTest; - -// A class for indicating whether an assertion was successful. When -// the assertion wasn't successful, the AssertionResult object -// remembers a non-empty message that describes how it failed. -// -// To create an instance of this class, use one of the factory functions -// (AssertionSuccess() and AssertionFailure()). -// -// This class is useful for two purposes: -// 1. Defining predicate functions to be used with Boolean test assertions -// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts -// 2. Defining predicate-format functions to be -// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). -// -// For example, if you define IsEven predicate: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) -// will print the message -// -// Value of: IsEven(Fib(5)) -// Actual: false (5 is odd) -// Expected: true -// -// instead of a more opaque -// -// Value of: IsEven(Fib(5)) -// Actual: false -// Expected: true -// -// in case IsEven is a simple Boolean predicate. -// -// If you expect your predicate to be reused and want to support informative -// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up -// about half as often as positive ones in our tests), supply messages for -// both success and failure cases: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess() << n << " is even"; -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print -// -// Value of: IsEven(Fib(6)) -// Actual: true (8 is even) -// Expected: false -// -// NB: Predicates that support negative Boolean assertions have reduced -// performance in positive ones so be careful not to use them in tests -// that have lots (tens of thousands) of positive Boolean assertions. -// -// To use this class with EXPECT_PRED_FORMAT assertions such as: -// -// // Verifies that Foo() returns an even number. -// EXPECT_PRED_FORMAT1(IsEven, Foo()); -// -// you need to define: -// -// testing::AssertionResult IsEven(const char* expr, int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() -// << "Expected: " << expr << " is even\n Actual: it's " << n; -// } -// -// If Foo() returns 5, you will see the following message: -// -// Expected: Foo() is even -// Actual: it's 5 -// -class GTEST_API_ AssertionResult { - public: - // Copy constructor. - // Used in EXPECT_TRUE/FALSE(assertion_result). - AssertionResult(const AssertionResult& other); - // Used in the EXPECT_TRUE/FALSE(bool_expression). - explicit AssertionResult(bool success) : success_(success) {} - - // Returns true iff the assertion succeeded. - operator bool() const { return success_; } // NOLINT - - // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. - AssertionResult operator!() const; - - // Returns the text streamed into this AssertionResult. Test assertions - // use it when they fail (i.e., the predicate's outcome doesn't match the - // assertion's expectation). When nothing has been streamed into the - // object, returns an empty string. - const char* message() const { - return message_.get() != NULL ? message_->c_str() : ""; - } - // TODO(vladl@google.com): Remove this after making sure no clients use it. - // Deprecated; please use message() instead. - const char* failure_message() const { return message(); } - - // Streams a custom failure message into this object. - template AssertionResult& operator<<(const T& value) { - AppendMessage(Message() << value); - return *this; - } - - // Allows streaming basic output manipulators such as endl or flush into - // this object. - AssertionResult& operator<<( - ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { - AppendMessage(Message() << basic_manipulator); - return *this; - } - - private: - // Appends the contents of message to message_. - void AppendMessage(const Message& a_message) { - if (message_.get() == NULL) - message_.reset(new ::std::string); - message_->append(a_message.GetString().c_str()); - } - - // Stores result of the assertion predicate. - bool success_; - // Stores the message describing the condition in case the expectation - // construct is not satisfied with the predicate's outcome. - // Referenced via a pointer to avoid taking too much stack frame space - // with test assertions. - internal::scoped_ptr< ::std::string> message_; - - GTEST_DISALLOW_ASSIGN_(AssertionResult); -}; - -// Makes a successful assertion result. -GTEST_API_ AssertionResult AssertionSuccess(); - -// Makes a failed assertion result. -GTEST_API_ AssertionResult AssertionFailure(); - -// Makes a failed assertion result with the given failure message. -// Deprecated; use AssertionFailure() << msg. -GTEST_API_ AssertionResult AssertionFailure(const Message& msg); - -// The abstract class that all tests inherit from. -// -// In Google Test, a unit test program contains one or many TestCases, and -// each TestCase contains one or many Tests. -// -// When you define a test using the TEST macro, you don't need to -// explicitly derive from Test - the TEST macro automatically does -// this for you. -// -// The only time you derive from Test is when defining a test fixture -// to be used a TEST_F. For example: -// -// class FooTest : public testing::Test { -// protected: -// virtual void SetUp() { ... } -// virtual void TearDown() { ... } -// ... -// }; -// -// TEST_F(FooTest, Bar) { ... } -// TEST_F(FooTest, Baz) { ... } -// -// Test is not copyable. -class GTEST_API_ Test { - public: - friend class TestInfo; - - // Defines types for pointers to functions that set up and tear down - // a test case. - typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; - typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; - - // The d'tor is virtual as we intend to inherit from Test. - virtual ~Test(); - - // Sets up the stuff shared by all tests in this test case. - // - // Google Test will call Foo::SetUpTestCase() before running the first - // test in test case Foo. Hence a sub-class can define its own - // SetUpTestCase() method to shadow the one defined in the super - // class. - static void SetUpTestCase() {} - - // Tears down the stuff shared by all tests in this test case. - // - // Google Test will call Foo::TearDownTestCase() after running the last - // test in test case Foo. Hence a sub-class can define its own - // TearDownTestCase() method to shadow the one defined in the super - // class. - static void TearDownTestCase() {} - - // Returns true iff the current test has a fatal failure. - static bool HasFatalFailure(); - - // Returns true iff the current test has a non-fatal failure. - static bool HasNonfatalFailure(); - - // Returns true iff the current test has a (either fatal or - // non-fatal) failure. - static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } - - // Logs a property for the current test. Only the last value for a given - // key is remembered. - // These are public static so they can be called from utility functions - // that are not members of the test fixture. - // The arguments are const char* instead strings, as Google Test is used - // on platforms where string doesn't compile. - // - // Note that a driving consideration for these RecordProperty methods - // was to produce xml output suited to the Greenspan charting utility, - // which at present will only chart values that fit in a 32-bit int. It - // is the user's responsibility to restrict their values to 32-bit ints - // if they intend them to be used with Greenspan. - static void RecordProperty(const char* key, const char* value); - static void RecordProperty(const char* key, int value); - - protected: - // Creates a Test object. - Test(); - - // Sets up the test fixture. - virtual void SetUp(); - - // Tears down the test fixture. - virtual void TearDown(); - - private: - // Returns true iff the current test has the same fixture class as - // the first test in the current test case. - static bool HasSameFixtureClass(); - - // Runs the test after the test fixture has been set up. - // - // A sub-class must implement this to define the test logic. - // - // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. - // Instead, use the TEST or TEST_F macro. - virtual void TestBody() = 0; - - // Sets up, executes, and tears down the test. - void Run(); - - // Deletes self. We deliberately pick an unusual name for this - // internal method to avoid clashing with names used in user TESTs. - void DeleteSelf_() { delete this; } - - // Uses a GTestFlagSaver to save and restore all Google Test flags. - const internal::GTestFlagSaver* const gtest_flag_saver_; - - // Often a user mis-spells SetUp() as Setup() and spends a long time - // wondering why it is never called by Google Test. The declaration of - // the following method is solely for catching such an error at - // compile time: - // - // - The return type is deliberately chosen to be not void, so it - // will be a conflict if a user declares void Setup() in his test - // fixture. - // - // - This method is private, so it will be another compiler error - // if a user calls it from his test fixture. - // - // DO NOT OVERRIDE THIS FUNCTION. - // - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } - - // We disallow copying Tests. - GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); -}; - -typedef internal::TimeInMillis TimeInMillis; - -// A copyable object representing a user specified test property which can be -// output as a key/value string pair. -// -// Don't inherit from TestProperty as its destructor is not virtual. -class TestProperty { - public: - // C'tor. TestProperty does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestProperty object. - TestProperty(const char* a_key, const char* a_value) : - key_(a_key), value_(a_value) { - } - - // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } - - // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } - - // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const char* new_value) { - value_ = new_value; - } - - private: - // The key supplied by the user. - internal::String key_; - // The value supplied by the user. - internal::String value_; -}; - -// The result of a single Test. This includes a list of -// TestPartResults, a list of TestProperties, a count of how many -// death tests there are in the Test, and how much time it took to run -// the Test. -// -// TestResult is not copyable. -class GTEST_API_ TestResult { - public: - // Creates an empty TestResult. - TestResult(); - - // D'tor. Do not inherit from TestResult. - ~TestResult(); - - // Gets the number of all test parts. This is the sum of the number - // of successful test parts and the number of failed test parts. - int total_part_count() const; - - // Returns the number of the test properties. - int test_property_count() const; - - // Returns true iff the test passed (i.e. no test part failed). - bool Passed() const { return !Failed(); } - - // Returns true iff the test failed. - bool Failed() const; - - // Returns true iff the test fatally failed. - bool HasFatalFailure() const; - - // Returns true iff the test has a non-fatal failure. - bool HasNonfatalFailure() const; - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns the i-th test part result among all the results. i can range - // from 0 to test_property_count() - 1. If i is not in that range, aborts - // the program. - const TestPartResult& GetTestPartResult(int i) const; - - // Returns the i-th test property. i can range from 0 to - // test_property_count() - 1. If i is not in that range, aborts the - // program. - const TestProperty& GetTestProperty(int i) const; - - private: - friend class TestInfo; - friend class UnitTest; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::ExecDeathTest; - friend class internal::TestResultAccessor; - friend class internal::UnitTestImpl; - friend class internal::WindowsDeathTest; - - // Gets the vector of TestPartResults. - const std::vector& test_part_results() const { - return test_part_results_; - } - - // Gets the vector of TestProperties. - const std::vector& test_properties() const { - return test_properties_; - } - - // Sets the elapsed time. - void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } - - // Adds a test property to the list. The property is validated and may add - // a non-fatal failure if invalid (e.g., if it conflicts with reserved - // key names). If a property is already recorded for the same key, the - // value will be updated, rather than storing multiple values for the same - // key. - void RecordProperty(const TestProperty& test_property); - - // Adds a failure if the key is a reserved attribute of Google Test - // testcase tags. Returns true if the property is valid. - // TODO(russr): Validate attribute names are legal and human readable. - static bool ValidateTestProperty(const TestProperty& test_property); - - // Adds a test part result to the list. - void AddTestPartResult(const TestPartResult& test_part_result); - - // Returns the death test count. - int death_test_count() const { return death_test_count_; } - - // Increments the death test count, returning the new count. - int increment_death_test_count() { return ++death_test_count_; } - - // Clears the test part results. - void ClearTestPartResults(); - - // Clears the object. - void Clear(); - - // Protects mutable state of the property vector and of owned - // properties, whose values may be updated. - internal::Mutex test_properites_mutex_; - - // The vector of TestPartResults - std::vector test_part_results_; - // The vector of TestProperties - std::vector test_properties_; - // Running count of death tests. - int death_test_count_; - // The elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - - // We disallow copying TestResult. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); -}; // class TestResult - -// A TestInfo object stores the following information about a test: -// -// Test case name -// Test name -// Whether the test should be run -// A function pointer that creates the test object when invoked -// Test result -// -// The constructor of TestInfo registers itself with the UnitTest -// singleton such that the RUN_ALL_TESTS() macro knows which tests to -// run. -class GTEST_API_ TestInfo { - public: - // Destructs a TestInfo object. This function is not virtual, so - // don't inherit from TestInfo. - ~TestInfo(); - - // Returns the test case name. - const char* test_case_name() const { return test_case_name_.c_str(); } - - // Returns the test name. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a typed - // or a type-parameterized test. - const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); - return NULL; - } - - // Returns the text representation of the value parameter, or NULL if this - // is not a value-parameterized test. - const char* value_param() const { - if (value_param_.get() != NULL) - return value_param_->c_str(); - return NULL; - } - - // Returns true if this test should run, that is if the test is not disabled - // (or it is disabled but the also_run_disabled_tests flag has been specified) - // and its full name matches the user-specified filter. - // - // Google Test allows the user to filter the tests by their full names. - // The full name of a test Bar in test case Foo is defined as - // "Foo.Bar". Only the tests that match the filter will run. - // - // A filter is a colon-separated list of glob (not regex) patterns, - // optionally followed by a '-' and a colon-separated list of - // negative patterns (tests to exclude). A test is run if it - // matches one of the positive patterns and does not match any of - // the negative patterns. - // - // For example, *A*:Foo.* is a filter that matches any string that - // contains the character 'A' or starts with "Foo.". - bool should_run() const { return should_run_; } - - // Returns the result of the test. - const TestResult* result() const { return &result_; } - - private: - -#if GTEST_HAS_DEATH_TEST - friend class internal::DefaultDeathTestFactory; -#endif // GTEST_HAS_DEATH_TEST - friend class Test; - friend class TestCase; - friend class internal::UnitTestImpl; - friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_case_name, const char* name, - const char* type_param, - const char* value_param, - internal::TypeId fixture_class_id, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - internal::TestFactoryBase* factory); - - // Constructs a TestInfo object. The newly constructed instance assumes - // ownership of the factory object. - TestInfo(const char* test_case_name, const char* name, - const char* a_type_param, - const char* a_value_param, - internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory); - - // Increments the number of death tests encountered in this test so - // far. - int increment_death_test_count() { - return result_.increment_death_test_count(); - } - - // Creates the test object, runs it, records its result, and then - // deletes it. - void Run(); - - static void ClearTestResult(TestInfo* test_info) { - test_info->result_.Clear(); - } - - // These fields are immutable properties of the test. - const std::string test_case_name_; // Test case name - const std::string name_; // Test name - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const internal::scoped_ptr type_param_; - // Text representation of the value parameter, or NULL if this is not a - // value-parameterized test. - const internal::scoped_ptr value_param_; - const internal::TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True iff this test should run - bool is_disabled_; // True iff this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. - internal::TestFactoryBase* const factory_; // The factory that creates - // the test object - - // This field is mutable and needs to be reset before running the - // test for the second time. - TestResult result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); -}; - -// A test case, which consists of a vector of TestInfos. -// -// TestCase is not copyable. -class GTEST_API_ TestCase { - public: - // Creates a TestCase with the given name. - // - // TestCase does NOT have a default constructor. Always use this - // constructor to create a TestCase object. - // - // Arguments: - // - // name: name of the test case - // a_type_param: the name of the test's type parameter, or NULL if - // this is not a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - TestCase(const char* name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc); - - // Destructor of TestCase. - virtual ~TestCase(); - - // Gets the name of the TestCase. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a - // type-parameterized test case. - const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); - return NULL; - } - - // Returns true if any test in this test case should run. - bool should_run() const { return should_run_; } - - // Gets the number of successful tests in this test case. - int successful_test_count() const; - - // Gets the number of failed tests in this test case. - int failed_test_count() const; - - // Gets the number of disabled tests in this test case. - int disabled_test_count() const; - - // Get the number of tests in this test case that should run. - int test_to_run_count() const; - - // Gets the number of all tests in this test case. - int total_test_count() const; - - // Returns true iff the test case passed. - bool Passed() const { return !Failed(); } - - // Returns true iff the test case failed. - bool Failed() const { return failed_test_count() > 0; } - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - const TestInfo* GetTestInfo(int i) const; - - private: - friend class Test; - friend class internal::UnitTestImpl; - - // Gets the (mutable) vector of TestInfos in this TestCase. - std::vector& test_info_list() { return test_info_list_; } - - // Gets the (immutable) vector of TestInfos in this TestCase. - const std::vector& test_info_list() const { - return test_info_list_; - } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - TestInfo* GetMutableTestInfo(int i); - - // Sets the should_run member. - void set_should_run(bool should) { should_run_ = should; } - - // Adds a TestInfo to this test case. Will delete the TestInfo upon - // destruction of the TestCase object. - void AddTestInfo(TestInfo * test_info); - - // Clears the results of all tests in this test case. - void ClearResult(); - - // Clears the results of all tests in the given test case. - static void ClearTestCaseResult(TestCase* test_case) { - test_case->ClearResult(); - } - - // Runs every test in this TestCase. - void Run(); - - // Runs SetUpTestCase() for this TestCase. This wrapper is needed - // for catching exceptions thrown from SetUpTestCase(). - void RunSetUpTestCase() { (*set_up_tc_)(); } - - // Runs TearDownTestCase() for this TestCase. This wrapper is - // needed for catching exceptions thrown from TearDownTestCase(). - void RunTearDownTestCase() { (*tear_down_tc_)(); } - - // Returns true iff test passed. - static bool TestPassed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Passed(); - } - - // Returns true iff test failed. - static bool TestFailed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Failed(); - } - - // Returns true iff test is disabled. - static bool TestDisabled(const TestInfo* test_info) { - return test_info->is_disabled_; - } - - // Returns true if the given test should run. - static bool ShouldRunTest(const TestInfo* test_info) { - return test_info->should_run(); - } - - // Shuffles the tests in this test case. - void ShuffleTests(internal::Random* random); - - // Restores the test order to before the first shuffle. - void UnshuffleTests(); - - // Name of the test case. - internal::String name_; - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const internal::scoped_ptr type_param_; - // The vector of TestInfos in their original order. It owns the - // elements in the vector. - std::vector test_info_list_; - // Provides a level of indirection for the test list to allow easy - // shuffling and restoring the test order. The i-th element in this - // vector is the index of the i-th test in the shuffled test list. - std::vector test_indices_; - // Pointer to the function that sets up the test case. - Test::SetUpTestCaseFunc set_up_tc_; - // Pointer to the function that tears down the test case. - Test::TearDownTestCaseFunc tear_down_tc_; - // True iff any test in this test case should run. - bool should_run_; - // Elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - - // We disallow copying TestCases. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); -}; - -// An Environment object is capable of setting up and tearing down an -// environment. The user should subclass this to define his own -// environment(s). -// -// An Environment object does the set-up and tear-down in virtual -// methods SetUp() and TearDown() instead of the constructor and the -// destructor, as: -// -// 1. You cannot safely throw from a destructor. This is a problem -// as in some cases Google Test is used where exceptions are enabled, and -// we may want to implement ASSERT_* using exceptions where they are -// available. -// 2. You cannot use ASSERT_* directly in a constructor or -// destructor. -class Environment { - public: - // The d'tor is virtual as we need to subclass Environment. - virtual ~Environment() {} - - // Override this to define how to set up the environment. - virtual void SetUp() {} - - // Override this to define how to tear down the environment. - virtual void TearDown() {} - private: - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } -}; - -// The interface for tracing execution of tests. The methods are organized in -// the order the corresponding events are fired. -class TestEventListener { - public: - virtual ~TestEventListener() {} - - // Fired before any test activity starts. - virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; - - // Fired before each iteration of tests starts. There may be more than - // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration - // index, starting from 0. - virtual void OnTestIterationStart(const UnitTest& unit_test, - int iteration) = 0; - - // Fired before environment set-up for each iteration of tests starts. - virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; - - // Fired after environment set-up for each iteration of tests ends. - virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; - - // Fired before the test case starts. - virtual void OnTestCaseStart(const TestCase& test_case) = 0; - - // Fired before the test starts. - virtual void OnTestStart(const TestInfo& test_info) = 0; - - // Fired after a failed assertion or a SUCCEED() invocation. - virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; - - // Fired after the test ends. - virtual void OnTestEnd(const TestInfo& test_info) = 0; - - // Fired after the test case ends. - virtual void OnTestCaseEnd(const TestCase& test_case) = 0; - - // Fired before environment tear-down for each iteration of tests starts. - virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; - - // Fired after environment tear-down for each iteration of tests ends. - virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; - - // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; - - // Fired after all test activities have ended. - virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; -}; - -// The convenience class for users who need to override just one or two -// methods and are not concerned that a possible change to a signature of -// the methods they override will not be caught during the build. For -// comments about each method please see the definition of TestEventListener -// above. -class EmptyTestEventListener : public TestEventListener { - public: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int /*iteration*/) {} - virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} - virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} - virtual void OnTestStart(const TestInfo& /*test_info*/) {} - virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} - virtual void OnTestEnd(const TestInfo& /*test_info*/) {} - virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} - virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} - virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int /*iteration*/) {} - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} -}; - -// TestEventListeners lets users add listeners to track events in Google Test. -class GTEST_API_ TestEventListeners { - public: - TestEventListeners(); - ~TestEventListeners(); - - // Appends an event listener to the end of the list. Google Test assumes - // the ownership of the listener (i.e. it will delete the listener when - // the test program finishes). - void Append(TestEventListener* listener); - - // Removes the given event listener from the list and returns it. It then - // becomes the caller's responsibility to delete the listener. Returns - // NULL if the listener is not found in the list. - TestEventListener* Release(TestEventListener* listener); - - // Returns the standard listener responsible for the default console - // output. Can be removed from the listeners list to shut down default - // console output. Note that removing this object from the listener list - // with Release transfers its ownership to the caller and makes this - // function return NULL the next time. - TestEventListener* default_result_printer() const { - return default_result_printer_; - } - - // Returns the standard listener responsible for the default XML output - // controlled by the --gtest_output=xml flag. Can be removed from the - // listeners list by users who want to shut down the default XML output - // controlled by this flag and substitute it with custom one. Note that - // removing this object from the listener list with Release transfers its - // ownership to the caller and makes this function return NULL the next - // time. - TestEventListener* default_xml_generator() const { - return default_xml_generator_; - } - - private: - friend class TestCase; - friend class TestInfo; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::NoExecDeathTest; - friend class internal::TestEventListenersAccessor; - friend class internal::UnitTestImpl; - - // Returns repeater that broadcasts the TestEventListener events to all - // subscribers. - TestEventListener* repeater(); - - // Sets the default_result_printer attribute to the provided listener. - // The listener is also added to the listener list and previous - // default_result_printer is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultResultPrinter(TestEventListener* listener); - - // Sets the default_xml_generator attribute to the provided listener. The - // listener is also added to the listener list and previous - // default_xml_generator is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultXmlGenerator(TestEventListener* listener); - - // Controls whether events will be forwarded by the repeater to the - // listeners in the list. - bool EventForwardingEnabled() const; - void SuppressEventForwarding(); - - // The actual list of listeners. - internal::TestEventRepeater* repeater_; - // Listener responsible for the standard result output. - TestEventListener* default_result_printer_; - // Listener responsible for the creation of the XML output file. - TestEventListener* default_xml_generator_; - - // We disallow copying TestEventListeners. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); -}; - -// A UnitTest consists of a vector of TestCases. -// -// This is a singleton class. The only instance of UnitTest is -// created when UnitTest::GetInstance() is first called. This -// instance is never deleted. -// -// UnitTest is not copyable. -// -// This class is thread-safe as long as the methods are called -// according to their specification. -class GTEST_API_ UnitTest { - public: - // Gets the singleton UnitTest object. The first time this method - // is called, a UnitTest object is constructed and returned. - // Consecutive calls will return the same object. - static UnitTest* GetInstance(); - - // Runs all tests in this UnitTest object and prints the result. - // Returns 0 if successful, or 1 otherwise. - // - // This method can only be called from the main thread. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - int Run() GTEST_MUST_USE_RESULT_; - - // Returns the working directory when the first TEST() or TEST_F() - // was executed. The UnitTest object owns the string. - const char* original_working_dir() const; - - // Returns the TestCase object for the test that's currently running, - // or NULL if no test is running. - const TestCase* current_test_case() const; - - // Returns the TestInfo object for the test that's currently running, - // or NULL if no test is running. - const TestInfo* current_test_info() const; - - // Returns the random seed used at the start of the current test run. - int random_seed() const; - -#if GTEST_HAS_PARAM_TEST - // Returns the ParameterizedTestCaseRegistry object used to keep track of - // value-parameterized tests and instantiate and register them. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); -#endif // GTEST_HAS_PARAM_TEST - - // Gets the number of successful test cases. - int successful_test_case_count() const; - - // Gets the number of failed test cases. - int failed_test_case_count() const; - - // Gets the number of all test cases. - int total_test_case_count() const; - - // Gets the number of all test cases that contain at least one test - // that should run. - int test_case_to_run_count() const; - - // Gets the number of successful tests. - int successful_test_count() const; - - // Gets the number of failed tests. - int failed_test_count() const; - - // Gets the number of disabled tests. - int disabled_test_count() const; - - // Gets the number of all tests. - int total_test_count() const; - - // Gets the number of tests that should run. - int test_to_run_count() const; - - // Gets the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const; - - // Returns true iff the unit test passed (i.e. all test cases passed). - bool Passed() const; - - // Returns true iff the unit test failed (i.e. some test case failed - // or something outside of all tests failed). - bool Failed() const; - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - const TestCase* GetTestCase(int i) const; - - // Returns the list of event listeners that can be used to track events - // inside Google Test. - TestEventListeners& listeners(); - - private: - // Registers and returns a global test environment. When a test - // program is run, all global test environments will be set-up in - // the order they were registered. After all tests in the program - // have finished, all global test environments will be torn-down in - // the *reverse* order they were registered. - // - // The UnitTest object takes ownership of the given environment. - // - // This method can only be called from the main thread. - Environment* AddEnvironment(Environment* env); - - // Adds a TestPartResult to the current TestResult object. All - // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) - // eventually call this to report their results. The user code - // should use the assertion macros instead of calling this directly. - void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const internal::String& message, - const internal::String& os_stack_trace); - - // Adds a TestProperty to the current TestResult object. If the result already - // contains a property with the same key, the value will be updated. - void RecordPropertyForCurrentTest(const char* key, const char* value); - - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - TestCase* GetMutableTestCase(int i); - - // Accessors for the implementation object. - internal::UnitTestImpl* impl() { return impl_; } - const internal::UnitTestImpl* impl() const { return impl_; } - - // These classes and funcions are friends as they need to access private - // members of UnitTest. - friend class Test; - friend class internal::AssertHelper; - friend class internal::ScopedTrace; - friend Environment* AddGlobalTestEnvironment(Environment* env); - friend internal::UnitTestImpl* internal::GetUnitTestImpl(); - friend void internal::ReportFailureInUnknownLocation( - TestPartResult::Type result_type, - const internal::String& message); - - // Creates an empty UnitTest. - UnitTest(); - - // D'tor - virtual ~UnitTest(); - - // Pushes a trace defined by SCOPED_TRACE() on to the per-thread - // Google Test trace stack. - void PushGTestTrace(const internal::TraceInfo& trace); - - // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace(); - - // Protects mutable state in *impl_. This is mutable as some const - // methods need to lock it too. - mutable internal::Mutex mutex_; - - // Opaque implementation object. This field is never changed once - // the object is constructed. We don't mark it as const here, as - // doing so will cause a warning in the constructor of UnitTest. - // Mutable state in *impl_ is protected by mutex_. - internal::UnitTestImpl* impl_; - - // We disallow copying UnitTest. - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); -}; - -// A convenient wrapper for adding an environment for the test -// program. -// -// You should call this before RUN_ALL_TESTS() is called, probably in -// main(). If you use gtest_main, you need to call this before main() -// starts for it to take effect. For example, you can define a global -// variable like this: -// -// testing::Environment* const foo_env = -// testing::AddGlobalTestEnvironment(new FooEnvironment); -// -// However, we strongly recommend you to write your own main() and -// call AddGlobalTestEnvironment() there, as relying on initialization -// of global variables makes the code harder to read and may cause -// problems when you register multiple environments from different -// translation units and the environments have dependencies among them -// (remember that the compiler doesn't guarantee the order in which -// global variables from different translation units are initialized). -inline Environment* AddGlobalTestEnvironment(Environment* env) { - return UnitTest::GetInstance()->AddEnvironment(env); -} - -// Initializes Google Test. This must be called before calling -// RUN_ALL_TESTS(). In particular, it parses a command line for the -// flags that Google Test recognizes. Whenever a Google Test flag is -// seen, it is removed from argv, and *argc is decremented. -// -// No value is returned. Instead, the Google Test flag variables are -// updated. -// -// Calling the function for the second time has no user-visible effect. -GTEST_API_ void InitGoogleTest(int* argc, char** argv); - -// This overloaded version can be used in Windows programs compiled in -// UNICODE mode. -GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); - -namespace internal { - -// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) -// operand to be used in a failure message. The type (but not value) -// of the other operand may affect the format. This allows us to -// print a char* as a raw pointer when it is compared against another -// char*, and print it as a C string when it is compared against an -// std::string object, for example. -// -// The default implementation ignores the type of the other operand. -// Some specialized versions are used to handle formatting wide or -// narrow C strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -String FormatForComparisonFailureMessage(const T1& value, - const T2& /* other_operand */) { - // C++Builder compiles this incorrectly if the namespace isn't explicitly - // given. - return ::testing::PrintToString(value); -} - -// The helper function for {ASSERT|EXPECT}_EQ. -template -AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { -#ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4389) // Temporarily disables warning on - // signed/unsigned mismatch. -#endif - - if (expected == actual) { - return AssertionSuccess(); - } - -#ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif - - return EqFailure(expected_expression, - actual_expression, - FormatForComparisonFailureMessage(expected, actual), - FormatForComparisonFailureMessage(actual, expected), - false); -} - -// With this overloaded version, we allow anonymous enums to be used -// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums -// can be implicitly cast to BiggestInt. -GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual); - -// The helper class for {ASSERT|EXPECT}_EQ. The template argument -// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() -// is a null pointer literal. The following default implementation is -// for lhs_is_null_literal being false. -template -class EqHelper { - public: - // This templatized version is for the general case. - template - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } - - // With this overloaded version, we allow anonymous enums to be used - // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous - // enums can be implicitly cast to BiggestInt. - // - // Even though its body looks the same as the above version, we - // cannot merge the two, as it will make anonymous enums unhappy. - static AssertionResult Compare(const char* expected_expression, - const char* actual_expression, - BiggestInt expected, - BiggestInt actual) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } -}; - -// This specialization is used when the first argument to ASSERT_EQ() -// is a null pointer literal, like NULL, false, or 0. -template <> -class EqHelper { - public: - // We define two overloaded versions of Compare(). The first - // version will be picked when the second argument to ASSERT_EQ() is - // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or - // EXPECT_EQ(false, a_bool). - template - static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, - const T1& expected, - const T2& actual, - // The following line prevents this overload from being considered if T2 - // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) - // expands to Compare("", "", NULL, my_ptr), which requires a conversion - // to match the Secret* in the other overload, which would otherwise make - // this template match better. - typename EnableIf::value>::type* = 0) { - return CmpHelperEQ(expected_expression, actual_expression, expected, - actual); - } - - // This version will be picked when the second argument to ASSERT_EQ() is a - // pointer, e.g. ASSERT_EQ(NULL, a_pointer). - template - static AssertionResult Compare( - const char* expected_expression, - const char* actual_expression, - // We used to have a second template parameter instead of Secret*. That - // template parameter would deduce to 'long', making this a better match - // than the first overload even without the first overload's EnableIf. - // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to - // non-pointer argument" (even a deduced integral argument), so the old - // implementation caused warnings in user code. - Secret* /* expected (NULL) */, - T* actual) { - // We already know that 'expected' is a null pointer. - return CmpHelperEQ(expected_expression, actual_expression, - static_cast(NULL), actual); - } -}; - -// A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste -// of similar code. -// -// For each templatized helper function, we also define an overloaded -// version for BiggestInt in order to reduce code bloat and allow -// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled -// with gcc 4. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template \ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - }\ -}\ -GTEST_API_ AssertionResult CmpHelper##op_name(\ - const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) - -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - -// Implements the helper function for {ASSERT|EXPECT}_NE -GTEST_IMPL_CMP_HELPER_(NE, !=); -// Implements the helper function for {ASSERT|EXPECT}_LE -GTEST_IMPL_CMP_HELPER_(LE, <=); -// Implements the helper function for {ASSERT|EXPECT}_LT -GTEST_IMPL_CMP_HELPER_(LT, < ); -// Implements the helper function for {ASSERT|EXPECT}_GE -GTEST_IMPL_CMP_HELPER_(GE, >=); -// Implements the helper function for {ASSERT|EXPECT}_GT -GTEST_IMPL_CMP_HELPER_(GT, > ); - -#undef GTEST_IMPL_CMP_HELPER_ - -// The helper function for {ASSERT|EXPECT}_STREQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); - -// The helper function for {ASSERT|EXPECT}_STRCASEEQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, - const char* actual_expression, - const char* expected, - const char* actual); - -// The helper function for {ASSERT|EXPECT}_STRNE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - -// The helper function for {ASSERT|EXPECT}_STRCASENE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - - -// Helper function for *_STREQ on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, - const char* actual_expression, - const wchar_t* expected, - const wchar_t* actual); - -// Helper function for *_STRNE on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); - -} // namespace internal - -// IsSubstring() and IsNotSubstring() are intended to be used as the -// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by -// themselves. They check whether needle is a substring of haystack -// (NULL is considered a substring of itself only), and return an -// appropriate error message when they fail. -// -// The {needle,haystack}_expr arguments are the stringified -// expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -#endif // GTEST_HAS_STD_WSTRING - -namespace internal { - -// Helper template function for comparing floating-points. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, - const char* actual_expression, - RawType expected, - RawType actual) { - const FloatingPoint lhs(expected), rhs(actual); - - if (lhs.AlmostEquals(rhs)) { - return AssertionSuccess(); - } - - ::std::stringstream expected_ss; - expected_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << expected; - - ::std::stringstream actual_ss; - actual_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << actual; - - return EqFailure(expected_expression, - actual_expression, - StringStreamToString(&expected_ss), - StringStreamToString(&actual_ss), - false); -} - -// Helper function for implementing ASSERT_NEAR. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error); - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// A class that enables one to stream messages to assertion macros -class GTEST_API_ AssertHelper { - public: - // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message); - ~AssertHelper(); - - // Message assignment is a semantic trick to enable assertion - // streaming; see the GTEST_MESSAGE_ macro below. - void operator=(const Message& message) const; - - private: - // We put our data in a struct so that the size of the AssertHelper class can - // be as small as possible. This is important because gcc is incapable of - // re-using stack space even for temporary variables, so every EXPECT_EQ - // reserves stack space for another AssertHelper. - struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, - const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } - - TestPartResult::Type const type; - const char* const file; - int const line; - String const message; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); - }; - - AssertHelperData* const data_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); -}; - -} // namespace internal - -#if GTEST_HAS_PARAM_TEST -// The pure interface class that all value-parameterized tests inherit from. -// A value-parameterized class must inherit from both ::testing::Test and -// ::testing::WithParamInterface. In most cases that just means inheriting -// from ::testing::TestWithParam, but more complicated test hierarchies -// may need to inherit from Test and WithParamInterface at different levels. -// -// This interface has support for accessing the test parameter value via -// the GetParam() method. -// -// Use it with one of the parameter generator defining functions, like Range(), -// Values(), ValuesIn(), Bool(), and Combine(). -// -// class FooTest : public ::testing::TestWithParam { -// protected: -// FooTest() { -// // Can use GetParam() here. -// } -// virtual ~FooTest() { -// // Can use GetParam() here. -// } -// virtual void SetUp() { -// // Can use GetParam() here. -// } -// virtual void TearDown { -// // Can use GetParam() here. -// } -// }; -// TEST_P(FooTest, DoesBar) { -// // Can use GetParam() method here. -// Foo foo; -// ASSERT_TRUE(foo.DoesBar(GetParam())); -// } -// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); - -template -class WithParamInterface { - public: - typedef T ParamType; - virtual ~WithParamInterface() {} - - // The current parameter value. Is also available in the test fixture's - // constructor. This member function is non-static, even though it only - // references static data, to reduce the opportunity for incorrect uses - // like writing 'WithParamInterface::GetParam()' for a test that - // uses a fixture whose parameter type is int. - const ParamType& GetParam() const { return *parameter_; } - - private: - // Sets parameter value. The caller is responsible for making sure the value - // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } - - // Static value used for accessing parameter during a test lifetime. - static const ParamType* parameter_; - - // TestClass must be a subclass of WithParamInterface and Test. - template friend class internal::ParameterizedTestFactory; -}; - -template -const T* WithParamInterface::parameter_ = NULL; - -// Most value-parameterized classes can ignore the existence of -// WithParamInterface, and can just inherit from ::testing::TestWithParam. - -template -class TestWithParam : public Test, public WithParamInterface { -}; - -#endif // GTEST_HAS_PARAM_TEST - -// Macros for indicating success/failure in test code. - -// ADD_FAILURE unconditionally adds a failure to the current test. -// SUCCEED generates a success - it doesn't automatically make the -// current test successful, as a test is only successful when it has -// no failure. -// -// EXPECT_* verifies that a certain condition is satisfied. If not, -// it behaves like ADD_FAILURE. In particular: -// -// EXPECT_TRUE verifies that a Boolean condition is true. -// EXPECT_FALSE verifies that a Boolean condition is false. -// -// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except -// that they will also abort the current function on failure. People -// usually want the fail-fast behavior of FAIL and ASSERT_*, but those -// writing data-driven tests often find themselves using ADD_FAILURE -// and EXPECT_* more. -// -// Examples: -// -// EXPECT_TRUE(server.StatusIsOK()); -// ASSERT_FALSE(server.HasPendingRequest(port)) -// << "There are still pending requests " << "on port " << port; - -// Generates a nonfatal failure with a generic message. -#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") - -// Generates a nonfatal failure at the given source file location with -// a generic message. -#define ADD_FAILURE_AT(file, line) \ - GTEST_MESSAGE_AT_(file, line, "Failed", \ - ::testing::TestPartResult::kNonFatalFailure) - -// Generates a fatal failure with a generic message. -#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") - -// Define this macro to 1 to omit the definition of FAIL(), which is a -// generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() -#endif - -// Generates a success with a generic message. -#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") - -// Define this macro to 1 to omit the definition of SUCCEED(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() -#endif - -// Macros for testing exceptions. -// -// * {ASSERT|EXPECT}_THROW(statement, expected_exception): -// Tests that the statement throws the expected exception. -// * {ASSERT|EXPECT}_NO_THROW(statement): -// Tests that the statement doesn't throw any exception. -// * {ASSERT|EXPECT}_ANY_THROW(statement): -// Tests that the statement throws an exception. - -#define EXPECT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) -#define EXPECT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define EXPECT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define ASSERT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) -#define ASSERT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) -#define ASSERT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) - -// Boolean assertions. Condition can be either a Boolean expression or an -// AssertionResult. For more information on how to use AssertionResult with -// these macros see comments on that class. -#define EXPECT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_NONFATAL_FAILURE_) -#define EXPECT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_NONFATAL_FAILURE_) -#define ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define ASSERT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_FATAL_FAILURE_) - -// Includes the auto-generated header that implements a family of -// generic predicate assertion macros. -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. 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 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 COPYRIGHT -// OWNER 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. - -// This file is AUTOMATICALLY GENERATED on 09/24/2010 by command -// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! -// -// Implements a family of generic predicate assertion macros. - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -// Makes sure this header is not included before gtest.h. -#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. -#endif // GTEST_INCLUDE_GTEST_GTEST_H_ - -// This header implements a family of generic predicate assertion -// macros: -// -// ASSERT_PRED_FORMAT1(pred_format, v1) -// ASSERT_PRED_FORMAT2(pred_format, v1, v2) -// ... -// -// where pred_format is a function or functor that takes n (in the -// case of ASSERT_PRED_FORMATn) values and their source expression -// text, and returns a testing::AssertionResult. See the definition -// of ASSERT_EQ in gtest.h for an example. -// -// If you don't care about formatting, you can use the more -// restrictive version: -// -// ASSERT_PRED1(pred, v1) -// ASSERT_PRED2(pred, v1, v2) -// ... -// -// where pred is an n-ary function or functor that returns bool, -// and the values v1, v2, ..., must support the << operator for -// streaming to std::ostream. -// -// We also define the EXPECT_* variations. -// -// For now we only support predicates whose arity is at most 5. -// Please email googletestframework@googlegroups.com if you need -// support for higher arities. - -// GTEST_ASSERT_ is the basic statement to which all of the assertions -// in this file reduce. Don't use this in your code. - -#define GTEST_ASSERT_(expression, on_failure) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar = (expression)) \ - ; \ - else \ - on_failure(gtest_ar.failure_message()) - - -// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -template -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { - if (pred(v1)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. -// Don't use this in your code. -#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -#define GTEST_PRED1_(pred, v1, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ - #v1, \ - pred, \ - v1), on_failure) - -// Unary predicate assertion macros. -#define EXPECT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -template -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, - const T2& v2) { - if (pred(v1, v2)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. -// Don't use this in your code. -#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -#define GTEST_PRED2_(pred, v1, v2, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ - #v1, \ - #v2, \ - pred, \ - v1, \ - v2), on_failure) - -// Binary predicate assertion macros. -#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -template -AssertionResult AssertPred3Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3) { - if (pred(v1, v2, v3)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. -// Don't use this in your code. -#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - pred, \ - v1, \ - v2, \ - v3), on_failure) - -// Ternary predicate assertion macros. -#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -template -AssertionResult AssertPred4Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { - if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. -// Don't use this in your code. -#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4), on_failure) - -// 4-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -template -AssertionResult AssertPred5Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, - const T5& v5) { - if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ", " - << e5 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4 - << "\n" << e5 << " evaluates to " << v5; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. -// Don't use this in your code. -#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - #v5, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4, \ - v5), on_failure) - -// 5-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -// Macros for testing equalities and inequalities. -// -// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual -// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 -// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 -// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 -// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 -// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 -// -// When they are not, Google Test prints both the tested expressions and -// their actual values. The values must be compatible built-in types, -// or you will get a compiler error. By "compatible" we mean that the -// values can be compared by the respective operator. -// -// Note: -// -// 1. It is possible to make a user-defined type work with -// {ASSERT|EXPECT}_??(), but that requires overloading the -// comparison operators and is thus discouraged by the Google C++ -// Usage Guide. Therefore, you are advised to use the -// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are -// equal. -// -// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on -// pointers (in particular, C strings). Therefore, if you use it -// with two C strings, you are testing how their locations in memory -// are related, not how their content is related. To compare two C -// strings by content, use {ASSERT|EXPECT}_STR*(). -// -// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to -// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you -// what the actual value is when it fails, and similarly for the -// other comparisons. -// -// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() -// evaluate their arguments, which is undefined. -// -// 5. These macros evaluate their arguments exactly once. -// -// Examples: -// -// EXPECT_NE(5, Foo()); -// EXPECT_EQ(NULL, a_pointer); -// ASSERT_LT(i, array_size); -// ASSERT_GT(records.size(), 0) << "There is no record left."; - -#define EXPECT_EQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - expected, actual) -#define EXPECT_NE(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) -#define EXPECT_LE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define EXPECT_LT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define EXPECT_GE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define EXPECT_GT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -#define GTEST_ASSERT_EQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - expected, actual) -#define GTEST_ASSERT_NE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define GTEST_ASSERT_LE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define GTEST_ASSERT_LT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define GTEST_ASSERT_GE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define GTEST_ASSERT_GT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of -// ASSERT_XY(), which clashes with some users' own code. - -#if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) -#endif - -// C String Comparisons. All tests treat NULL and any non-NULL string -// as different. Two NULLs are equal. -// -// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 -// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 -// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case -// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case -// -// For wide or narrow string objects, you can use the -// {ASSERT|EXPECT}_??() macros. -// -// Don't depend on the order in which the arguments are evaluated, -// which is undefined. -// -// These macros evaluate their arguments exactly once. - -#define EXPECT_STREQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) -#define EXPECT_STRNE(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define EXPECT_STRCASEEQ(expected, actual) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) -#define EXPECT_STRCASENE(s1, s2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -#define ASSERT_STREQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) -#define ASSERT_STRNE(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define ASSERT_STRCASEEQ(expected, actual) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) -#define ASSERT_STRCASENE(s1, s2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -// Macros for comparing floating-point numbers. -// -// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): -// Tests that two float values are almost equal. -// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): -// Tests that two double values are almost equal. -// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): -// Tests that v1 and v2 are within the given distance to each other. -// -// Google Test uses ULP-based comparison to automatically pick a default -// error bound that is appropriate for the operands. See the -// FloatingPoint template class in gtest-internal.h if you are -// interested in the implementation details. - -#define EXPECT_FLOAT_EQ(expected, actual)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define EXPECT_DOUBLE_EQ(expected, actual)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define ASSERT_FLOAT_EQ(expected, actual)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define ASSERT_DOUBLE_EQ(expected, actual)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - expected, actual) - -#define EXPECT_NEAR(val1, val2, abs_error)\ - EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -#define ASSERT_NEAR(val1, val2, abs_error)\ - ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -// These predicate format functions work on floating-point values, and -// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. -// -// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2); -GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2); - - -#if GTEST_OS_WINDOWS - -// Macros that test for HRESULT failure and success, these are only useful -// on Windows, and rely on Windows SDK macros and APIs to compile. -// -// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) -// -// When expr unexpectedly fails or succeeds, Google Test prints the -// expected result and the actual result with both a human-readable -// string representation of the error, if available, as well as the -// hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -#endif // GTEST_OS_WINDOWS - -// Macros that execute statement and check that it doesn't generate new fatal -// failures in the current thread. -// -// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); -// -// Examples: -// -// EXPECT_NO_FATAL_FAILURE(Process()); -// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; -// -#define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) -#define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) - -// Causes a trace (including the source file path, the current line -// number, and the given message) to be included in every test failure -// message generated by code in the current scope. The effect is -// undone when the control leaves the current scope. -// -// The message argument can be anything streamable to std::ostream. -// -// In the implementation, we include the current line number as part -// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s -// to appear in the same block - as long as they are on different -// lines. -#define SCOPED_TRACE(message) \ - ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, ::testing::Message() << (message)) - -// Compile-time assertion for type equality. -// StaticAssertTypeEq() compiles iff type1 and type2 are -// the same type. The value it returns is not interesting. -// -// Instead of making StaticAssertTypeEq a class template, we make it a -// function template that invokes a helper class template. This -// prevents a user from misusing StaticAssertTypeEq by -// defining objects of that type. -// -// CAVEAT: -// -// When used inside a method of a class template, -// StaticAssertTypeEq() is effective ONLY IF the method is -// instantiated. For example, given: -// -// template class Foo { -// public: -// void Bar() { testing::StaticAssertTypeEq(); } -// }; -// -// the code: -// -// void Test1() { Foo foo; } -// -// will NOT generate a compiler error, as Foo::Bar() is never -// actually instantiated. Instead, you need: -// -// void Test2() { Foo foo; foo.Bar(); } -// -// to cause a compiler error. -template -bool StaticAssertTypeEq() { - (void)internal::StaticAssertTypeEqHelper(); - return true; -} - -// Defines a test. -// -// The first parameter is the name of the test case, and the second -// parameter is the name of the test within the test case. -// -// The convention is to end the test case name with "Test". For -// example, a test case for the Foo class can be named FooTest. -// -// The user should put his test code between braces after using this -// macro. Example: -// -// TEST(FooTest, InitializesCorrectly) { -// Foo foo; -// EXPECT_TRUE(foo.StatusIsOK()); -// } - -// Note that we call GetTestTypeId() instead of GetTypeId< -// ::testing::Test>() here to get the type ID of testing::Test. This -// is to work around a suspected linker bug when using Google Test as -// a framework on Mac OS X. The bug causes GetTypeId< -// ::testing::Test>() to return different values depending on whether -// the call is from the Google Test framework itself or from user test -// code. GetTestTypeId() is guaranteed to always return the same -// value, as it always calls GetTypeId<>() from the Google Test -// framework. -#define GTEST_TEST(test_case_name, test_name)\ - GTEST_TEST_(test_case_name, test_name, \ - ::testing::Test, ::testing::internal::GetTestTypeId()) - -// Define this macro to 1 to omit the definition of TEST(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_TEST -# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) -#endif - -// Defines a test that uses a test fixture. -// -// The first parameter is the name of the test fixture class, which -// also doubles as the test case name. The second parameter is the -// name of the test within the test case. -// -// A test fixture class must be declared earlier. The user should put -// his test code between braces after using this macro. Example: -// -// class FooTest : public testing::Test { -// protected: -// virtual void SetUp() { b_.AddElement(3); } -// -// Foo a_; -// Foo b_; -// }; -// -// TEST_F(FooTest, InitializesCorrectly) { -// EXPECT_TRUE(a_.StatusIsOK()); -// } -// -// TEST_F(FooTest, ReturnsElementCountCorrectly) { -// EXPECT_EQ(0, a_.size()); -// EXPECT_EQ(1, b_.size()); -// } - -#define TEST_F(test_fixture, test_name)\ - GTEST_TEST_(test_fixture, test_name, test_fixture, \ - ::testing::internal::GetTypeId()) - -// Use this macro in main() to run all tests. It returns 0 if all -// tests are successful, or 1 otherwise. -// -// RUN_ALL_TESTS() should be invoked after the command line has been -// parsed by InitGoogleTest(). - -#define RUN_ALL_TESTS()\ - (::testing::UnitTest::GetInstance()->Run()) - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_perf.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_perf.hpp deleted file mode 100755 index edbf352..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ts/ts_perf.hpp +++ /dev/null @@ -1,440 +0,0 @@ -#ifndef __OPENCV_TS_PERF_HPP__ -#define __OPENCV_TS_PERF_HPP__ - -#include "opencv2/core/core.hpp" -#include "ts_gtest.h" - -#if defined(ANDROID) && defined(USE_ANDROID_LOGGING) -#include - -#define PERF_TESTS_LOG_TAG "OpenCV_perf" -#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, PERF_TESTS_LOG_TAG, __VA_ARGS__)) -#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, PERF_TESTS_LOG_TAG, __VA_ARGS__)) -#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, PERF_TESTS_LOG_TAG, __VA_ARGS__)) -#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, PERF_TESTS_LOG_TAG, __VA_ARGS__)) -#else -#define LOGD(_str, ...) do{printf(_str , ## __VA_ARGS__); printf("\n");fflush(stdout);} while(0) -#define LOGI(_str, ...) do{printf(_str , ## __VA_ARGS__); printf("\n");fflush(stdout);} while(0) -#define LOGW(_str, ...) do{printf(_str , ## __VA_ARGS__); printf("\n");fflush(stdout);} while(0) -#define LOGE(_str, ...) do{printf(_str , ## __VA_ARGS__); printf("\n");fflush(stdout);} while(0) -#endif - - -namespace perf -{ - -/*****************************************************************************************\ -* Predefined typical frame sizes and typical test parameters * -\*****************************************************************************************/ -const cv::Size szQVGA = cv::Size(320, 240); -const cv::Size szVGA = cv::Size(640, 480); -const cv::Size szSVGA = cv::Size(800, 600); -const cv::Size szXGA = cv::Size(1024, 768); -const cv::Size szSXGA = cv::Size(1280, 1024); - -const cv::Size sznHD = cv::Size(640, 360); -const cv::Size szqHD = cv::Size(960, 540); -const cv::Size sz720p = cv::Size(1280, 720); -const cv::Size sz1080p = cv::Size(1920, 1080); - -const cv::Size sz2K = cv::Size(2048, 2048); - -const cv::Size szODD = cv::Size(127, 61); - -const cv::Size szSmall24 = cv::Size(24, 24); -const cv::Size szSmall32 = cv::Size(32, 32); -const cv::Size szSmall64 = cv::Size(64, 64); -const cv::Size szSmall128 = cv::Size(128, 128); - -#define SZ_ALL_VGA ::testing::Values(::perf::szQVGA, ::perf::szVGA, ::perf::szSVGA) -#define SZ_ALL_GA ::testing::Values(::perf::szQVGA, ::perf::szVGA, ::perf::szSVGA, ::perf::szXGA, ::perf::szSXGA) -#define SZ_ALL_HD ::testing::Values(::perf::sznHD, ::perf::szqHD, ::perf::sz720p, ::perf::sz1080p) -#define SZ_ALL_SMALL ::testing::Values(::perf::szSmall24, ::perf::szSmall32, ::perf::szSmall64, ::perf::szSmall128) -#define SZ_ALL ::testing::Values(::perf::szQVGA, ::perf::szVGA, ::perf::szSVGA, ::perf::szXGA, ::perf::szSXGA, ::perf::sznHD, ::perf::szqHD, ::perf::sz720p, ::perf::sz1080p) -#define SZ_TYPICAL ::testing::Values(::perf::szVGA, ::perf::szqHD, ::perf::sz720p, ::perf::szODD) - - -#define TYPICAL_MAT_SIZES ::perf::szVGA, ::perf::sz720p, ::perf::sz1080p, ::perf::szODD -#define TYPICAL_MAT_TYPES CV_8UC1, CV_8UC4, CV_32FC1 -#define TYPICAL_MATS testing::Combine( testing::Values( TYPICAL_MAT_SIZES ), testing::Values( TYPICAL_MAT_TYPES ) ) -#define TYPICAL_MATS_C1 testing::Combine( testing::Values( TYPICAL_MAT_SIZES ), testing::Values( CV_8UC1, CV_32FC1 ) ) -#define TYPICAL_MATS_C4 testing::Combine( testing::Values( TYPICAL_MAT_SIZES ), testing::Values( CV_8UC4 ) ) - - -/*****************************************************************************************\ -* MatType - printable wrapper over integer 'type' of Mat * -\*****************************************************************************************/ -class MatType -{ -public: - MatType(int val=0) : _type(val) {} - operator int() const {return _type;} - -private: - int _type; -}; - -/*****************************************************************************************\ -* CV_ENUM and CV_FLAGS - macro to create printable wrappers for defines and enums * -\*****************************************************************************************/ - -#define CV_ENUM(class_name, ...) \ -class CV_EXPORTS class_name {\ -public:\ - class_name(int val = 0) : _val(val) {}\ - operator int() const {return _val;}\ - void PrintTo(std::ostream* os) const {\ - const int vals[] = {__VA_ARGS__};\ - const char* svals = #__VA_ARGS__;\ - for(int i = 0, pos = 0; i < (int)(sizeof(vals)/sizeof(int)); ++i){\ - while(isspace(svals[pos]) || svals[pos] == ',') ++pos;\ - int start = pos;\ - while(!(isspace(svals[pos]) || svals[pos] == ',' || svals[pos] == 0)) ++pos;\ - if (_val == vals[i]) {\ - *os << std::string(svals + start, svals + pos);\ - return;\ - }\ - }\ - *os << "UNKNOWN";\ - }\ -private: int _val;\ -};\ -inline void PrintTo(const class_name& t, std::ostream* os) { t.PrintTo(os); } - -#define CV_FLAGS(class_name, ...) \ -class CV_EXPORTS class_name {\ -public:\ - class_name(int val = 0) : _val(val) {}\ - operator int() const {return _val;}\ - void PrintTo(std::ostream* os) const {\ - const int vals[] = {__VA_ARGS__};\ - const char* svals = #__VA_ARGS__;\ - int value = _val;\ - bool first = true;\ - for(int i = 0, pos = 0; i < (int)(sizeof(vals)/sizeof(int)); ++i){\ - while(isspace(svals[pos]) || svals[pos] == ',') ++pos;\ - int start = pos;\ - while(!(isspace(svals[pos]) || svals[pos] == ',' || svals[pos] == 0)) ++pos;\ - if ((value & vals[i]) == vals[i]) {\ - value &= ~vals[i]; \ - if (first) first = false; else *os << "|"; \ - *os << std::string(svals + start, svals + pos);\ - if (!value) return;\ - }\ - }\ - if (first) *os << "UNKNOWN";\ - }\ -private: int _val;\ -};\ -inline void PrintTo(const class_name& t, std::ostream* os) { t.PrintTo(os); } - -CV_ENUM(MatDepth, CV_8U, CV_8S, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F, CV_USRTYPE1) - -/*****************************************************************************************\ -* Regression control utility for performance testing * -\*****************************************************************************************/ -class CV_EXPORTS Regression -{ -public: - static Regression& add(const std::string& name, cv::InputArray array, double eps = DBL_EPSILON); - static void Init(const std::string& testSuitName, const std::string& ext = ".xml"); - - Regression& operator() (const std::string& name, cv::InputArray array, double eps = DBL_EPSILON); - -private: - static Regression& instance(); - Regression(); - ~Regression(); - - Regression(const Regression&); - Regression& operator=(const Regression&); - - cv::RNG regRNG;//own random numbers generator to make collection and verification work identical - std::string storageInPath; - std::string storageOutPath; - cv::FileStorage storageIn; - cv::FileStorage storageOut; - cv::FileNode rootIn; - std::string currentTestNodeName; - cv::FileStorage& write(); - - static std::string getCurrentTestNodeName(); - static bool isVector(cv::InputArray a); - static double getElem(cv::Mat& m, int x, int y, int cn = 0); - - void init(const std::string& testSuitName, const std::string& ext); - void write(cv::InputArray array); - void write(cv::Mat m); - void verify(cv::FileNode node, cv::InputArray array, double eps); - void verify(cv::FileNode node, cv::Mat actual, double eps, std::string argname); -}; - -#define SANITY_CHECK(array, ...) ::perf::Regression::add(#array, array , ## __VA_ARGS__) - - -/*****************************************************************************************\ -* Container for performance metrics * -\*****************************************************************************************/ -typedef struct CV_EXPORTS performance_metrics -{ - size_t bytesIn; - size_t bytesOut; - unsigned int samples; - unsigned int outliers; - double gmean; - double gstddev;//stddev for log(time) - double mean; - double stddev; - double median; - double min; - double frequency; - int terminationReason; - - enum - { - TERM_ITERATIONS = 0, - TERM_TIME = 1, - TERM_INTERRUPT = 2, - TERM_EXCEPTION = 3, - TERM_UNKNOWN = -1 - }; - - performance_metrics(); -} performance_metrics; - - -/*****************************************************************************************\ -* Base fixture for performance tests * -\*****************************************************************************************/ -class CV_EXPORTS TestBase: public ::testing::Test -{ -public: - TestBase(); - - static void Init(int argc, const char* const argv[]); - static std::string getDataPath(const std::string& relativePath); - -protected: - virtual void PerfTestBody() = 0; - - virtual void SetUp(); - virtual void TearDown(); - - void startTimer(); - void stopTimer(); - bool next(); - - //_declareHelper declare; - - enum - { - WARMUP_READ, - WARMUP_WRITE, - WARMUP_RNG, - WARMUP_NONE - }; - - void reportMetrics(bool toJUnitXML = false); - static void warmup(cv::InputOutputArray a, int wtype = WARMUP_READ); - - performance_metrics& calcMetrics(); - void RunPerfTestBody(); -private: - typedef std::vector > SizeVector; - typedef std::vector TimeVector; - - SizeVector inputData; - SizeVector outputData; - unsigned int getTotalInputSize() const; - unsigned int getTotalOutputSize() const; - - TimeVector times; - int64 lastTime; - int64 totalTime; - int64 timeLimit; - static int64 timeLimitDefault; - - unsigned int nIters; - unsigned int currentIter; - - performance_metrics metrics; - void validateMetrics(); - - static int64 _timeadjustment; - static int64 _calibrate(); - - static void warmup_impl(cv::Mat m, int wtype); - static int getSizeInBytes(cv::InputArray a); - static cv::Size getSize(cv::InputArray a); - static void declareArray(SizeVector& sizes, cv::InputOutputArray a, int wtype = 0); - - class CV_EXPORTS _declareHelper - { - public: - _declareHelper& in(cv::InputOutputArray a1, int wtype = WARMUP_READ); - _declareHelper& in(cv::InputOutputArray a1, cv::InputOutputArray a2, int wtype = WARMUP_READ); - _declareHelper& in(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, int wtype = WARMUP_READ); - _declareHelper& in(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, cv::InputOutputArray a4, int wtype = WARMUP_READ); - - _declareHelper& out(cv::InputOutputArray a1, int wtype = WARMUP_WRITE); - _declareHelper& out(cv::InputOutputArray a1, cv::InputOutputArray a2, int wtype = WARMUP_WRITE); - _declareHelper& out(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, int wtype = WARMUP_WRITE); - _declareHelper& out(cv::InputOutputArray a1, cv::InputOutputArray a2, cv::InputOutputArray a3, cv::InputOutputArray a4, int wtype = WARMUP_WRITE); - - _declareHelper& iterations(int n); - _declareHelper& time(double timeLimitSecs); - private: - TestBase* test; - _declareHelper(TestBase* t); - _declareHelper(const _declareHelper&); - _declareHelper& operator=(const _declareHelper&); - friend class TestBase; - }; - friend class _declareHelper; - -public: - _declareHelper declare; -}; - -template class TestBaseWithParam: public TestBase, public ::testing::WithParamInterface {}; - -typedef std::tr1::tuple Size_MatType_t; -typedef TestBaseWithParam Size_MatType; - -/*****************************************************************************************\ -* Print functions for googletest * -\*****************************************************************************************/ -CV_EXPORTS void PrintTo(const MatType& t, std::ostream* os); - -} //namespace perf - -namespace cv -{ - -CV_EXPORTS void PrintTo(const Size& sz, ::std::ostream* os); - -} //namespace cv - - -/*****************************************************************************************\ -* Macro definitions for performance tests * -\*****************************************************************************************/ -#define PERF_PROXY_NAMESPACE_NAME_(test_case_name, test_name) \ - test_case_name##_##test_name##_perf_namespace_proxy - -// Defines a performance test. -// -// The first parameter is the name of the test case, and the second -// parameter is the name of the test within the test case. -// -// The user should put his test code between braces after using this -// macro. Example: -// -// PERF_TEST(FooTest, InitializesCorrectly) { -// Foo foo; -// EXPECT_TRUE(foo.StatusIsOK()); -// } -#define PERF_TEST(test_case_name, test_name)\ - namespace PERF_PROXY_NAMESPACE_NAME_(test_case_name, test_name) {\ - class TestBase {/*compile error for this class means that you are trying to use perf::TestBase as a fixture*/};\ - class test_case_name : public ::perf::TestBase {\ - public:\ - test_case_name() {}\ - protected:\ - virtual void PerfTestBody();\ - };\ - TEST_F(test_case_name, test_name){ RunPerfTestBody(); }\ - }\ - void PERF_PROXY_NAMESPACE_NAME_(test_case_name, test_name)::test_case_name::PerfTestBody() - -// Defines a performance test that uses a test fixture. -// -// The first parameter is the name of the test fixture class, which -// also doubles as the test case name. The second parameter is the -// name of the test within the test case. -// -// A test fixture class must be declared earlier. The user should put -// his test code between braces after using this macro. Example: -// -// class FooTest : public ::perf::TestBase { -// protected: -// virtual void SetUp() { TestBase::SetUp(); b_.AddElement(3); } -// -// Foo a_; -// Foo b_; -// }; -// -// PERF_TEST_F(FooTest, InitializesCorrectly) { -// EXPECT_TRUE(a_.StatusIsOK()); -// } -// -// PERF_TEST_F(FooTest, ReturnsElementCountCorrectly) { -// EXPECT_EQ(0, a_.size()); -// EXPECT_EQ(1, b_.size()); -// } -#define PERF_TEST_F(fixture, testname) \ - namespace PERF_PROXY_NAMESPACE_NAME_(fixture, testname) {\ - class TestBase {/*compile error for this class means that you are trying to use perf::TestBase as a fixture*/};\ - class fixture : public ::fixture {\ - public:\ - fixture() {}\ - protected:\ - virtual void PerfTestBody();\ - };\ - TEST_F(fixture, testname){ RunPerfTestBody(); }\ - }\ - void PERF_PROXY_NAMESPACE_NAME_(fixture, testname)::fixture::PerfTestBody() - -// Defines a parametrized performance test. -// -// The first parameter is the name of the test fixture class, which -// also doubles as the test case name. The second parameter is the -// name of the test within the test case. -// -// The user should put his test code between braces after using this -// macro. Example: -// -// typedef ::perf::TestBaseWithParam FooTest; -// -// PERF_TEST_P(FooTest, DoTestingRight, ::testing::Values(::perf::szVGA, ::perf::sz720p) { -// cv::Mat b(GetParam(), CV_8U, cv::Scalar(10)); -// cv::Mat a(GetParam(), CV_8U, cv::Scalar(20)); -// cv::Mat c(GetParam(), CV_8U, cv::Scalar(0)); -// -// declare.in(a, b).out(c).time(0.5); -// -// SIMPLE_TEST_CYCLE() cv::add(a, b, c); -// -// SANITY_CHECK(c); -// } -#define PERF_TEST_P(fixture, name, params) \ - class fixture##_##name : public ::fixture {\ - public:\ - fixture##_##name() {}\ - protected:\ - virtual void PerfTestBody();\ - };\ - TEST_P(fixture##_##name, name /*perf*/){ RunPerfTestBody(); }\ - INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\ - void fixture##_##name::PerfTestBody() - - -#define CV_PERF_TEST_MAIN(testsuitname) \ -int main(int argc, char **argv)\ -{\ - ::perf::Regression::Init(#testsuitname);\ - ::perf::TestBase::Init(argc, argv);\ - ::testing::InitGoogleTest(&argc, argv);\ - return RUN_ALL_TESTS();\ -} - -#define TEST_CYCLE(n) for(declare.iterations(n); startTimer(), next(); stopTimer()) -#define SIMPLE_TEST_CYCLE() for(; startTimer(), next(); stopTimer()) - -//flags -namespace perf -{ -//GTEST_DECLARE_int32_(allowed_outliers); -} //namespace perf - -#endif //__OPENCV_TS_PERF_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/video/background_segm.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/video/background_segm.hpp deleted file mode 100755 index 83a571a..0000000 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/video/background_segm.hpp +++ /dev/null @@ -1,481 +0,0 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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 __OPENCV_BACKGROUND_SEGM_HPP__ -#define __OPENCV_BACKGROUND_SEGM_HPP__ - -#include "opencv2/core/core.hpp" - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************************\ -* Background/foreground segmentation * -\****************************************************************************************/ - -/* We discriminate between foreground and background pixels - * by building and maintaining a model of the background. - * Any pixel which does not fit this model is then deemed - * to be foreground. - * - * At present we support two core background models, - * one of which has two variations: - * - * o CV_BG_MODEL_FGD: latest and greatest algorithm, described in - * - * Foreground Object Detection from Videos Containing Complex Background. - * Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian. - * ACM MM2003 9p - * - * o CV_BG_MODEL_FGD_SIMPLE: - * A code comment describes this as a simplified version of the above, - * but the code is in fact currently identical - * - * o CV_BG_MODEL_MOG: "Mixture of Gaussians", older algorithm, described in - * - * Moving target classification and tracking from real-time video. - * A Lipton, H Fujijoshi, R Patil - * Proceedings IEEE Workshop on Application of Computer Vision pp 8-14 1998 - * - * Learning patterns of activity using real-time tracking - * C Stauffer and W Grimson August 2000 - * IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8):747-757 - */ - - -#define CV_BG_MODEL_FGD 0 -#define CV_BG_MODEL_MOG 1 /* "Mixture of Gaussians". */ -#define CV_BG_MODEL_FGD_SIMPLE 2 - -struct CvBGStatModel; - -typedef void (CV_CDECL * CvReleaseBGStatModel)( struct CvBGStatModel** bg_model ); -typedef int (CV_CDECL * CvUpdateBGStatModel)( IplImage* curr_frame, struct CvBGStatModel* bg_model, - double learningRate ); - -#define CV_BG_STAT_MODEL_FIELDS() \ - int type; /*type of BG model*/ \ - CvReleaseBGStatModel release; \ - CvUpdateBGStatModel update; \ - IplImage* background; /*8UC3 reference background image*/ \ - IplImage* foreground; /*8UC1 foreground image*/ \ - IplImage** layers; /*8UC3 reference background image, can be null */ \ - int layer_count; /* can be zero */ \ - CvMemStorage* storage; /*storage for foreground_regions*/ \ - CvSeq* foreground_regions /*foreground object contours*/ - -typedef struct CvBGStatModel -{ - CV_BG_STAT_MODEL_FIELDS(); -} CvBGStatModel; - -// - -// Releases memory used by BGStatModel -CVAPI(void) cvReleaseBGStatModel( CvBGStatModel** bg_model ); - -// Updates statistical model and returns number of found foreground regions -CVAPI(int) cvUpdateBGStatModel( IplImage* current_frame, CvBGStatModel* bg_model, - double learningRate CV_DEFAULT(-1)); - -// Performs FG post-processing using segmentation -// (all pixels of a region will be classified as foreground if majority of pixels of the region are FG). -// parameters: -// segments - pointer to result of segmentation (for example MeanShiftSegmentation) -// bg_model - pointer to CvBGStatModel structure -CVAPI(void) cvRefineForegroundMaskBySegm( CvSeq* segments, CvBGStatModel* bg_model ); - -/* Common use change detection function */ -CVAPI(int) cvChangeDetection( IplImage* prev_frame, - IplImage* curr_frame, - IplImage* change_mask ); - -/* - Interface of ACM MM2003 algorithm -*/ - -/* Default parameters of foreground detection algorithm: */ -#define CV_BGFG_FGD_LC 128 -#define CV_BGFG_FGD_N1C 15 -#define CV_BGFG_FGD_N2C 25 - -#define CV_BGFG_FGD_LCC 64 -#define CV_BGFG_FGD_N1CC 25 -#define CV_BGFG_FGD_N2CC 40 - -/* Background reference image update parameter: */ -#define CV_BGFG_FGD_ALPHA_1 0.1f - -/* stat model update parameter - * 0.002f ~ 1K frame(~45sec), 0.005 ~ 18sec (if 25fps and absolutely static BG) - */ -#define CV_BGFG_FGD_ALPHA_2 0.005f - -/* start value for alpha parameter (to fast initiate statistic model) */ -#define CV_BGFG_FGD_ALPHA_3 0.1f - -#define CV_BGFG_FGD_DELTA 2 - -#define CV_BGFG_FGD_T 0.9f - -#define CV_BGFG_FGD_MINAREA 15.f - -#define CV_BGFG_FGD_BG_UPDATE_TRESH 0.5f - -/* See the above-referenced Li/Huang/Gu/Tian paper - * for a full description of these background-model - * tuning parameters. - * - * Nomenclature: 'c' == "color", a three-component red/green/blue vector. - * We use histograms of these to model the range of - * colors we've seen at a given background pixel. - * - * 'cc' == "color co-occurrence", a six-component vector giving - * RGB color for both this frame and preceding frame. - * We use histograms of these to model the range of - * color CHANGES we've seen at a given background pixel. - */ -typedef struct CvFGDStatModelParams -{ - int Lc; /* Quantized levels per 'color' component. Power of two, typically 32, 64 or 128. */ - int N1c; /* Number of color vectors used to model normal background color variation at a given pixel. */ - int N2c; /* Number of color vectors retained at given pixel. Must be > N1c, typically ~ 5/3 of N1c. */ - /* Used to allow the first N1c vectors to adapt over time to changing background. */ - - int Lcc; /* Quantized levels per 'color co-occurrence' component. Power of two, typically 16, 32 or 64. */ - int N1cc; /* Number of color co-occurrence vectors used to model normal background color variation at a given pixel. */ - int N2cc; /* Number of color co-occurrence vectors retained at given pixel. Must be > N1cc, typically ~ 5/3 of N1cc. */ - /* Used to allow the first N1cc vectors to adapt over time to changing background. */ - - int is_obj_without_holes;/* If TRUE we ignore holes within foreground blobs. Defaults to TRUE. */ - int perform_morphing; /* Number of erode-dilate-erode foreground-blob cleanup iterations. */ - /* These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1. */ - - float alpha1; /* How quickly we forget old background pixel values seen. Typically set to 0.1 */ - float alpha2; /* "Controls speed of feature learning". Depends on T. Typical value circa 0.005. */ - float alpha3; /* Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1. */ - - float delta; /* Affects color and color co-occurrence quantization, typically set to 2. */ - float T; /* "A percentage value which determines when new features can be recognized as new background." (Typically 0.9).*/ - float minArea; /* Discard foreground blobs whose bounding box is smaller than this threshold. */ -} CvFGDStatModelParams; - -typedef struct CvBGPixelCStatTable -{ - float Pv, Pvb; - uchar v[3]; -} CvBGPixelCStatTable; - -typedef struct CvBGPixelCCStatTable -{ - float Pv, Pvb; - uchar v[6]; -} CvBGPixelCCStatTable; - -typedef struct CvBGPixelStat -{ - float Pbc; - float Pbcc; - CvBGPixelCStatTable* ctable; - CvBGPixelCCStatTable* cctable; - uchar is_trained_st_model; - uchar is_trained_dyn_model; -} CvBGPixelStat; - - -typedef struct CvFGDStatModel -{ - CV_BG_STAT_MODEL_FIELDS(); - CvBGPixelStat* pixel_stat; - IplImage* Ftd; - IplImage* Fbd; - IplImage* prev_frame; - CvFGDStatModelParams params; -} CvFGDStatModel; - -/* Creates FGD model */ -CVAPI(CvBGStatModel*) cvCreateFGDStatModel( IplImage* first_frame, - CvFGDStatModelParams* parameters CV_DEFAULT(NULL)); - -/* - Interface of Gaussian mixture algorithm - - "An improved adaptive background mixture model for real-time tracking with shadow detection" - P. KadewTraKuPong and R. Bowden, - Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001." - http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf -*/ - -/* Note: "MOG" == "Mixture Of Gaussians": */ - -#define CV_BGFG_MOG_MAX_NGAUSSIANS 500 - -/* default parameters of gaussian background detection algorithm */ -#define CV_BGFG_MOG_BACKGROUND_THRESHOLD 0.7 /* threshold sum of weights for background test */ -#define CV_BGFG_MOG_STD_THRESHOLD 2.5 /* lambda=2.5 is 99% */ -#define CV_BGFG_MOG_WINDOW_SIZE 200 /* Learning rate; alpha = 1/CV_GBG_WINDOW_SIZE */ -#define CV_BGFG_MOG_NGAUSSIANS 5 /* = K = number of Gaussians in mixture */ -#define CV_BGFG_MOG_WEIGHT_INIT 0.05 -#define CV_BGFG_MOG_SIGMA_INIT 30 -#define CV_BGFG_MOG_MINAREA 15.f - - -#define CV_BGFG_MOG_NCOLORS 3 - -typedef struct CvGaussBGStatModelParams -{ - int win_size; /* = 1/alpha */ - int n_gauss; - double bg_threshold, std_threshold, minArea; - double weight_init, variance_init; -}CvGaussBGStatModelParams; - -typedef struct CvGaussBGValues -{ - int match_sum; - double weight; - double variance[CV_BGFG_MOG_NCOLORS]; - double mean[CV_BGFG_MOG_NCOLORS]; -} CvGaussBGValues; - -typedef struct CvGaussBGPoint -{ - CvGaussBGValues* g_values; -} CvGaussBGPoint; - - -typedef struct CvGaussBGModel -{ - CV_BG_STAT_MODEL_FIELDS(); - CvGaussBGStatModelParams params; - CvGaussBGPoint* g_point; - int countFrames; -} CvGaussBGModel; - - -/* Creates Gaussian mixture background model */ -CVAPI(CvBGStatModel*) cvCreateGaussianBGModel( IplImage* first_frame, - CvGaussBGStatModelParams* parameters CV_DEFAULT(NULL)); - - -typedef struct CvBGCodeBookElem -{ - struct CvBGCodeBookElem* next; - int tLastUpdate; - int stale; - uchar boxMin[3]; - uchar boxMax[3]; - uchar learnMin[3]; - uchar learnMax[3]; -} CvBGCodeBookElem; - -typedef struct CvBGCodeBookModel -{ - CvSize size; - int t; - uchar cbBounds[3]; - uchar modMin[3]; - uchar modMax[3]; - CvBGCodeBookElem** cbmap; - CvMemStorage* storage; - CvBGCodeBookElem* freeList; -} CvBGCodeBookModel; - -CVAPI(CvBGCodeBookModel*) cvCreateBGCodeBookModel(); -CVAPI(void) cvReleaseBGCodeBookModel( CvBGCodeBookModel** model ); - -CVAPI(void) cvBGCodeBookUpdate( CvBGCodeBookModel* model, const CvArr* image, - CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), - const CvArr* mask CV_DEFAULT(0) ); - -CVAPI(int) cvBGCodeBookDiff( const CvBGCodeBookModel* model, const CvArr* image, - CvArr* fgmask, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)) ); - -CVAPI(void) cvBGCodeBookClearStale( CvBGCodeBookModel* model, int staleThresh, - CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), - const CvArr* mask CV_DEFAULT(0) ); - -CVAPI(CvSeq*) cvSegmentFGMask( CvArr *fgmask, int poly1Hull0 CV_DEFAULT(1), - float perimScale CV_DEFAULT(4.f), - CvMemStorage* storage CV_DEFAULT(0), - CvPoint offset CV_DEFAULT(cvPoint(0,0))); - -#ifdef __cplusplus -} - -namespace cv -{ - -/*! - The Base Class for Background/Foreground Segmentation - - The class is only used to define the common interface for - the whole family of background/foreground segmentation algorithms. -*/ -class CV_EXPORTS_W BackgroundSubtractor -{ -public: - //! the virtual destructor - virtual ~BackgroundSubtractor(); - //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image. - CV_WRAP_AS(apply) virtual void operator()(InputArray image, OutputArray fgmask, - double learningRate=0); - - //! computes a background image - virtual void getBackgroundImage(OutputArray backgroundImage) const; -}; - - -/*! - Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm - - The class implements the following algorithm: - "An improved adaptive background mixture model for real-time tracking with shadow detection" - P. KadewTraKuPong and R. Bowden, - Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001." - http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf - -*/ -class CV_EXPORTS_W BackgroundSubtractorMOG : public BackgroundSubtractor -{ -public: - //! the default constructor - CV_WRAP BackgroundSubtractorMOG(); - //! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength - CV_WRAP BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0); - //! the destructor - virtual ~BackgroundSubtractorMOG(); - //! the update operator - virtual void operator()(InputArray image, OutputArray fgmask, double learningRate=0); - - //! re-initiaization method - virtual void initialize(Size frameSize, int frameType); - - Size frameSize; - int frameType; - Mat bgmodel; - int nframes; - int history; - int nmixtures; - double varThreshold; - double backgroundRatio; - double noiseSigma; -}; - - -class CV_EXPORTS BackgroundSubtractorMOG2 : public BackgroundSubtractor -{ -public: - //! the default constructor - BackgroundSubtractorMOG2(); - //! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength - BackgroundSubtractorMOG2(int history, float varThreshold, bool bShadowDetection=1); - //! the destructor - virtual ~BackgroundSubtractorMOG2(); - //! the update operator - virtual void operator()(InputArray image, OutputArray fgmask, double learningRate=-1); - - //! computes a background image which are the mean of all background gaussians - virtual void getBackgroundImage(OutputArray backgroundImage) const; - - //! re-initiaization method - virtual void initialize(Size frameSize, int frameType); - - Size frameSize; - int frameType; - Mat bgmodel; - Mat bgmodelUsedModes;//keep track of number of modes per pixel - int nframes; - int history; - int nmixtures; - //! here it is the maximum allowed number of mixture comonents. - //! Actual number is determined dynamically per pixel - float varThreshold; - // threshold on the squared Mahalan. dist. to decide if it is well described - //by the background model or not. Related to Cthr from the paper. - //This does not influence the update of the background. A typical value could be 4 sigma - //and that is varThreshold=4*4=16; Corresponds to Tb in the paper. - - ///////////////////////// - //less important parameters - things you might change but be carefull - //////////////////////// - float backgroundRatio; - //corresponds to fTB=1-cf from the paper - //TB - threshold when the component becomes significant enough to be included into - //the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0. - //For alpha=0.001 it means that the mode should exist for approximately 105 frames before - //it is considered foreground - //float noiseSigma; - float varThresholdGen; - //correspondts to Tg - threshold on the squared Mahalan. dist. to decide - //when a sample is close to the existing components. If it is not close - //to any a new component will be generated. I use 3 sigma => Tg=3*3=9. - //Smaller Tg leads to more generated components and higher Tg might make - //lead to small number of components but they can grow too large - float fVarInit; - float fVarMin; - float fVarMax; - //initial variance for the newly generated components. - //It will will influence the speed of adaptation. A good guess should be made. - //A simple way is to estimate the typical standard deviation from the images. - //I used here 10 as a reasonable value - // min and max can be used to further control the variance - float fCT;//CT - complexity reduction prior - //this is related to the number of samples needed to accept that a component - //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get - //the standard Stauffer&Grimson algorithm (maybe not exact but very similar) - - //shadow detection parameters - bool bShadowDetection;//default 1 - do shadow detection - unsigned char nShadowDetection;//do shadow detection - insert this value as the detection result - 127 default value - float fTau; - // Tau - shadow threshold. The shadow is detected if the pixel is darker - //version of the background. Tau is a threshold on how much darker the shadow can be. - //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow - //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003. -}; - -} -#endif - -#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjasper.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjasper.a deleted file mode 100755 index 0ebda50..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjasper.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjpeg.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjpeg.a deleted file mode 100755 index 074c00a..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibjpeg.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibpng.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibpng.a deleted file mode 100755 index 10ef544..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibpng.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibtiff.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibtiff.a deleted file mode 100755 index aa39ec9..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/liblibtiff.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_calib3d.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_calib3d.a deleted file mode 100755 index 3786086..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_calib3d.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_contrib.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_contrib.a deleted file mode 100755 index ee67098..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_contrib.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_core.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_core.a deleted file mode 100755 index 83a4ba4..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_core.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_features2d.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_features2d.a deleted file mode 100755 index 1a44e34..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_features2d.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_flann.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_flann.a deleted file mode 100755 index a070d8c..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_flann.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_legacy.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_legacy.a deleted file mode 100755 index 35079d7..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_legacy.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_ml.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_ml.a deleted file mode 100755 index 8be8ca5..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_ml.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_objdetect.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_objdetect.a deleted file mode 100755 index 5544128..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_objdetect.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_video.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_video.a deleted file mode 100755 index afb08bd..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libopencv_video.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libzlib.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libzlib.a deleted file mode 100755 index 1b061bb..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/debug/libzlib.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjasper.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjasper.a deleted file mode 100755 index f5cdab7..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjasper.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjpeg.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjpeg.a deleted file mode 100755 index e950a2a..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibjpeg.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibpng.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibpng.a deleted file mode 100755 index 857d169..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibpng.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibtiff.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibtiff.a deleted file mode 100755 index 9302515..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/liblibtiff.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_calib3d.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_calib3d.a deleted file mode 100755 index 75e0d0d..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_calib3d.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_contrib.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_contrib.a deleted file mode 100755 index 5c74855..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_contrib.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_core.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_core.a deleted file mode 100755 index cf321da..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_core.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_features2d.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_features2d.a deleted file mode 100755 index 07172b3..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_features2d.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_flann.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_flann.a deleted file mode 100755 index c322844..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_flann.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_imgproc.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_imgproc.a deleted file mode 100755 index 2338083..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_imgproc.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_legacy.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_legacy.a deleted file mode 100755 index 76b18d1..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_legacy.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_ml.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_ml.a deleted file mode 100755 index 2166cba..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_ml.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_objdetect.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_objdetect.a deleted file mode 100755 index d283fb0..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_objdetect.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_video.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_video.a deleted file mode 100755 index b6912ea..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libopencv_video.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libzlib.a b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libzlib.a deleted file mode 100755 index de47bd7..0000000 Binary files a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/lib/release/libzlib.a and /dev/null differ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Headers b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Headers new file mode 120000 index 0000000..d5ab97c --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Headers @@ -0,0 +1 @@ +Versions/A/Headers \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Resources b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Resources new file mode 120000 index 0000000..186f014 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Resources @@ -0,0 +1 @@ +Versions/A/Resources \ No newline at end of file diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/calib3d/calib3d.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/calib3d/calib3d.hpp old mode 100755 new mode 100644 similarity index 94% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/calib3d/calib3d.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/calib3d/calib3d.hpp index fae3111..0d1cc46 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/calib3d/calib3d.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/calib3d/calib3d.hpp @@ -81,12 +81,19 @@ CVAPI(void) cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst ); #define CV_LMEDS 4 #define CV_RANSAC 8 - + #define CV_FM_LMEDS_ONLY CV_LMEDS #define CV_FM_RANSAC_ONLY CV_RANSAC #define CV_FM_LMEDS CV_LMEDS #define CV_FM_RANSAC CV_RANSAC - + +enum +{ + CV_ITERATIVE = 0, + CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" + CV_P3P = 2 // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" +}; + CVAPI(int) cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, CvMat* fundamental_matrix, int method CV_DEFAULT(CV_FM_RANSAC), @@ -110,7 +117,7 @@ CVAPI(void) cvTriangulatePoints(CvMat* projMatr1, CvMat* projMatr2, CVAPI(void) cvCorrectMatches(CvMat* F, CvMat* points1, CvMat* points2, CvMat* new_points1, CvMat* new_points2); - + /* Computes the optimal new camera matrix according to the free scaling parameter alpha: alpha=0 - only valid pixels will be retained in the undistorted image alpha=1 - all the source image pixels will be retained in the undistorted image @@ -196,20 +203,19 @@ CVAPI(void) cvInitIntrinsicParams2D( const CvMat* object_points, #define CV_CALIB_CB_FILTER_QUADS 4 #define CV_CALIB_CB_FAST_CHECK 8 -// Performs a fast check if a chessboard is in the input image. This is a workaround to +// Performs a fast check if a chessboard is in the input image. This is a workaround to // a problem of cvFindChessboardCorners being slow on images with no chessboard // - src: input image // - size: chessboard size -// Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, +// Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, // 0 if there is no chessboard, -1 in case of error CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size); - + /* Detects corners on a chessboard calibration pattern */ CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size, CvPoint2D32f* corners, int* corner_count CV_DEFAULT(NULL), - int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+ - CV_CALIB_CB_NORMALIZE_IMAGE) ); + int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) ); /* Draws individual chessboard corners or the whole chessboard detected */ CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size, @@ -239,7 +245,9 @@ CVAPI(double) cvCalibrateCamera2( const CvMat* object_points, CvMat* distortion_coeffs, CvMat* rotation_vectors CV_DEFAULT(NULL), CvMat* translation_vectors CV_DEFAULT(NULL), - int flags CV_DEFAULT(0) ); + int flags CV_DEFAULT(0), + CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria( + CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON)) ); /* Computes various useful characteristics of the camera from the data computed by cvCalibrateCamera2 */ @@ -321,7 +329,7 @@ typedef struct CvStereoBMState int speckleRange; // acceptable range of variation in window int trySmallerWindows; // if 1, the results may be more accurate, - // at the expense of slower processing + // at the expense of slower processing CvRect roi1, roi2; int disp12MaxDiff; @@ -344,44 +352,13 @@ CVAPI(void) cvReleaseStereoBMState( CvStereoBMState** state ); CVAPI(void) cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, CvArr* disparity, CvStereoBMState* state ); - + CVAPI(CvRect) cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity, int numberOfDisparities, int SADWindowSize ); - + CVAPI(void) cvValidateDisparity( CvArr* disparity, const CvArr* cost, int minDisparity, int numberOfDisparities, - int disp12MaxDiff CV_DEFAULT(1) ); - -/* Kolmogorov-Zabin stereo-correspondence algorithm (a.k.a. KZ1) */ -#define CV_STEREO_GC_OCCLUDED SHRT_MAX - -typedef struct CvStereoGCState -{ - int Ithreshold; - int interactionRadius; - float K, lambda, lambda1, lambda2; - int occlusionCost; - int minDisparity; - int numberOfDisparities; - int maxIters; - - CvMat* left; - CvMat* right; - CvMat* dispLeft; - CvMat* dispRight; - CvMat* ptrLeft; - CvMat* ptrRight; - CvMat* vtxBuf; - CvMat* edgeBuf; -} CvStereoGCState; - -CVAPI(CvStereoGCState*) cvCreateStereoGCState( int numberOfDisparities, int maxIters ); -CVAPI(void) cvReleaseStereoGCState( CvStereoGCState** state ); - -CVAPI(void) cvFindStereoCorrespondenceGC( const CvArr* left, const CvArr* right, - CvArr* disparityLeft, CvArr* disparityRight, - CvStereoGCState* state, - int useDisparityGuess CV_DEFAULT(0) ); + int disp12MaxDiff CV_DEFAULT(1) ); /* Reprojects the computed disparity image to the 3D space using the specified 4x4 matrix */ CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage, @@ -393,7 +370,6 @@ CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage, } ////////////////////////////////////////////////////////////////////////////////////////// - class CV_EXPORTS CvLevMarq { public: @@ -407,11 +383,11 @@ class CV_EXPORTS CvLevMarq bool completeSymmFlag=false ); bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - + void clear(); void step(); enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - + cv::Ptr mask; cv::Ptr prevParam; cv::Ptr param; @@ -432,7 +408,6 @@ class CV_EXPORTS CvLevMarq namespace cv { - //! converts rotation vector to rotation matrix or vice versa using Rodrigues transformation CV_EXPORTS_W void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian=noArray()); @@ -451,7 +426,7 @@ CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, //! variant of findHomography for backward compatibility CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, OutputArray mask, int method=0, double ransacReprojThreshold=3); - + //! Computes RQ decomposition of 3x3 matrix CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, OutputArray Qx=noArray(), @@ -464,7 +439,7 @@ CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray OutputArray rotMatrixX=noArray(), OutputArray rotMatrixY=noArray(), OutputArray rotMatrixZ=noArray(), - OutputArray eulerAngles=noArray() ); + OutputArray eulerAngles=noArray() ); //! computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, @@ -489,10 +464,16 @@ CV_EXPORTS_W void projectPoints( InputArray objectPoints, double aspectRatio=0 ); //! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled. -CV_EXPORTS_W void solvePnP( InputArray objectPoints, InputArray imagePoints, +enum +{ + ITERATIVE=CV_ITERATIVE, + EPNP=CV_EPNP, + P3P=CV_P3P +}; +CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess=false ); + bool useExtrinsicGuess=false, int flags=ITERATIVE); //! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints, @@ -505,7 +486,8 @@ CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, - OutputArray inliers = noArray() ); + OutputArray inliers = noArray(), + int flags = ITERATIVE); //! initializes camera matrix from a few 3D points and the corresponding projections. CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, @@ -518,10 +500,9 @@ enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2, //! finds checkerboard pattern of the specified size in the image CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, - int flags=CALIB_CB_ADAPTIVE_THRESH+ - CALIB_CB_NORMALIZE_IMAGE ); + int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE ); -//! finds subpixel-accurate positions of the chessboard corners +//! finds subpixel-accurate positions of the chessboard corners CV_EXPORTS bool find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size region_size); //! draws the checkerboard pattern (found or partly found) in the image @@ -532,13 +513,13 @@ enum { CALIB_CB_SYMMETRIC_GRID = 1, CALIB_CB_ASYMMETRIC_GRID = 2, CALIB_CB_CLUSTERING = 4 }; //! finds circles' grid pattern of the specified size in the image -CV_EXPORTS bool findCirclesGrid( InputArray image, Size patternSize, +CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, const Ptr &blobDetector = new SimpleBlobDetector()); +//! the deprecated function. Use findCirclesGrid() instead of it. CV_EXPORTS_W bool findCirclesGridDefault( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID ); - enum { CALIB_USE_INTRINSIC_GUESS = CV_CALIB_USE_INTRINSIC_GUESS, @@ -567,7 +548,8 @@ CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, CV_OUT InputOutputArray cameraMatrix, CV_OUT InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags=0 ); + int flags=0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) ); //! computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size. CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, @@ -590,11 +572,10 @@ CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, CV_OUT InputOutputArray distCoeffs2, Size imageSize, OutputArray R, OutputArray T, OutputArray E, OutputArray F, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+ - TermCriteria::EPS, 30, 1e-6), + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6), int flags=CALIB_FIX_INTRINSIC ); - + //! computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, @@ -622,7 +603,7 @@ CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distC OutputArray P1, OutputArray P2, OutputArray P3, OutputArray Q, double alpha, Size newImgSize, CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); - + //! returns the optimal new camera matrix CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, double alpha, Size newImgSize=Size(), @@ -630,16 +611,16 @@ CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray //! converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); - + //! converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); //! for backward compatibility CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); - + //! the algorithm for finding fundamental matrix enum -{ +{ FM_7POINT = CV_FM_7POINT, //!< 7-point algorithm FM_8POINT = CV_FM_8POINT, //!< 8-point algorithm FM_LMEDS = CV_FM_LMEDS, //!< least-median algorithm @@ -658,15 +639,22 @@ CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, double param1=3., double param2=0.99); //! finds coordinates of epipolar lines corresponding the specified points -CV_EXPORTS void computeCorrespondEpilines( InputArray points1, +CV_EXPORTS void computeCorrespondEpilines( InputArray points, int whichImage, InputArray F, OutputArray lines ); +CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, + InputArray projPoints1, InputArray projPoints2, + OutputArray points4D ); + +CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, + OutputArray newPoints1, OutputArray newPoints2 ); + template<> CV_EXPORTS void Ptr::delete_obj(); /*! Block Matching Stereo Correspondence Algorithm - + The class implements BM stereo correspondence algorithm by K. Konolige. */ class CV_EXPORTS_W StereoBM @@ -692,7 +680,7 @@ class CV_EXPORTS_W StereoBM /*! Semi-Global Block Matching Stereo Correspondence Algorithm - + The class implements the original SGBM stereo correspondence algorithm by H. Hirschmuller and some its modification. */ class CV_EXPORTS_W StereoSGBM @@ -702,7 +690,7 @@ class CV_EXPORTS_W StereoSGBM //! the default constructor CV_WRAP StereoSGBM(); - + //! the full constructor taking all the necessary algorithm parameters CV_WRAP StereoSGBM(int minDisparity, int numDisparities, int SADWindowSize, int P1=0, int P2=0, int disp12MaxDiff=0, @@ -751,11 +739,11 @@ CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues=false, int ddepth=-1 ); - -CV_EXPORTS_W int estimateAffine3D(InputArray _from, InputArray _to, - OutputArray _out, OutputArray _inliers, - double param1=3, double param2=0.99); - + +CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, + OutputArray out, OutputArray inliers, + double ransacThreshold=3, double confidence=0.99); + } #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/contrib.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/contrib.hpp old mode 100755 new mode 100644 similarity index 58% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/contrib.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/contrib.hpp index 7eb6a1e..1b13fd7 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/contrib.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/contrib.hpp @@ -44,6 +44,7 @@ #define __OPENCV_CONTRIB_HPP__ #include "opencv2/core/core.hpp" +#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/objdetect/objdetect.hpp" @@ -62,48 +63,48 @@ class CV_EXPORTS CvAdaptiveSkinDetector GSD_INTENSITY_LT = 15, GSD_INTENSITY_UT = 250 }; - + class CV_EXPORTS Histogram { private: enum { HistogramSize = (GSD_HUE_UT - GSD_HUE_LT + 1) }; - + protected: int findCoverageIndex(double surfaceToCover, int defaultValue = 0); - + public: CvHistogram *fHistogram; Histogram(); virtual ~Histogram(); - + void findCurveThresholds(int &x1, int &x2, double percent = 0.05); void mergeWith(Histogram *source, double weight); }; - + int nStartCounter, nFrameCount, nSkinHueLowerBound, nSkinHueUpperBound, nMorphingMethod, nSamplingDivider; double fHistogramMergeFactor, fHuePercentCovered; Histogram histogramHueMotion, skinHueHistogram; IplImage *imgHueFrame, *imgSaturationFrame, *imgLastGrayFrame, *imgMotionFrame, *imgFilteredFrame; IplImage *imgShrinked, *imgTemp, *imgGrayFrame, *imgHSVFrame; - + protected: void initData(IplImage *src, int widthDivider, int heightDivider); void adaptiveFilter(); - + public: - + enum { MORPHING_METHOD_NONE = 0, MORPHING_METHOD_ERODE = 1, MORPHING_METHOD_ERODE_ERODE = 2, MORPHING_METHOD_ERODE_DILATE = 3 }; - + CvAdaptiveSkinDetector(int samplingDivider = 1, int morphingMethod = MORPHING_METHOD_NONE); virtual ~CvAdaptiveSkinDetector(); - + virtual void process(IplImage *inputBGRImage, IplImage *outputHueMask); }; @@ -115,7 +116,7 @@ class CV_EXPORTS CvAdaptiveSkinDetector class CV_EXPORTS CvFuzzyPoint { public: double x, y, value; - + CvFuzzyPoint(double _x, double _y); }; @@ -123,13 +124,13 @@ class CV_EXPORTS CvFuzzyCurve { private: std::vector points; double value, centre; - + bool between(double x, double x1, double x2); - + public: CvFuzzyCurve(); ~CvFuzzyCurve(); - + void setCentre(double _centre); double getCentre(); void clear(); @@ -142,7 +143,7 @@ class CV_EXPORTS CvFuzzyCurve { class CV_EXPORTS CvFuzzyFunction { public: std::vector curves; - + CvFuzzyFunction(); ~CvFuzzyFunction(); void addCurve(CvFuzzyCurve *curve, double value = 0); @@ -185,7 +186,7 @@ class CV_EXPORTS CvFuzzyMeanShiftTracker FuzzyResizer(); int calcOutput(double edgeDensity, double density); }; - + class SearchWindow { public: @@ -199,7 +200,7 @@ class CV_EXPORTS CvFuzzyMeanShiftTracker double density; unsigned int depthLow, depthHigh; int verticalEdgeLeft, verticalEdgeRight, horizontalEdgeTop, horizontalEdgeBottom; - + SearchWindow(); ~SearchWindow(); void setSize(int _x, int _y, int _width, int _height); @@ -211,7 +212,7 @@ class CV_EXPORTS CvFuzzyMeanShiftTracker void getResizeAttribsEdgeDensityFuzzy(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh); bool meanShift(IplImage *maskImage, IplImage *depthMap, int maxIteration, bool initDepth); }; - + public: enum TrackingState { @@ -221,40 +222,40 @@ class CV_EXPORTS CvFuzzyMeanShiftTracker tsSetWindow = 3, tsDisabled = 10 }; - + enum ResizeMethod { rmEdgeDensityLinear = 0, rmEdgeDensityFuzzy = 1, rmInnerDensity = 2 }; - + enum { MinKernelMass = 1000 }; - + SearchWindow kernel; int searchMode; - + private: enum { MaxMeanShiftIteration = 5, MaxSetSizeIteration = 5 }; - + void findOptimumSearchWindow(SearchWindow &searchWindow, IplImage *maskImage, IplImage *depthMap, int maxIteration, int resizeMethod, bool initDepth); - + public: CvFuzzyMeanShiftTracker(); ~CvFuzzyMeanShiftTracker(); - + void track(IplImage *maskImage, IplImage *depthMap, int resizeMethod, bool resetSearch, int minKernelMass = MinKernelMass); }; namespace cv { - + class CV_EXPORTS Octree { public: @@ -267,11 +268,11 @@ namespace cv bool isLeaf; int children[8]; }; - + Octree(); Octree( const vector& points, int maxLevels = 10, int minPoints = 20 ); virtual ~Octree(); - + virtual void buildTree( const vector& points, int maxLevels = 10, int minPoints = 20 ); virtual void getPointsWithinSphere( const Point3f& center, float radius, vector& points ) const; @@ -280,85 +281,85 @@ namespace cv int minPoints; vector points; vector nodes; - + virtual void buildNext(size_t node_ind); }; - - + + class CV_EXPORTS Mesh3D { public: struct EmptyMeshException {}; - + Mesh3D(); Mesh3D(const vector& vtx); ~Mesh3D(); - + void buildOctree(); void clearOctree(); float estimateResolution(float tryRatio = 0.1f); void computeNormals(float normalRadius, int minNeighbors = 20); void computeNormals(const vector& subset, float normalRadius, int minNeighbors = 20); - + void writeAsVrml(const String& file, const vector& colors = vector()) const; - + vector vtx; vector normals; float resolution; Octree octree; - + const static Point3f allzero; }; - + class CV_EXPORTS SpinImageModel { public: - + /* model parameters, leave unset for default or auto estimate */ float normalRadius; int minNeighbors; - + float binSize; int imageWidth; - + float lambda; float gamma; - + float T_GeometriccConsistency; float T_GroupingCorespondances; - + /* public interface */ SpinImageModel(); explicit SpinImageModel(const Mesh3D& mesh); ~SpinImageModel(); - + void setLogger(std::ostream* log); void selectRandomSubset(float ratio); void setSubset(const vector& subset); void compute(); - + void match(const SpinImageModel& scene, vector< vector >& result); - + Mat packRandomScaledSpins(bool separateScale = false, size_t xCount = 10, size_t yCount = 10) const; - + size_t getSpinCount() const { return spinImages.rows; } Mat getSpinImage(size_t index) const { return spinImages.row((int)index); } const Point3f& getSpinVertex(size_t index) const { return mesh.vtx[subset[index]]; } const Point3f& getSpinNormal(size_t index) const { return mesh.normals[subset[index]]; } - + const Mesh3D& getMesh() const { return mesh; } Mesh3D& getMesh() { return mesh; } - + /* static utility functions */ static bool spinCorrelation(const Mat& spin1, const Mat& spin2, float lambda, float& result); - + static Point2f calcSpinMapCoo(const Point3f& point, const Point3f& vertex, const Point3f& normal); - + static float geometricConsistency(const Point3f& pointScene1, const Point3f& normalScene1, const Point3f& pointModel1, const Point3f& normalModel1, const Point3f& pointScene2, const Point3f& normalScene2, const Point3f& pointModel2, const Point3f& normalModel2); - + static float groupingCreteria(const Point3f& pointScene1, const Point3f& normalScene1, const Point3f& pointModel1, const Point3f& normalModel1, const Point3f& pointScene2, const Point3f& normalScene2, @@ -366,40 +367,40 @@ namespace cv float gamma); protected: void defaultParams(); - + void matchSpinToModel(const Mat& spin, vector& indeces, vector& corrCoeffs, bool useExtremeOutliers = true) const; - + void repackSpinImages(const vector& mask, Mat& spinImages, bool reAlloc = true) const; - + vector subset; Mesh3D mesh; Mat spinImages; std::ostream* out; }; - + class CV_EXPORTS TickMeter { public: TickMeter(); void start(); void stop(); - + int64 getTimeTicks() const; double getTimeMicro() const; double getTimeMilli() const; double getTimeSec() const; int64 getCounter() const; - + void reset(); private: int64 counter; int64 sumTime; int64 startTime; }; - + CV_EXPORTS std::ostream& operator<<(std::ostream& out, const TickMeter& tm); - + class CV_EXPORTS SelfSimDescriptor { public: @@ -411,29 +412,29 @@ namespace cv SelfSimDescriptor(const SelfSimDescriptor& ss); virtual ~SelfSimDescriptor(); SelfSimDescriptor& operator = (const SelfSimDescriptor& ss); - + size_t getDescriptorSize() const; Size getGridSize( Size imgsize, Size winStride ) const; - + virtual void compute(const Mat& img, vector& descriptors, Size winStride=Size(), const vector& locations=vector()) const; virtual void computeLogPolarMapping(Mat& mappingMask) const; virtual void SSD(const Mat& img, Point pt, Mat& ssd) const; - + int smallSize; int largeSize; int startDistanceBucket; int numberOfDistanceBuckets; int numberOfAngles; - + enum { DEFAULT_SMALL_SIZE = 5, DEFAULT_LARGE_SIZE = 41, DEFAULT_NUM_ANGLES = 20, DEFAULT_START_DISTANCE_BUCKET = 3, DEFAULT_NUM_DISTANCE_BUCKETS = 7 }; }; - - + + typedef bool (*BundleAdjustCallback)(int iteration, double norm_error, void* user_data); - + class LevMarqSparse { public: LevMarqSparse(); @@ -446,9 +447,9 @@ namespace cv Mat& visibility, // visibility matrix. rows correspond to points, columns correspond to cameras // 1 - point is visible for the camera, 0 - invisible Mat& P0, // starting vector of parameters, first cameras then points - Mat& X, // measurements, in order of visibility. non visible cases are skipped + Mat& X, // measurements, in order of visibility. non visible cases are skipped TermCriteria criteria, // termination criteria - + // callback for estimation of Jacobian matrices void (CV_CDECL * fjac)(int i, int j, Mat& point_params, Mat& cam_params, Mat& A, Mat& B, void* data), @@ -458,9 +459,9 @@ namespace cv void* data, // user-specific data passed to the callbacks BundleAdjustCallback cb, void* user_data ); - + virtual ~LevMarqSparse(); - + virtual void run( int npoints, // number of points int ncameras, // number of cameras int nPointParams, // number of params per one point (3 in case of 3D points) @@ -470,9 +471,9 @@ namespace cv Mat& visibility, // visibility matrix. rows correspond to points, columns correspond to cameras // 1 - point is visible for the camera, 0 - invisible Mat& P0, // starting vector of parameters, first cameras then points - Mat& X, // measurements, in order of visibility. non visible cases are skipped + Mat& X, // measurements, in order of visibility. non visible cases are skipped TermCriteria criteria, // termination criteria - + // callback for estimation of Jacobian matrices void (CV_CDECL * fjac)(int i, int j, Mat& point_params, Mat& cam_params, Mat& A, Mat& B, void* data), @@ -481,13 +482,13 @@ namespace cv Mat& cam_params, Mat& estim, void* data), void* data // user-specific data passed to the callbacks ); - + virtual void clear(); - + // useful function to do simple bundle adjustment tasks static void bundleAdjust(vector& points, // positions of points in global coordinate system (input and output) const vector >& imagePoints, // projections of 3d points for every camera - const vector >& visibility, // visibility of 3d points for every camera + const vector >& visibility, // visibility of 3d points for every camera vector& cameraMatrix, // intrinsic matrices of all cameras (input and output) vector& R, // rotation matrices of all cameras (input and output) vector& T, // translation vector of all cameras (input and output) @@ -495,123 +496,123 @@ namespace cv const TermCriteria& criteria= TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON), BundleAdjustCallback cb = 0, void* user_data = 0); - + public: virtual void optimize(CvMat &_vis); //main function that runs minimization - + //iteratively asks for measurement for visible camera-point pairs void ask_for_proj(CvMat &_vis,bool once=false); //iteratively asks for Jacobians for every camera_point pair void ask_for_projac(CvMat &_vis); - + CvMat* err; //error X-hX double prevErrNorm, errNorm; double lambda; CvTermCriteria criteria; int iters; - + CvMat** U; //size of array is equal to number of cameras CvMat** V; //size of array is equal to number of points CvMat** inv_V_star; //inverse of V* - + CvMat** A; CvMat** B; CvMat** W; - - CvMat* X; //measurement - CvMat* hX; //current measurement extimation given new parameter vector - - CvMat* prevP; //current already accepted parameter. + + CvMat* X; //measurement + CvMat* hX; //current measurement extimation given new parameter vector + + CvMat* prevP; //current already accepted parameter. CvMat* P; // parameters used to evaluate function with new params - // this parameters may be rejected - + // this parameters may be rejected + CvMat* deltaP; //computed increase of parameters (result of normal system solution ) - + CvMat** ea; // sum_i AijT * e_ij , used as right part of normal equation - // length of array is j = number of cameras + // length of array is j = number of cameras CvMat** eb; // sum_j BijT * e_ij , used as right part of normal equation // length of array is i = number of points - + CvMat** Yj; //length of array is i = num_points - - CvMat* S; //big matrix of block Sjk , each block has size num_cam_params x num_cam_params - + + CvMat* S; //big matrix of block Sjk , each block has size num_cam_params x num_cam_params + CvMat* JtJ_diag; //diagonal of JtJ, used to backup diagonal elements before augmentation - + CvMat* Vis_index; // matrix which element is index of measurement for point i and camera j - + int num_cams; int num_points; int num_err_param; int num_cam_param; int num_point_param; - - //target function and jacobian pointers, which needs to be initialized + + //target function and jacobian pointers, which needs to be initialized void (*fjac)(int i, int j, Mat& point_params, Mat& cam_params, Mat& A, Mat& B, void* data); void (*func)(int i, int j, Mat& point_params, Mat& cam_params, Mat& estim, void* data); - + void* data; - + BundleAdjustCallback cb; void* user_data; - }; - - CV_EXPORTS int chamerMatching( Mat& img, Mat& templ, - vector >& results, vector& cost, + }; + + CV_EXPORTS_W int chamerMatching( Mat& img, Mat& templ, + CV_OUT vector >& results, CV_OUT vector& cost, double templScale=1, int maxMatches = 20, double minMatchDistance = 1.0, int padX = 3, int padY = 3, int scales = 5, double minScale = 0.6, double maxScale = 1.6, double orientationWeight = 0.5, double truncate = 20); - - - class CV_EXPORTS StereoVar + + + class CV_EXPORTS_W StereoVar { public: - // Flags + // Flags enum {USE_INITIAL_DISPARITY = 1, USE_EQUALIZE_HIST = 2, USE_SMART_ID = 4, USE_AUTO_PARAMS = 8, USE_MEDIAN_FILTERING = 16}; enum {CYCLE_O, CYCLE_V}; enum {PENALIZATION_TICHONOV, PENALIZATION_CHARBONNIER, PENALIZATION_PERONA_MALIK}; - + //! the default constructor CV_WRAP StereoVar(); - + //! the full constructor taking all the necessary algorithm parameters CV_WRAP StereoVar(int levels, double pyrScale, int nIt, int minDisp, int maxDisp, int poly_n, double poly_sigma, float fi, float lambda, int penalization, int cycle, int flags); - + //! the destructor virtual ~StereoVar(); - + //! the stereo correspondence operator that computes disparity map for the specified rectified stereo pair CV_WRAP_AS(compute) virtual void operator()(const Mat& left, const Mat& right, Mat& disp); - - CV_PROP_RW int levels; - CV_PROP_RW double pyrScale; - CV_PROP_RW int nIt; - CV_PROP_RW int minDisp; - CV_PROP_RW int maxDisp; - CV_PROP_RW int poly_n; - CV_PROP_RW double poly_sigma; - CV_PROP_RW float fi; - CV_PROP_RW float lambda; - CV_PROP_RW int penalization; - CV_PROP_RW int cycle; - CV_PROP_RW int flags; - + + CV_PROP_RW int levels; + CV_PROP_RW double pyrScale; + CV_PROP_RW int nIt; + CV_PROP_RW int minDisp; + CV_PROP_RW int maxDisp; + CV_PROP_RW int poly_n; + CV_PROP_RW double poly_sigma; + CV_PROP_RW float fi; + CV_PROP_RW float lambda; + CV_PROP_RW int penalization; + CV_PROP_RW int cycle; + CV_PROP_RW int flags; + private: void autoParams(); - void FMG(Mat &I1, Mat &I2, Mat &I2x, Mat &u, int level); + void FMG(Mat &I1, Mat &I2, Mat &I2x, Mat &u, int level); void VCycle_MyFAS(Mat &I1_h, Mat &I2_h, Mat &I2x_h, Mat &u_h, int level); void VariationalSolver(Mat &I1_h, Mat &I2_h, Mat &I2x_h, Mat &u_h, int level); }; - + CV_EXPORTS void polyfit(const Mat& srcx, const Mat& srcy, Mat& dst, int order); - class CV_EXPORTS Directory + class CV_EXPORTS Directory { - public: - static std::vector GetListFiles ( const std::string& path, const std::string & exten = "*", bool addPath = true ); - static std::vector GetListFilesR ( const std::string& path, const std::string & exten = "*", bool addPath = true ); - static std::vector GetListFolders( const std::string& path, const std::string & exten = "*", bool addPath = true ); + public: + static std::vector GetListFiles ( const std::string& path, const std::string & exten = "*", bool addPath = true ); + static std::vector GetListFilesR ( const std::string& path, const std::string & exten = "*", bool addPath = true ); + static std::vector GetListFolders( const std::string& path, const std::string & exten = "*", bool addPath = true ); }; /* @@ -623,10 +624,362 @@ namespace cv * 4) convert the colors back to RGB */ CV_EXPORTS void generateColors( std::vector& colors, size_t count, size_t factor=100 ); + + + /* + * Estimate the rigid body motion from frame0 to frame1. The method is based on the paper + * "Real-Time Visual Odometry from Dense RGB-D Images", F. Steinbucker, J. Strum, D. Cremers, ICCV, 2011. + */ + enum { ROTATION = 1, + TRANSLATION = 2, + RIGID_BODY_MOTION = 4 + }; + CV_EXPORTS bool RGBDOdometry( Mat& Rt, const Mat& initRt, + const Mat& image0, const Mat& depth0, const Mat& mask0, + const Mat& image1, const Mat& depth1, const Mat& mask1, + const Mat& cameraMatrix, float minDepth=0.f, float maxDepth=4.f, float maxDepthDiff=0.07f, + const std::vector& iterCounts=std::vector(), + const std::vector& minGradientMagnitudes=std::vector(), + int transformType=RIGID_BODY_MOTION ); + + /** + *Bilinear interpolation technique. + * + *The value of a desired cortical pixel is obtained through a bilinear interpolation of the values + *of the four nearest neighbouring Cartesian pixels to the center of the RF. + *The same principle is applied to the inverse transformation. + * + *More details can be found in http://dx.doi.org/10.1007/978-3-642-23968-7_5 + */ + class CV_EXPORTS LogPolar_Interp + { + public: + + LogPolar_Interp() {} + + /** + *Constructor + *\param w the width of the input image + *\param h the height of the input image + *\param center the transformation center: where the output precision is maximal + *\param R the number of rings of the cortical image (default value 70 pixel) + *\param ro0 the radius of the blind spot (default value 3 pixel) + *\param full \a 1 (default value) means that the retinal image (the inverse transform) is computed within the circumscribing circle. + * \a 0 means that the retinal image is computed within the inscribed circle. + *\param S the number of sectors of the cortical image (default value 70 pixel). + * Its value is usually internally computed to obtain a pixel aspect ratio equals to 1. + *\param sp \a 1 (default value) means that the parameter \a S is internally computed. + * \a 0 means that the parameter \a S is provided by the user. + */ + LogPolar_Interp(int w, int h, Point2i center, int R=70, double ro0=3.0, + int interp=INTER_LINEAR, int full=1, int S=117, int sp=1); + /** + *Transformation from Cartesian image to cortical (log-polar) image. + *\param source the Cartesian image + *\return the transformed image (cortical image) + */ + const Mat to_cortical(const Mat &source); + /** + *Transformation from cortical image to retinal (inverse log-polar) image. + *\param source the cortical image + *\return the transformed image (retinal image) + */ + const Mat to_cartesian(const Mat &source); + /** + *Destructor + */ + ~LogPolar_Interp(); + + protected: + + Mat Rsri; + Mat Csri; + + int S, R, M, N; + int top, bottom,left,right; + double ro0, romax, a, q; + int interp; + + Mat ETAyx; + Mat CSIyx; + + void create_map(int M, int N, int R, int S, double ro0); + }; + + /** + *Overlapping circular receptive fields technique + * + *The Cartesian plane is divided in two regions: the fovea and the periphery. + *The fovea (oversampling) is handled by using the bilinear interpolation technique described above, whereas in + *the periphery we use the overlapping Gaussian circular RFs. + * + *More details can be found in http://dx.doi.org/10.1007/978-3-642-23968-7_5 + */ + class CV_EXPORTS LogPolar_Overlapping + { + public: + LogPolar_Overlapping() {} + + /** + *Constructor + *\param w the width of the input image + *\param h the height of the input image + *\param center the transformation center: where the output precision is maximal + *\param R the number of rings of the cortical image (default value 70 pixel) + *\param ro0 the radius of the blind spot (default value 3 pixel) + *\param full \a 1 (default value) means that the retinal image (the inverse transform) is computed within the circumscribing circle. + * \a 0 means that the retinal image is computed within the inscribed circle. + *\param S the number of sectors of the cortical image (default value 70 pixel). + * Its value is usually internally computed to obtain a pixel aspect ratio equals to 1. + *\param sp \a 1 (default value) means that the parameter \a S is internally computed. + * \a 0 means that the parameter \a S is provided by the user. + */ + LogPolar_Overlapping(int w, int h, Point2i center, int R=70, + double ro0=3.0, int full=1, int S=117, int sp=1); + /** + *Transformation from Cartesian image to cortical (log-polar) image. + *\param source the Cartesian image + *\return the transformed image (cortical image) + */ + const Mat to_cortical(const Mat &source); + /** + *Transformation from cortical image to retinal (inverse log-polar) image. + *\param source the cortical image + *\return the transformed image (retinal image) + */ + const Mat to_cartesian(const Mat &source); + /** + *Destructor + */ + ~LogPolar_Overlapping(); + + protected: + + Mat Rsri; + Mat Csri; + vector Rsr; + vector Csr; + vector Wsr; + + int S, R, M, N, ind1; + int top, bottom,left,right; + double ro0, romax, a, q; + + struct kernel + { + kernel() { w = 0; } + vector weights; + int w; + }; + + Mat ETAyx; + Mat CSIyx; + vector w_ker_2D; + + void create_map(int M, int N, int R, int S, double ro0); + }; + + /** + * Adjacent receptive fields technique + * + *All the Cartesian pixels, whose coordinates in the cortical domain share the same integer part, are assigned to the same RF. + *The precision of the boundaries of the RF can be improved by breaking each pixel into subpixels and assigning each of them to the correct RF. + *This technique is implemented from: Traver, V., Pla, F.: Log-polar mapping template design: From task-level requirements + *to geometry parameters. Image Vision Comput. 26(10) (2008) 1354-1370 + * + *More details can be found in http://dx.doi.org/10.1007/978-3-642-23968-7_5 + */ + class CV_EXPORTS LogPolar_Adjacent + { + public: + LogPolar_Adjacent() {} + + /** + *Constructor + *\param w the width of the input image + *\param h the height of the input image + *\param center the transformation center: where the output precision is maximal + *\param R the number of rings of the cortical image (default value 70 pixel) + *\param ro0 the radius of the blind spot (default value 3 pixel) + *\param smin the size of the subpixel (default value 0.25 pixel) + *\param full \a 1 (default value) means that the retinal image (the inverse transform) is computed within the circumscribing circle. + * \a 0 means that the retinal image is computed within the inscribed circle. + *\param S the number of sectors of the cortical image (default value 70 pixel). + * Its value is usually internally computed to obtain a pixel aspect ratio equals to 1. + *\param sp \a 1 (default value) means that the parameter \a S is internally computed. + * \a 0 means that the parameter \a S is provided by the user. + */ + LogPolar_Adjacent(int w, int h, Point2i center, int R=70, double ro0=3.0, double smin=0.25, int full=1, int S=117, int sp=1); + /** + *Transformation from Cartesian image to cortical (log-polar) image. + *\param source the Cartesian image + *\return the transformed image (cortical image) + */ + const Mat to_cortical(const Mat &source); + /** + *Transformation from cortical image to retinal (inverse log-polar) image. + *\param source the cortical image + *\return the transformed image (retinal image) + */ + const Mat to_cartesian(const Mat &source); + /** + *Destructor + */ + ~LogPolar_Adjacent(); + + protected: + struct pixel + { + pixel() { u = v = 0; a = 0.; } + int u; + int v; + double a; + }; + int S, R, M, N; + int top, bottom,left,right; + double ro0, romax, a, q; + vector > L; + vector A; + + void subdivide_recursively(double x, double y, int i, int j, double length, double smin); + bool get_uv(double x, double y, int&u, int&v); + void create_map(int M, int N, int R, int S, double ro0, double smin); + }; + + CV_EXPORTS Mat subspaceProject(InputArray W, InputArray mean, InputArray src); + CV_EXPORTS Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); + + class CV_EXPORTS LDA + { + public: + // Initializes a LDA with num_components (default 0) and specifies how + // samples are aligned (default dataAsRow=true). + LDA(int num_components = 0) : + _num_components(num_components) {}; + + // Initializes and performs a Discriminant Analysis with Fisher's + // Optimization Criterion on given data in src and corresponding labels + // in labels. If 0 (or less) number of components are given, they are + // automatically determined for given data in computation. + LDA(const Mat& src, vector labels, + int num_components = 0) : + _num_components(num_components) + { + this->compute(src, labels); //! compute eigenvectors and eigenvalues + } + + // Initializes and performs a Discriminant Analysis with Fisher's + // Optimization Criterion on given data in src and corresponding labels + // in labels. If 0 (or less) number of components are given, they are + // automatically determined for given data in computation. + LDA(InputArrayOfArrays src, InputArray labels, + int num_components = 0) : + _num_components(num_components) + { + this->compute(src, labels); //! compute eigenvectors and eigenvalues + } + + // Serializes this object to a given filename. + void save(const string& filename) const; + + // Deserializes this object from a given filename. + void load(const string& filename); + + // Serializes this object to a given cv::FileStorage. + void save(FileStorage& fs) const; + + // Deserializes this object from a given cv::FileStorage. + void load(const FileStorage& node); + + // Destructor. + ~LDA() {} + + //! Compute the discriminants for data in src and labels. + void compute(InputArrayOfArrays src, InputArray labels); + + // Projects samples into the LDA subspace. + Mat project(InputArray src); + + // Reconstructs projections from the LDA subspace. + Mat reconstruct(InputArray src); + + // Returns the eigenvectors of this LDA. + Mat eigenvectors() const { return _eigenvectors; }; + + // Returns the eigenvalues of this LDA. + Mat eigenvalues() const { return _eigenvalues; } + + protected: + bool _dataAsRow; + int _num_components; + Mat _eigenvectors; + Mat _eigenvalues; + + void lda(InputArrayOfArrays src, InputArray labels); + }; + + class CV_EXPORTS_W FaceRecognizer : public Algorithm + { + public: + //! virtual destructor + virtual ~FaceRecognizer() {} + + // Trains a FaceRecognizer. + CV_WRAP virtual void train(InputArrayOfArrays src, InputArray labels) = 0; + + // Updates a FaceRecognizer. + CV_WRAP void update(InputArrayOfArrays src, InputArray labels); + + // Gets a prediction from a FaceRecognizer. + virtual int predict(InputArray src) const = 0; + + // Predicts the label and confidence for a given sample. + CV_WRAP virtual void predict(InputArray src, CV_OUT int &label, CV_OUT double &confidence) const = 0; + + // Serializes this object to a given filename. + CV_WRAP virtual void save(const string& filename) const; + + // Deserializes this object from a given filename. + CV_WRAP virtual void load(const string& filename); + + // Serializes this object to a given cv::FileStorage. + virtual void save(FileStorage& fs) const = 0; + + // Deserializes this object from a given cv::FileStorage. + virtual void load(const FileStorage& fs) = 0; + + }; + + CV_EXPORTS_W Ptr createEigenFaceRecognizer(int num_components = 0, double threshold = DBL_MAX); + CV_EXPORTS_W Ptr createFisherFaceRecognizer(int num_components = 0, double threshold = DBL_MAX); + CV_EXPORTS_W Ptr createLBPHFaceRecognizer(int radius=1, int neighbors=8, + int grid_x=8, int grid_y=8, double threshold = DBL_MAX); + + enum + { + COLORMAP_AUTUMN = 0, + COLORMAP_BONE = 1, + COLORMAP_JET = 2, + COLORMAP_WINTER = 3, + COLORMAP_RAINBOW = 4, + COLORMAP_OCEAN = 5, + COLORMAP_SUMMER = 6, + COLORMAP_SPRING = 7, + COLORMAP_COOL = 8, + COLORMAP_HSV = 9, + COLORMAP_PINK = 10, + COLORMAP_HOT = 11 + }; + + CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); + + CV_EXPORTS bool initModule_contrib(); } #include "opencv2/contrib/retina.hpp" +#include "opencv2/contrib/openfabmap.hpp" + #endif #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/detection_based_tracker.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/detection_based_tracker.hpp new file mode 100644 index 0000000..56aa1cc --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/detection_based_tracker.hpp @@ -0,0 +1,106 @@ +#pragma once + +#if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(ANDROID) + +#include +#include + +#include + +class DetectionBasedTracker +{ + public: + struct Parameters + { + int minObjectSize; + int maxObjectSize; + double scaleFactor; + int maxTrackLifetime; + int minNeighbors; + int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 + + Parameters(); + }; + + DetectionBasedTracker(const std::string& cascadeFilename, const Parameters& params); + virtual ~DetectionBasedTracker(); + + virtual bool run(); + virtual void stop(); + virtual void resetTracking(); + + virtual void process(const cv::Mat& imageGray); + + bool setParameters(const Parameters& params); + const Parameters& getParameters(); + + + typedef std::pair Object; + virtual void getObjects(std::vector& result) const; + virtual void getObjects(std::vector& result) const; + + protected: + class SeparateDetectionWork; + cv::Ptr separateDetectionWork; + friend void* workcycleObjectDetectorFunction(void* p); + + + struct InnerParameters + { + int numLastPositionsToTrack; + int numStepsToWaitBeforeFirstShow; + int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; + int numStepsToShowWithoutDetecting; + + float coeffTrackingWindowSize; + float coeffObjectSizeToTrack; + float coeffObjectSpeedUsingInPrediction; + + InnerParameters(); + }; + Parameters parameters; + InnerParameters innerParameters; + + struct TrackedObject + { + typedef std::vector PositionsVector; + + PositionsVector lastPositions; + + int numDetectedFrames; + int numFramesNotDetected; + int id; + + TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) + { + lastPositions.push_back(rect); + id=getNextId(); + }; + + static int getNextId() + { + static int _id=0; + return _id++; + } + }; + + int numTrackedSteps; + std::vector trackedObjects; + + std::vector weightsPositionsSmoothing; + std::vector weightsSizesSmoothing; + + cv::CascadeClassifier cascadeForTracking; + + + void updateTrackedObjects(const std::vector& detectedObjects); + cv::Rect calcTrackedObjectPositionToShow(int i) const; + void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); +}; + +namespace cv +{ + using ::DetectionBasedTracker; +} //end of cv namespace + +#endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/hybridtracker.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/hybridtracker.hpp old mode 100755 new mode 100644 similarity index 53% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/hybridtracker.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/hybridtracker.hpp index 5bf7844..3a1f722 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/contrib/hybridtracker.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/hybridtracker.hpp @@ -59,155 +59,151 @@ namespace cv // To add Kalman filter struct CV_EXPORTS CvMotionModel { - enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2}; + enum {LOW_PASS_FILTER = 0, KALMAN_FILTER = 1, EM = 2}; - CvMotionModel() - { - } + CvMotionModel() + { + } - float low_pass_gain; // low pass gain - CvEMParams em_params; // EM parameters + float low_pass_gain; // low pass gain }; // Mean Shift Tracker parameters for specifying use of HSV channel and CamShift parameters. struct CV_EXPORTS CvMeanShiftTrackerParams { - enum { H = 0, HS = 1, HSV = 2 }; - CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS, - CvTermCriteria term_crit = CvTermCriteria()); - - int tracking_type; - vector h_range; - vector s_range; - vector v_range; - CvTermCriteria term_crit; + enum { H = 0, HS = 1, HSV = 2 }; + CvMeanShiftTrackerParams(int tracking_type = CvMeanShiftTrackerParams::HS, + CvTermCriteria term_crit = CvTermCriteria()); + + int tracking_type; + vector h_range; + vector s_range; + vector v_range; + CvTermCriteria term_crit; }; // Feature tracking parameters struct CV_EXPORTS CvFeatureTrackerParams { - enum { SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 }; - CvFeatureTrackerParams(int feature_type = 0, int window_size = 0) - { - feature_type = 0; - window_size = 0; - } - - int feature_type; // Feature type to use - int window_size; // Window size in pixels around which to search for new window + enum { SIFT = 0, SURF = 1, OPTICAL_FLOW = 2 }; + CvFeatureTrackerParams(int featureType = 0, int windowSize = 0) + { + feature_type = featureType; + window_size = windowSize; + } + + int feature_type; // Feature type to use + int window_size; // Window size in pixels around which to search for new window }; // Hybrid Tracking parameters for specifying weights of individual trackers and motion model. struct CV_EXPORTS CvHybridTrackerParams { - CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5, - CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(), - CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(), - CvMotionModel model = CvMotionModel()); - - float ft_tracker_weight; - float ms_tracker_weight; - CvFeatureTrackerParams ft_params; - CvMeanShiftTrackerParams ms_params; - CvEMParams em_params; - int motion_model; - float low_pass_gain; + CvHybridTrackerParams(float ft_tracker_weight = 0.5, float ms_tracker_weight = 0.5, + CvFeatureTrackerParams ft_params = CvFeatureTrackerParams(), + CvMeanShiftTrackerParams ms_params = CvMeanShiftTrackerParams(), + CvMotionModel model = CvMotionModel()); + + float ft_tracker_weight; + float ms_tracker_weight; + CvFeatureTrackerParams ft_params; + CvMeanShiftTrackerParams ms_params; + int motion_model; + float low_pass_gain; }; // Performs Camshift using parameters from MeanShiftTrackerParams class CV_EXPORTS CvMeanShiftTracker { private: - Mat hsv, hue; - Mat backproj; - Mat mask, maskroi; - MatND hist; - Rect prev_trackwindow; - RotatedRect prev_trackbox; - Point2f prev_center; + Mat hsv, hue; + Mat backproj; + Mat mask, maskroi; + MatND hist; + Rect prev_trackwindow; + RotatedRect prev_trackbox; + Point2f prev_center; public: - CvMeanShiftTrackerParams params; - - CvMeanShiftTracker(); - explicit CvMeanShiftTracker(CvMeanShiftTrackerParams _params); - ~CvMeanShiftTracker(); - void newTrackingWindow(Mat image, Rect selection); - RotatedRect updateTrackingWindow(Mat image); - Mat getHistogramProjection(int type); - void setTrackingWindow(Rect _window); - Rect getTrackingWindow(); - RotatedRect getTrackingEllipse(); - Point2f getTrackingCenter(); + CvMeanShiftTrackerParams params; + + CvMeanShiftTracker(); + explicit CvMeanShiftTracker(CvMeanShiftTrackerParams _params); + ~CvMeanShiftTracker(); + void newTrackingWindow(Mat image, Rect selection); + RotatedRect updateTrackingWindow(Mat image); + Mat getHistogramProjection(int type); + void setTrackingWindow(Rect _window); + Rect getTrackingWindow(); + RotatedRect getTrackingEllipse(); + Point2f getTrackingCenter(); }; // Performs SIFT/SURF feature tracking using parameters from FeatureTrackerParams class CV_EXPORTS CvFeatureTracker { private: - FeatureDetector* detector; - DescriptorExtractor* descriptor; - DescriptorMatcher* matcher; - vector matches; + Ptr dd; + Ptr matcher; + vector matches; - Mat prev_image; - Mat prev_image_bw; - Rect prev_trackwindow; - Point2d prev_center; + Mat prev_image; + Mat prev_image_bw; + Rect prev_trackwindow; + Point2d prev_center; - int ittr; - vector features[2]; + int ittr; + vector features[2]; public: - Mat disp_matches; - CvFeatureTrackerParams params; - - CvFeatureTracker(); - explicit CvFeatureTracker(CvFeatureTrackerParams params); - ~CvFeatureTracker(); - void newTrackingWindow(Mat image, Rect selection); - Rect updateTrackingWindow(Mat image); - Rect updateTrackingWindowWithSIFT(Mat image); - Rect updateTrackingWindowWithFlow(Mat image); - void setTrackingWindow(Rect _window); - Rect getTrackingWindow(); - Point2f getTrackingCenter(); + Mat disp_matches; + CvFeatureTrackerParams params; + + CvFeatureTracker(); + explicit CvFeatureTracker(CvFeatureTrackerParams params); + ~CvFeatureTracker(); + void newTrackingWindow(Mat image, Rect selection); + Rect updateTrackingWindow(Mat image); + Rect updateTrackingWindowWithSIFT(Mat image); + Rect updateTrackingWindowWithFlow(Mat image); + void setTrackingWindow(Rect _window); + Rect getTrackingWindow(); + Point2f getTrackingCenter(); }; // Performs Hybrid Tracking and combines individual trackers using EM or filters class CV_EXPORTS CvHybridTracker { private: - CvMeanShiftTracker* mstracker; - CvFeatureTracker* fttracker; + CvMeanShiftTracker* mstracker; + CvFeatureTracker* fttracker; - CvMat* samples; - CvMat* labels; - CvEM em_model; + CvMat* samples; + CvMat* labels; - Rect prev_window; - Point2f prev_center; - Mat prev_proj; - RotatedRect trackbox; + Rect prev_window; + Point2f prev_center; + Mat prev_proj; + RotatedRect trackbox; - int ittr; - Point2f curr_center; + int ittr; + Point2f curr_center; - inline float getL2Norm(Point2f p1, Point2f p2); - Mat getDistanceProjection(Mat image, Point2f center); - Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center); - void updateTrackerWithEM(Mat image); - void updateTrackerWithLowPassFilter(Mat image); + inline float getL2Norm(Point2f p1, Point2f p2); + Mat getDistanceProjection(Mat image, Point2f center); + Mat getGaussianProjection(Mat image, int ksize, double sigma, Point2f center); + void updateTrackerWithEM(Mat image); + void updateTrackerWithLowPassFilter(Mat image); public: - CvHybridTrackerParams params; - CvHybridTracker(); - explicit CvHybridTracker(CvHybridTrackerParams params); - ~CvHybridTracker(); - - void newTracker(Mat image, Rect selection); - void updateTracker(Mat image); - Rect getTrackingWindow(); + CvHybridTrackerParams params; + CvHybridTracker(); + explicit CvHybridTracker(CvHybridTrackerParams params); + ~CvHybridTracker(); + + void newTracker(Mat image, Rect selection); + void updateTracker(Mat image); + Rect getTrackingWindow(); }; typedef CvMotionModel MotionModel; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/openfabmap.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/openfabmap.hpp new file mode 100644 index 0000000..6b2834e --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/openfabmap.hpp @@ -0,0 +1,405 @@ +/*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. +// +// This file originates from the openFABMAP project: +// [http://code.google.com/p/openfabmap/] +// +// For published work which uses all or part of OpenFABMAP, please cite: +// [http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=6224843] +// +// Original Algorithm by Mark Cummins and Paul Newman: +// [http://ijr.sagepub.com/content/27/6/647.short] +// [http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=5613942] +// [http://ijr.sagepub.com/content/30/9/1100.abstract] +// +// License Agreement +// +// Copyright (C) 2012 Arren Glover [aj.glover@qut.edu.au] and +// Will Maddern [w.maddern@qut.edu.au], all rights reserved. +// +// +// 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 the copyright holders 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 __OPENCV_OPENFABMAP_H_ +#define __OPENCV_OPENFABMAP_H_ + +#include "opencv2/core/core.hpp" +#include "opencv2/features2d/features2d.hpp" + +#include +#include +#include +#include +#include + +namespace cv { + +namespace of2 { + +using std::list; +using std::map; +using std::multiset; + +/* + Return data format of a FABMAP compare call +*/ +struct CV_EXPORTS IMatch { + + IMatch() : + queryIdx(-1), imgIdx(-1), likelihood(-DBL_MAX), match(-DBL_MAX) { + } + IMatch(int _queryIdx, int _imgIdx, double _likelihood, double _match) : + queryIdx(_queryIdx), imgIdx(_imgIdx), likelihood(_likelihood), match( + _match) { + } + + int queryIdx; //query index + int imgIdx; //test index + + double likelihood; //raw loglikelihood + double match; //normalised probability + + bool operator<(const IMatch& m) const { + return match < m.match; + } + +}; + +/* + Base FabMap class. Each FabMap method inherits from this class. +*/ +class CV_EXPORTS FabMap { +public: + + //FabMap options + enum { + MEAN_FIELD = 1, + SAMPLED = 2, + NAIVE_BAYES = 4, + CHOW_LIU = 8, + MOTION_MODEL = 16 + }; + + FabMap(const Mat& clTree, double PzGe, double PzGNe, int flags, + int numSamples = 0); + virtual ~FabMap(); + + //methods to add training data for sampling method + virtual void addTraining(const Mat& queryImgDescriptor); + virtual void addTraining(const vector& queryImgDescriptors); + + //methods to add to the test data + virtual void add(const Mat& queryImgDescriptor); + virtual void add(const vector& queryImgDescriptors); + + //accessors + const vector& getTrainingImgDescriptors() const; + const vector& getTestImgDescriptors() const; + + //Main FabMap image comparison + void compare(const Mat& queryImgDescriptor, + vector& matches, bool addQuery = false, + const Mat& mask = Mat()); + void compare(const Mat& queryImgDescriptor, + const Mat& testImgDescriptors, vector& matches, + const Mat& mask = Mat()); + void compare(const Mat& queryImgDescriptor, + const vector& testImgDescriptors, + vector& matches, const Mat& mask = Mat()); + void compare(const vector& queryImgDescriptors, vector< + IMatch>& matches, bool addQuery = false, const Mat& mask = + Mat()); + void compare(const vector& queryImgDescriptors, + const vector& testImgDescriptors, + vector& matches, const Mat& mask = Mat()); + +protected: + + void compareImgDescriptor(const Mat& queryImgDescriptor, + int queryIndex, const vector& testImgDescriptors, + vector& matches); + + void addImgDescriptor(const Mat& queryImgDescriptor); + + //the getLikelihoods method is overwritten for each different FabMap + //method. + virtual void getLikelihoods(const Mat& queryImgDescriptor, + const vector& testImgDescriptors, + vector& matches); + virtual double getNewPlaceLikelihood(const Mat& queryImgDescriptor); + + //turn likelihoods into probabilities (also add in motion model if used) + void normaliseDistribution(vector& matches); + + //Chow-Liu Tree + int pq(int q); + double Pzq(int q, bool zq); + double PzqGzpq(int q, bool zq, bool zpq); + + //FAB-MAP Core + double PzqGeq(bool zq, bool eq); + double PeqGL(int q, bool Lzq, bool eq); + double PzqGL(int q, bool zq, bool zpq, bool Lzq); + double PzqGzpqL(int q, bool zq, bool zpq, bool Lzq); + double (FabMap::*PzGL)(int q, bool zq, bool zpq, bool Lzq); + + //data + Mat clTree; + vector trainingImgDescriptors; + vector testImgDescriptors; + vector priorMatches; + + //parameters + double PzGe; + double PzGNe; + double Pnew; + + double mBias; + double sFactor; + + int flags; + int numSamples; + +}; + +/* + The original FAB-MAP algorithm, developed based on: + http://ijr.sagepub.com/content/27/6/647.short +*/ +class CV_EXPORTS FabMap1: public FabMap { +public: + FabMap1(const Mat& clTree, double PzGe, double PzGNe, int flags, + int numSamples = 0); + virtual ~FabMap1(); +protected: + + //FabMap1 implementation of likelihood comparison + void getLikelihoods(const Mat& queryImgDescriptor, const vector< + Mat>& testImgDescriptors, vector& matches); +}; + +/* + A computationally faster version of the original FAB-MAP algorithm. A look- + up-table is used to precompute many of the reoccuring calculations +*/ +class CV_EXPORTS FabMapLUT: public FabMap { +public: + FabMapLUT(const Mat& clTree, double PzGe, double PzGNe, + int flags, int numSamples = 0, int precision = 6); + virtual ~FabMapLUT(); +protected: + + //FabMap look-up-table implementation of the likelihood comparison + void getLikelihoods(const Mat& queryImgDescriptor, const vector< + Mat>& testImgDescriptors, vector& matches); + + //precomputed data + int (*table)[8]; + + //data precision + int precision; +}; + +/* + The Accelerated FAB-MAP algorithm, developed based on: + http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=5613942 +*/ +class CV_EXPORTS FabMapFBO: public FabMap { +public: + FabMapFBO(const Mat& clTree, double PzGe, double PzGNe, int flags, + int numSamples = 0, double rejectionThreshold = 1e-8, double PsGd = + 1e-8, int bisectionStart = 512, int bisectionIts = 9); + virtual ~FabMapFBO(); + +protected: + + //FabMap Fast Bail-out implementation of the likelihood comparison + void getLikelihoods(const Mat& queryImgDescriptor, const vector< + Mat>& testImgDescriptors, vector& matches); + + //stucture used to determine word comparison order + struct WordStats { + WordStats() : + q(0), info(0), V(0), M(0) { + } + + WordStats(int _q, double _info) : + q(_q), info(_info), V(0), M(0) { + } + + int q; + double info; + mutable double V; + mutable double M; + + bool operator<(const WordStats& w) const { + return info < w.info; + } + + }; + + //private fast bail-out necessary functions + void setWordStatistics(const Mat& queryImgDescriptor, multiset& wordData); + double limitbisection(double v, double m); + double bennettInequality(double v, double m, double delta); + static bool compInfo(const WordStats& first, const WordStats& second); + + //parameters + double PsGd; + double rejectionThreshold; + int bisectionStart; + int bisectionIts; +}; + +/* + The FAB-MAP2.0 algorithm, developed based on: + http://ijr.sagepub.com/content/30/9/1100.abstract +*/ +class CV_EXPORTS FabMap2: public FabMap { +public: + + FabMap2(const Mat& clTree, double PzGe, double PzGNe, int flags); + virtual ~FabMap2(); + + //FabMap2 builds the inverted index and requires an additional training/test + //add function + void addTraining(const Mat& queryImgDescriptors) { + FabMap::addTraining(queryImgDescriptors); + } + void addTraining(const vector& queryImgDescriptors); + + void add(const Mat& queryImgDescriptors) { + FabMap::add(queryImgDescriptors); + } + void add(const vector& queryImgDescriptors); + +protected: + + //FabMap2 implementation of the likelihood comparison + void getLikelihoods(const Mat& queryImgDescriptor, const vector< + Mat>& testImgDescriptors, vector& matches); + double getNewPlaceLikelihood(const Mat& queryImgDescriptor); + + //the likelihood function using the inverted index + void getIndexLikelihoods(const Mat& queryImgDescriptor, vector< + double>& defaults, map >& invertedMap, + vector& matches); + void addToIndex(const Mat& queryImgDescriptor, + vector& defaults, + map >& invertedMap); + + //data + vector d1, d2, d3, d4; + vector > children; + + // TODO: inverted map a vector? + + vector trainingDefaults; + map > trainingInvertedMap; + + vector testDefaults; + map > testInvertedMap; + +}; +/* + A Chow-Liu tree is required by FAB-MAP. The Chow-Liu tree provides an + estimate of the full distribution of visual words using a minimum spanning + tree. The tree is generated through training data. +*/ +class CV_EXPORTS ChowLiuTree { +public: + ChowLiuTree(); + virtual ~ChowLiuTree(); + + //add data to the chow-liu tree before calling make + void add(const Mat& imgDescriptor); + void add(const vector& imgDescriptors); + + const vector& getImgDescriptors() const; + + Mat make(double infoThreshold = 0.0); + +private: + vector imgDescriptors; + Mat mergedImgDescriptors; + + typedef struct info { + float score; + short word1; + short word2; + } info; + + //probabilities extracted from mergedImgDescriptors + double P(int a, bool za); + double JP(int a, bool za, int b, bool zb); //a & b + double CP(int a, bool za, int b, bool zb); // a | b + + //calculating mutual information of all edges + void createBaseEdges(list& edges, double infoThreshold); + double calcMutInfo(int word1, int word2); + static bool sortInfoScores(const info& first, const info& second); + + //selecting minimum spanning egdges with maximum information + bool reduceEdgesToMinSpan(list& edges); + + //building the tree sctructure + Mat buildTree(int root_word, list &edges); + void recAddToTree(Mat &cltree, int q, int pq, + list &remaining_edges); + vector extractChildren(list &remaining_edges, int q); + +}; + +/* + A custom vocabulary training method based on: + http://www.springerlink.com/content/d1h6j8x552532003/ +*/ +class CV_EXPORTS BOWMSCTrainer: public BOWTrainer { +public: + BOWMSCTrainer(double clusterSize = 0.4); + virtual ~BOWMSCTrainer(); + + // Returns trained vocabulary (i.e. cluster centers). + virtual Mat cluster() const; + virtual Mat cluster(const Mat& descriptors) const; + +protected: + + double clusterSize; + +}; + +} + +} + +#endif /* OPENFABMAP_H_ */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/retina.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/retina.hpp new file mode 100644 index 0000000..3ee291a --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/contrib/retina.hpp @@ -0,0 +1,356 @@ +/*#****************************************************************************** + ** 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. + ** + ** + ** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. + ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. + ** + ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) + ** + ** Creation - enhancement process 2007-2011 + ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France + ** + ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). + ** Refer to the following research paper for more information: + ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 + ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: + ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. + ** + ** The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : + ** _take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: + ** ====> B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 + ** _take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. + ** ====> more informations in the above cited Jeanny Heraults's book. + ** + ** License Agreement + ** For Open Source Computer Vision Library + ** + ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. + ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. + ** + ** For Human Visual System tools (hvstools) + ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, 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: + ** + ** * Redistributions of source code must retain the above copyright notice, + ** this list of conditions and the following disclaimer. + ** + ** * 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. + ** + ** * The name of the copyright holders 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. + *******************************************************************************/ + +#ifndef __OPENCV_CONTRIB_RETINA_HPP__ +#define __OPENCV_CONTRIB_RETINA_HPP__ + +/* + * Retina.hpp + * + * Created on: Jul 19, 2011 + * Author: Alexandre Benoit + */ + +#include "opencv2/core/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support +#include + +namespace cv +{ + +enum RETINA_COLORSAMPLINGMETHOD +{ + RETINA_COLOR_RANDOM, //!< each pixel position is either R, G or B in a random choice + RETINA_COLOR_DIAGONAL,//!< color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... + RETINA_COLOR_BAYER//!< standard bayer sampling +}; + +class RetinaFilter; + +/** + * @class Retina a wrapper class which allows the Gipsa/Listic Labs model to be used. + * This retina model allows spatio-temporal image processing (applied on still images, video sequences). + * As a summary, these are the retina model properties: + * => It applies a spectral whithening (mid-frequency details enhancement) + * => high frequency spatio-temporal noise reduction + * => low frequency luminance to be reduced (luminance range compression) + * => local logarithmic luminance compression allows details to be enhanced in low light conditions + * + * USE : this model can be used basically for spatio-temporal video effects but also for : + * _using the getParvo method output matrix : texture analysiswith enhanced signal to noise ratio and enhanced details robust against input images luminance ranges + * _using the getMagno method output matrix : motion analysis also with the previously cited properties + * + * for more information, reer to the following papers : + * Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 + * Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891. + * + * The retina filter includes the research contributions of phd/research collegues from which code has been redrawn by the author : + * _take a look at the retinacolor.hpp module to discover Brice Chaix de Lavarene color mosaicing/demosaicing and the reference paper: + * ====> B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 + * _take a look at imagelogpolprojection.hpp to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. + * ====> more informations in the above cited Jeanny Heraults's book. + */ +class CV_EXPORTS Retina { + +public: + + // parameters structure for better clarity, check explenations on the comments of methods : setupOPLandIPLParvoChannel and setupIPLMagnoChannel + struct RetinaParameters{ + struct OPLandIplParvoParameters{ // Outer Plexiform Layer (OPL) and Inner Plexiform Layer Parvocellular (IplParvo) parameters + OPLandIplParvoParameters():colorMode(true), + normaliseOutput(true), + photoreceptorsLocalAdaptationSensitivity(0.7f), + photoreceptorsTemporalConstant(0.5f), + photoreceptorsSpatialConstant(0.53f), + horizontalCellsGain(0.0f), + hcellsTemporalConstant(1.f), + hcellsSpatialConstant(7.f), + ganglionCellsSensitivity(0.7f){};// default setup + bool colorMode, normaliseOutput; + float photoreceptorsLocalAdaptationSensitivity, photoreceptorsTemporalConstant, photoreceptorsSpatialConstant, horizontalCellsGain, hcellsTemporalConstant, hcellsSpatialConstant, ganglionCellsSensitivity; + }; + struct IplMagnoParameters{ // Inner Plexiform Layer Magnocellular channel (IplMagno) + IplMagnoParameters(): + normaliseOutput(true), + parasolCells_beta(0.f), + parasolCells_tau(0.f), + parasolCells_k(7.f), + amacrinCellsTemporalCutFrequency(1.2f), + V0CompressionParameter(0.95f), + localAdaptintegration_tau(0.f), + localAdaptintegration_k(7.f){};// default setup + bool normaliseOutput; + float parasolCells_beta, parasolCells_tau, parasolCells_k, amacrinCellsTemporalCutFrequency, V0CompressionParameter, localAdaptintegration_tau, localAdaptintegration_k; + }; + struct OPLandIplParvoParameters OPLandIplParvo; + struct IplMagnoParameters IplMagno; + }; + + /** + * Main constructor with most commun use setup : create an instance of color ready retina model + * @param inputSize : the input frame size + */ + Retina(Size inputSize); + + /** + * Complete Retina filter constructor which allows all basic structural parameters definition + * @param inputSize : the input frame size + * @param colorMode : the chosen processing mode : with or without color processing + * @param colorSamplingMethod: specifies which kind of color sampling will be used + * @param useRetinaLogSampling: activate retina log sampling, if true, the 2 following parameters can be used + * @param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak + * @param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied + */ + Retina(Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + + virtual ~Retina(); + + /** + * retreive retina input buffer size + */ + Size inputSize(); + + /** + * retreive retina output buffer size + */ + Size outputSize(); + + /** + * try to open an XML retina parameters file to adjust current retina instance setup + * => if the xml file does not exist, then default setup is applied + * => warning, Exceptions are thrown if read XML file is not valid + * @param retinaParameterFile : the parameters filename + * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error + */ + void setup(std::string retinaParameterFile="", const bool applyDefaultSetupOnFailure=true); + + + /** + * try to open an XML retina parameters file to adjust current retina instance setup + * => if the xml file does not exist, then default setup is applied + * => warning, Exceptions are thrown if read XML file is not valid + * @param fs : the open Filestorage which contains retina parameters + * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error + */ + void setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure=true); + + /** + * try to open an XML retina parameters file to adjust current retina instance setup + * => if the xml file does not exist, then default setup is applied + * => warning, Exceptions are thrown if read XML file is not valid + * @param newParameters : a parameters structures updated with the new target configuration + * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error + */ + void setup(RetinaParameters newParameters); + + /** + * @return the current parameters setup + */ + struct Retina::RetinaParameters getParameters(); + + /** + * parameters setup display method + * @return a string which contains formatted parameters information + */ + const std::string printSetup(); + + /** + * write xml/yml formated parameters information + * @rparam fs : the filename of the xml file that will be open and writen with formatted parameters information + */ + virtual void write( std::string fs ) const; + + + /** + * write xml/yml formated parameters information + * @param fs : a cv::Filestorage object ready to be filled + */ + virtual void write( FileStorage& fs ) const; + + /** + * setup the OPL and IPL parvo channels (see biologocal model) + * OPL is referred as Outer Plexiform Layer of the retina, it allows the spatio-temporal filtering which withens the spectrum and reduces spatio-temporal noise while attenuating global luminance (low frequency energy) + * IPL parvo is the OPL next processing stage, it refers to Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision. + * for more informations, please have a look at the paper Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011 + * @param colorMode : specifies if (true) color is processed of not (false) to then processing gray level image + * @param normaliseOutput : specifies if (true) output is rescaled between 0 and 255 of not (false) + * @param photoreceptorsLocalAdaptationSensitivity: the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases) + * @param photoreceptorsTemporalConstant: the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame + * @param photoreceptorsSpatialConstant: the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel + * @param horizontalCellsGain: gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0 + * @param HcellsTemporalConstant: the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors + * @param HcellsSpatialConstant: the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model) + * @param ganglionCellsSensitivity: the compression strengh of the ganglion cells local adaptation output, set a value between 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 230 + */ + void setupOPLandIPLParvoChannel(const bool colorMode=true, const bool normaliseOutput = true, const float photoreceptorsLocalAdaptationSensitivity=0.7, const float photoreceptorsTemporalConstant=0.5, const float photoreceptorsSpatialConstant=0.53, const float horizontalCellsGain=0, const float HcellsTemporalConstant=1, const float HcellsSpatialConstant=7, const float ganglionCellsSensitivity=0.7); + + /** + * set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel + * this channel processes signals outpint from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference paper for more details. + * @param normaliseOutput : specifies if (true) output is rescaled between 0 and 255 of not (false) + * @param parasolCells_beta: the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0 + * @param parasolCells_tau: the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response) + * @param parasolCells_k: the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5 + * @param amacrinCellsTemporalCutFrequency: the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, tipicall value is 5 + * @param V0CompressionParameter: the compression strengh of the ganglion cells local adaptation output, set a value between 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 200 + * @param localAdaptintegration_tau: specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation + * @param localAdaptintegration_k: specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation + */ + void setupIPLMagnoChannel(const bool normaliseOutput = true, const float parasolCells_beta=0, const float parasolCells_tau=0, const float parasolCells_k=7, const float amacrinCellsTemporalCutFrequency=1.2, const float V0CompressionParameter=0.95, const float localAdaptintegration_tau=0, const float localAdaptintegration_k=7); + + /** + * method which allows retina to be applied on an input image, after run, encapsulated retina module is ready to deliver its outputs using dedicated acccessors, see getParvo and getMagno methods + * @param inputImage : the input cv::Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits) + */ + void run(const Mat &inputImage); + + /** + * accessor of the details channel of the retina (models foveal vision) + * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV + */ + void getParvo(Mat &retinaOutput_parvo); + + /** + * accessor of the details channel of the retina (models foveal vision) + * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is the original retina filter model output, without any quantification or rescaling + */ + void getParvo(std::valarray &retinaOutput_parvo); + + /** + * accessor of the motion channel of the retina (models peripheral vision) + * @param retinaOutput_magno : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV + */ + void getMagno(Mat &retinaOutput_magno); + + /** + * accessor of the motion channel of the retina (models peripheral vision) + * @param retinaOutput_magno : the output buffer (reallocated if necessary), this output is the original retina filter model output, without any quantification or rescaling + */ + void getMagno(std::valarray &retinaOutput_magno); + + // original API level data accessors : get buffers addresses... + const std::valarray & getMagno() const; + const std::valarray & getParvo() const; + + /** + * activate color saturation as the final step of the color demultiplexing process + * -> this saturation is a sigmoide function applied to each channel of the demultiplexed image. + * @param saturateColors: boolean that activates color saturation (if true) or desactivate (if false) + * @param colorSaturationValue: the saturation factor + */ + void setColorSaturation(const bool saturateColors=true, const float colorSaturationValue=4.0); + + /** + * clear all retina buffers (equivalent to opening the eyes after a long period of eye close ;o) + */ + void clearBuffers(); + + /** + * Activate/desactivate the Magnocellular pathway processing (motion information extraction), by default, it is activated + * @param activate: true if Magnocellular output should be activated, false if not + */ + void activateMovingContoursProcessing(const bool activate); + + /** + * Activate/desactivate the Parvocellular pathway processing (contours information extraction), by default, it is activated + * @param activate: true if Parvocellular (contours information extraction) output should be activated, false if not + */ + void activateContoursProcessing(const bool activate); + +protected: + // Parameteres setup members + RetinaParameters _retinaParameters; // structure of parameters + + // Retina model related modules + std::valarray _inputBuffer; //!< buffer used to convert input cv::Mat to internal retina buffers format (valarrays) + + // pointer to retina model + RetinaFilter* _retinaFilter; //!< the pointer to the retina module, allocated with instance construction + + /** + * exports a valarray buffer outing from HVStools objects to a cv::Mat in CV_8UC1 (gray level picture) or CV_8UC3 (color) format + * @param grayMatrixToConvert the valarray to export to OpenCV + * @param nbRows : the number of rows of the valarray flatten matrix + * @param nbColumns : the number of rows of the valarray flatten matrix + * @param colorMode : a flag which mentions if matrix is color (true) or graylevel (false) + * @param outBuffer : the output matrix which is reallocated to satisfy Retina output buffer dimensions + */ + void _convertValarrayBuffer2cvMat(const std::valarray &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, Mat &outBuffer); + + /** + * + * @param inputMatToConvert : the OpenCV cv::Mat that has to be converted to gray or RGB valarray buffer that will be processed by the retina model + * @param outputValarrayMatrix : the output valarray + * @return the input image color mode (color=true, gray levels=false) + */ + bool _convertCvMat2ValarrayBuffer(const cv::Mat inputMatToConvert, std::valarray &outputValarrayMatrix); + + //! private method called by constructors, gathers their parameters and use them in a unified way + void _init(const Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + + +}; + +} +#endif /* __OPENCV_CONTRIB_RETINA_HPP__ */ + diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core.hpp old mode 100755 new mode 100644 similarity index 89% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core.hpp index 4b57388..561d26b --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core.hpp @@ -61,11 +61,12 @@ #include #include #include +#include #endif // SKIP_INCLUDES /*! \namespace cv Namespace where all the C++ OpenCV functionality resides -*/ +*/ namespace cv { #undef abs @@ -76,20 +77,28 @@ namespace cv { using std::vector; using std::string; using std::ptrdiff_t; - + template class CV_EXPORTS Size_; template class CV_EXPORTS Point_; template class CV_EXPORTS Rect_; template class CV_EXPORTS Vec; template class CV_EXPORTS Matx; - + typedef std::string String; -typedef std::basic_string WString; class Mat; class SparseMat; typedef Mat MatND; +class GlBuffer; +class GlTexture; +class GlArrays; +class GlCamera; + +namespace gpu { + class GpuMat; +} + class CV_EXPORTS MatExpr; class CV_EXPORTS MatOp_Base; class CV_EXPORTS MatArg; @@ -99,22 +108,26 @@ template class CV_EXPORTS Mat_; template class CV_EXPORTS MatIterator_; template class CV_EXPORTS MatConstIterator_; template class CV_EXPORTS MatCommaInitializer_; - + +#if !defined(ANDROID) || (defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_WCHAR_T) +typedef std::basic_string WString; + CV_EXPORTS string fromUtf16(const WString& str); CV_EXPORTS WString toUtf16(const string& str); +#endif CV_EXPORTS string format( const char* fmt, ... ); CV_EXPORTS string tempfile( const char* suffix CV_DEFAULT(0)); - + // matrix decomposition types enum { DECOMP_LU=0, DECOMP_SVD=1, DECOMP_EIG=2, DECOMP_CHOLESKY=3, DECOMP_QR=4, DECOMP_NORMAL=16 }; -enum { NORM_INF=1, NORM_L1=2, NORM_L2=4, NORM_TYPE_MASK=7, NORM_RELATIVE=8, NORM_MINMAX=32}; +enum { NORM_INF=1, NORM_L1=2, NORM_L2=4, NORM_L2SQR=5, NORM_HAMMING=6, NORM_HAMMING2=7, NORM_TYPE_MASK=7, NORM_RELATIVE=8, NORM_MINMAX=32 }; enum { CMP_EQ=0, CMP_GT=1, CMP_GE=2, CMP_LT=3, CMP_LE=4, CMP_NE=5 }; enum { GEMM_1_T=1, GEMM_2_T=2, GEMM_3_T=4 }; enum { DFT_INVERSE=1, DFT_SCALE=2, DFT_ROWS=4, DFT_COMPLEX_OUTPUT=16, DFT_REAL_OUTPUT=32, DCT_INVERSE = DFT_INVERSE, DCT_ROWS=DFT_ROWS }; - + /*! The standard OpenCV exception class. Instances of the class are thrown by various functions and methods in the case of critical errors. @@ -135,27 +148,27 @@ class CV_EXPORTS Exception : public std::exception /*! \return the error description and the context as a text string. - */ + */ virtual const char *what() const throw(); void formatMessage(); - + string msg; ///< the formatted error message int code; ///< error code @see CVStatus string err; ///< error description string func; ///< function name. Available only when the compiler supports __func__ macro string file; ///< source file name where the error has occured - int line; ///< line number in the source file where the error has occured + int line; ///< line number in the source file where the error has occured }; //! Signals an error and raises the exception. - + /*! By default the function prints information about the error to stderr, then it either stops if setBreakOnError() had been called before or raises the exception. It is possible to alternate error processing by using redirectError(). - + \param exc the exception raisen. */ CV_EXPORTS void error( const Exception& exc ); @@ -165,11 +178,11 @@ CV_EXPORTS void error( const Exception& exc ); /*! When the break-on-error mode is set, the default error handler issues a hardware exception, which can make debugging more convenient. - + \return the previous state */ CV_EXPORTS bool setBreakOnError(bool flag); - + typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); @@ -178,16 +191,16 @@ typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name, /*! The function sets the new error handler, called from cv::error(). - + \param errCallback the new error handler. If NULL, the default error handler is used. \param userdata the optional user data pointer, passed to the callback. \param prevUserdata the optional output parameter where the previous user data pointer is stored - + \return the previous error handler -*/ +*/ CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); - + #ifdef __GNUC__ #define CV_Error( code, msg ) cv::error( cv::Exception(code, msg, __func__, __FILE__, __LINE__) ) #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, __func__, __FILE__, __LINE__) ) @@ -197,7 +210,7 @@ CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, #define CV_Error_( code, args ) cv::error( cv::Exception(code, cv::format args, "", __FILE__, __LINE__) ) #define CV_Assert( expr ) if((expr)) ; else cv::error( cv::Exception(CV_StsAssert, #expr, "", __FILE__, __LINE__) ) #endif - + #ifdef _DEBUG #define CV_DbgAssert(expr) CV_Assert(expr) #else @@ -208,6 +221,8 @@ CV_EXPORTS void setNumThreads(int nthreads); CV_EXPORTS int getNumThreads(); CV_EXPORTS int getThreadNum(); +CV_EXPORTS_W const string& getBuildInformation(); + //! Returns the number of ticks. /*! @@ -223,7 +238,7 @@ CV_EXPORTS_W int64 getTickCount(); The function returns the number of ticks (as returned by cv::getTickCount()) per second. The following code computes the execution time in milliseconds: - + \code double exec_time = (double)getTickCount(); // do something ... @@ -244,7 +259,7 @@ CV_EXPORTS_W int64 getCPUTickCount(); /*! Returns SSE etc. support status - + The function returns true if certain hardware features are available. Currently, the following features are recognized: - CV_CPU_MMX - MMX @@ -256,7 +271,7 @@ CV_EXPORTS_W int64 getCPUTickCount(); - CV_CPU_SSE4_2 - SSE 4.2 - CV_CPU_POPCNT - POPCOUNT - CV_CPU_AVX - AVX - + \note {Note that the function output is not static. Once you called cv::useOptimized(false), most of the hardware acceleration is disabled and thus the function will returns false, until you call cv::useOptimized(true)} @@ -265,22 +280,22 @@ CV_EXPORTS_W bool checkHardwareSupport(int feature); //! returns the number of CPUs (including hyper-threading) CV_EXPORTS_W int getNumberOfCPUs(); - + /*! Allocates memory buffer - + This is specialized OpenCV memory allocation function that returns properly aligned memory buffers. The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree(). If there is not enough memory, the function calls cv::error(), which raises an exception. - + \param bufSize buffer size in bytes \return the allocated memory buffer. -*/ +*/ CV_EXPORTS void* fastMalloc(size_t bufSize); /*! Frees the memory allocated with cv::fastMalloc - + This is the corresponding deallocation function for cv::fastMalloc(). When ptr==NULL, the function has no effect. */ @@ -298,10 +313,10 @@ template static inline void deallocate(_Tp* ptr, size_t) /*! Aligns pointer by the certain number of bytes - + This small inline function aligns the pointer by the certian number of bytes by shifting it forward by 0 or a positive offset. -*/ +*/ template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) { return (_Tp*)(((size_t)ptr + n-1) & -n); @@ -309,7 +324,7 @@ template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_ /*! Aligns buffer size by the certain number of bytes - + This small inline function aligns a buffer size by the certian number of bytes by enlarging it. */ static inline size_t alignSize(size_t sz, int n) @@ -319,20 +334,20 @@ static inline size_t alignSize(size_t sz, int n) /*! Turns on/off available optimization - + The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way. - + \note{Since optimization may imply using special data structures, it may be unsafe to call this function anywhere in the code. Instead, call it somewhere at the top level.} -*/ +*/ CV_EXPORTS_W void setUseOptimized(bool onoff); /*! Returns the current optimization status - + The function returns the current optimization status, which is controlled by cv::setUseOptimized(). -*/ +*/ CV_EXPORTS_W bool useOptimized(); /*! @@ -340,7 +355,7 @@ CV_EXPORTS_W bool useOptimized(); */ template class CV_EXPORTS Allocator { -public: +public: typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; @@ -372,14 +387,14 @@ template class CV_EXPORTS Allocator void destroy(pointer p) { p->~_Tp(); } }; -/////////////////////// Vec (used as element of multi-channel images ///////////////////// +/////////////////////// Vec (used as element of multi-channel images ///////////////////// /*! A helper class for cv::DataType - + The class is specialized for each fundamental numerical data type supported by OpenCV. It provides DataDepth::value constant. -*/ +*/ template class CV_EXPORTS DataDepth {}; template<> class DataDepth { public: enum { value = CV_8U, fmt=(int)'u' }; }; @@ -397,42 +412,42 @@ template class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE ////////////////////////////// Small Matrix /////////////////////////// - + /*! A short numerical vector. - + This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you can perform basic arithmetical operations, access individual elements using [] operator etc. The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which elements are dynamically allocated in the heap. - + The template takes 2 parameters: -# _Tp element type -# cn the number of elements - + In addition to the universal notation like Vec, you can use shorter aliases - for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. + for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. */ - + struct CV_EXPORTS Matx_AddOp {}; struct CV_EXPORTS Matx_SubOp {}; struct CV_EXPORTS Matx_ScaleOp {}; struct CV_EXPORTS Matx_MulOp {}; struct CV_EXPORTS Matx_MatMulOp {}; struct CV_EXPORTS Matx_TOp {}; - + template class CV_EXPORTS Matx { public: typedef _Tp value_type; - typedef Matx<_Tp, MIN(m, n), 1> diag_type; + typedef Matx<_Tp, (m < n ? m : n), 1> diag_type; typedef Matx<_Tp, m, n> mat_type; enum { depth = DataDepth<_Tp>::value, rows = m, cols = n, channels = rows*cols, type = CV_MAKETYPE(depth, channels) }; - + //! default constructor Matx(); - + Matx(_Tp v0); //!< 1x1 matrix Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix @@ -451,7 +466,7 @@ template class CV_EXPORTS Matx _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix explicit Matx(const _Tp* vals); //!< initialize from a plain array - + static Matx all(_Tp alpha); static Matx zeros(); static Matx ones(); @@ -459,52 +474,52 @@ template class CV_EXPORTS Matx static Matx diag(const diag_type& d); static Matx randu(_Tp a, _Tp b); static Matx randn(_Tp a, _Tp b); - + //! dot product computed with the default precision _Tp dot(const Matx<_Tp, m, n>& v) const; - + //! dot product computed in double-precision arithmetics double ddot(const Matx<_Tp, m, n>& v) const; //! convertion to another data type template operator Matx() const; - + //! change the matrix shape template Matx<_Tp, m1, n1> reshape() const; - + //! extract part of the matrix template Matx<_Tp, m1, n1> get_minor(int i, int j) const; - + //! extract the matrix row Matx<_Tp, 1, n> row(int i) const; - + //! extract the matrix column Matx<_Tp, m, 1> col(int i) const; - + //! extract the matrix diagonal - Matx<_Tp, MIN(m,n), 1> diag() const; - + diag_type diag() const; + //! transpose the matrix Matx<_Tp, n, m> t() const; - + //! invert matrix the matrix Matx<_Tp, n, m> inv(int method=DECOMP_LU) const; - + //! solve linear system template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; - Matx<_Tp, n, 1> solve(const Matx<_Tp, m, 1>& rhs, int method) const; - + Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; + //! multiply two matrices element-wise Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; - + //! element access const _Tp& operator ()(int i, int j) const; _Tp& operator ()(int i, int j); - + //! 1D element access const _Tp& operator ()(int i) const; _Tp& operator ()(int i); - + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); @@ -515,7 +530,7 @@ template class CV_EXPORTS Matx _Tp val[m*n]; //< matrix elements }; - + typedef Matx Matx12f; typedef Matx Matx12d; typedef Matx Matx13f; @@ -524,7 +539,7 @@ typedef Matx Matx14f; typedef Matx Matx14d; typedef Matx Matx16f; typedef Matx Matx16d; - + typedef Matx Matx21f; typedef Matx Matx21d; typedef Matx Matx31f; @@ -540,42 +555,42 @@ typedef Matx Matx23f; typedef Matx Matx23d; typedef Matx Matx32f; typedef Matx Matx32d; - + typedef Matx Matx33f; typedef Matx Matx33d; - + typedef Matx Matx34f; typedef Matx Matx34d; typedef Matx Matx43f; typedef Matx Matx43d; - + typedef Matx Matx44f; typedef Matx Matx44d; typedef Matx Matx66f; -typedef Matx Matx66d; +typedef Matx Matx66d; /*! A short numerical vector. - + This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you can perform basic arithmetical operations, access individual elements using [] operator etc. The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which elements are dynamically allocated in the heap. - + The template takes 2 parameters: -# _Tp element type -# cn the number of elements - + In addition to the universal notation like Vec, you can use shorter aliases - for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. -*/ + for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. +*/ template class CV_EXPORTS Vec : public Matx<_Tp, cn, 1> { public: typedef _Tp value_type; enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) }; - + //! default constructor Vec(); @@ -592,18 +607,18 @@ template class CV_EXPORTS Vec : public Matx<_Tp, cn, 1> explicit Vec(const _Tp* values); Vec(const Vec<_Tp, cn>& v); - + static Vec all(_Tp alpha); //! per-element multiplication Vec mul(const Vec<_Tp, cn>& v) const; - + //! conjugation (makes sense for complex numbers and quaternions) Vec conj() const; - + /*! cross product of the two 3D vectors. - + For other dimensionalities the exception is raised */ Vec cross(const Vec& v) const; @@ -611,13 +626,13 @@ template class CV_EXPORTS Vec : public Matx<_Tp, cn, 1> template operator Vec() const; //! conversion to 4-element CvScalar. operator CvScalar() const; - + /*! element access */ const _Tp& operator [](int i) const; _Tp& operator[](int i); const _Tp& operator ()(int i) const; _Tp& operator ()(int i); - + Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); @@ -638,8 +653,8 @@ typedef Vec Vec4s; typedef Vec Vec2w; typedef Vec Vec3w; -typedef Vec Vec4w; - +typedef Vec Vec4w; + typedef Vec Vec2i; typedef Vec Vec3i; typedef Vec Vec4i; @@ -661,7 +676,7 @@ typedef Vec Vec6d; /*! A complex number class. - + The template class is similar and compatible with std::complex, however it provides slightly more convenient access to the real and imaginary parts using through the simple field access, as opposite to std::complex::real() and std::complex::imag(). @@ -697,16 +712,16 @@ typedef Complex Complexd; /*! template 2D point class. - + The class defines a point in 2D space. Data type of the point coordinates is specified - as a template parameter. There are a few shorter aliases available for user convenience. + as a template parameter. There are a few shorter aliases available for user convenience. See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d. -*/ +*/ template class CV_EXPORTS Point_ { public: typedef _Tp value_type; - + // various constructors Point_(); Point_(_Tp _x, _Tp _y); @@ -729,25 +744,27 @@ template class CV_EXPORTS Point_ _Tp dot(const Point_& pt) const; //! dot product computed in double-precision arithmetics double ddot(const Point_& pt) const; + //! cross-product + double cross(const Point_& pt) const; //! checks whether the point is inside the specified rectangle bool inside(const Rect_<_Tp>& r) const; - + _Tp x, y; //< the point coordinates }; /*! template 3D point class. - + The class defines a point in 3D space. Data type of the point coordinates is specified as a template parameter. - + \see cv::Point3i, cv::Point3f and cv::Point3d */ template class CV_EXPORTS Point3_ { public: typedef _Tp value_type; - + // various constructors Point3_(); Point3_(_Tp _x, _Tp _y, _Tp _z); @@ -770,7 +787,7 @@ template class CV_EXPORTS Point3_ double ddot(const Point3_& pt) const; //! cross product of the 2 3D points Point3_ cross(const Point3_& pt) const; - + _Tp x, y, z; //< the point coordinates }; @@ -778,7 +795,7 @@ template class CV_EXPORTS Point3_ /*! The 2D size class - + The class represents the size of a 2D rectangle, image size, matrix size etc. Normally, cv::Size ~ cv::Size_ is used. */ @@ -786,7 +803,7 @@ template class CV_EXPORTS Size_ { public: typedef _Tp value_type; - + //! various constructors Size_(); Size_(_Tp _width, _Tp _height); @@ -801,7 +818,7 @@ template class CV_EXPORTS Size_ //! conversion of another data type. template operator Size_<_Tp2>() const; - + //! conversion to the old-style OpenCV types operator CvSize() const; operator CvSize2D32f() const; @@ -813,7 +830,7 @@ template class CV_EXPORTS Size_ /*! The 2D up-right rectangle class - + The class represents a 2D rectangle with coordinates of the specified data type. Normally, cv::Rect ~ cv::Rect_ is used. */ @@ -821,7 +838,7 @@ template class CV_EXPORTS Rect_ { public: typedef _Tp value_type; - + //! various constructors Rect_(); Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); @@ -835,7 +852,7 @@ template class CV_EXPORTS Rect_ Point_<_Tp> tl() const; //! the bottom-right corner Point_<_Tp> br() const; - + //! size (width, height) of the rectangle Size_<_Tp> size() const; //! area (width*height) of the rectangle @@ -855,7 +872,7 @@ template class CV_EXPORTS Rect_ /*! \typedef - + shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations */ typedef Point_ Point2i; @@ -873,17 +890,17 @@ typedef Point3_ Point3d; /*! The rotated 2D rectangle. - + The class represents rotated (i.e. not up-right) rectangles on a plane. Each rectangle is described by the center point (mass center), length of each side (represented by cv::Size2f structure) and the rotation angle in degrees. -*/ +*/ class CV_EXPORTS RotatedRect { public: //! various constructors RotatedRect(); - RotatedRect(const Point2f& _center, const Size2f& _size, float _angle); + RotatedRect(const Point2f& center, const Size2f& size, float angle); RotatedRect(const CvBox2D& box); //! returns 4 vertices of the rectangle @@ -892,19 +909,19 @@ class CV_EXPORTS RotatedRect Rect boundingRect() const; //! conversion to the old-style CvBox2D structure operator CvBox2D() const; - + Point2f center; //< the rectangle mass center Size2f size; //< width and height of the rectangle - float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. + float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. }; //////////////////////////////// Scalar_ /////////////////////////////// /*! The template scalar class. - + This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements. - Normally, cv::Scalar ~ cv::Scalar_ is used. + Normally, cv::Scalar ~ cv::Scalar_ is used. */ template class CV_EXPORTS Scalar_ : public Vec<_Tp, 4> { @@ -925,10 +942,10 @@ template class CV_EXPORTS Scalar_ : public Vec<_Tp, 4> //! per-element product Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const; - + // returns (v0, -v1, -v2, -v3) Scalar_<_Tp> conj() const; - + // returns true iff v1 == v2 == v3 == 0 bool isReal() const; }; @@ -941,7 +958,7 @@ CV_EXPORTS void scalarToRawData(const Scalar& s, void* buf, int type, int unroll /*! The 2D range class - + This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix. */ class CV_EXPORTS Range @@ -962,7 +979,7 @@ class CV_EXPORTS Range /*! Informative template class for OpenCV "scalars". - + The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float), as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc. The common property of all such types (called "scalars", do not confuse it with cv::Scalar_) @@ -978,7 +995,6 @@ template class DataType typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; - enum { generic_type = 1, depth = -1, channels = 1, fmt=0, type = CV_MAKETYPE(depth, channels) }; }; @@ -1091,6 +1107,18 @@ template<> class DataType type = CV_MAKETYPE(depth, channels) }; }; +template class DataType > +{ +public: + typedef Matx<_Tp, m, n> value_type; + typedef Matx::work_type, m, n> work_type; + typedef _Tp channel_type; + typedef value_type vec_type; + enum { generic_type = 0, depth = DataDepth::value, channels = m*n, + fmt = ((channels-1)<<8) + DataDepth::fmt, + type = CV_MAKETYPE(depth, channels) }; +}; + template class DataType > { public: @@ -1199,27 +1227,26 @@ template<> class DataType typedef Vec vec_type; }; - //////////////////// generic_type ref-counting pointer class for C/C++ objects //////////////////////// /*! Smart pointer to dynamically allocated objects. - + This is template pointer-wrapping class that stores the associated reference counter along with the object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard, but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library). - + Basically, you can use "Ptr ptr" (or faster "const Ptr& ptr" for read-only access) everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class. To make it all work, you need to specialize Ptr<>::delete_obj(), like: - + \code template<> void Ptr::delete_obj() { call_destructor_func(obj); } \endcode - + \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(), since the default implementation calls "delete obj;"} - + \note{Another good property of the class is that the operations on the reference counter are atomic, i.e. it is safe to use the class in multi-threaded applications} */ @@ -1234,6 +1261,7 @@ template class CV_EXPORTS Ptr ~Ptr(); //! copy constructor. Copies the members and calls addref() Ptr(const Ptr& ptr); + template Ptr(const Ptr<_Tp2>& ptr); //! copy operator. Calls ptr.addref() and release() before copying the members Ptr& operator = (const Ptr& ptr); //! increments the reference counter @@ -1245,43 +1273,70 @@ template class CV_EXPORTS Ptr //! returns true iff obj==NULL bool empty() const; - + //! cast pointer to another type + template Ptr<_Tp2> ptr(); + template const Ptr<_Tp2> ptr() const; + //! helper operators making "Ptr ptr" use very similar to "T* ptr". _Tp* operator -> (); const _Tp* operator -> () const; operator _Tp* (); operator const _Tp*() const; - -protected: + _Tp* obj; //< the object pointer. int* refcount; //< the associated reference counter }; - + //////////////////////// Input/Output Array Arguments ///////////////////////////////// - + /*! - Proxy datatype for passing Mat's and vector<>'s as input parameters + Proxy datatype for passing Mat's and vector<>'s as input parameters */ class CV_EXPORTS _InputArray { public: - enum { KIND_SHIFT=16, NONE=0< _InputArray(const _Tp* vec, int n); template _InputArray(const vector<_Tp>& vec); template _InputArray(const vector >& vec); _InputArray(const vector& vec); + template _InputArray(const vector >& vec); + template _InputArray(const Mat_<_Tp>& m); template _InputArray(const Matx<_Tp, m, n>& matx); _InputArray(const Scalar& s); _InputArray(const double& val); + _InputArray(const GlBuffer& buf); + _InputArray(const GlTexture& tex); + _InputArray(const gpu::GpuMat& d_mat); + virtual Mat getMat(int i=-1) const; virtual void getMatVector(vector& mv) const; + virtual GlBuffer getGlBuffer() const; + virtual GlTexture getGlTexture() const; + virtual gpu::GpuMat getGpuMat() const; + virtual int kind() const; virtual Size size(int i=-1) const; virtual size_t total(int i=-1) const; @@ -1290,6 +1345,10 @@ class CV_EXPORTS _InputArray virtual int channels(int i=-1) const; virtual bool empty() const; +#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY + virtual ~_InputArray(); +#endif + int flags; void* obj; Size sz; @@ -1312,26 +1371,47 @@ enum /*! - Proxy datatype for passing Mat's and vector<>'s as input parameters + Proxy datatype for passing Mat's and vector<>'s as input parameters */ class CV_EXPORTS _OutputArray : public _InputArray { public: _OutputArray(); + _OutputArray(Mat& m); template _OutputArray(vector<_Tp>& vec); template _OutputArray(vector >& vec); _OutputArray(vector& vec); + template _OutputArray(vector >& vec); + template _OutputArray(Mat_<_Tp>& m); template _OutputArray(Matx<_Tp, m, n>& matx); + template _OutputArray(_Tp* vec, int n); + _OutputArray(gpu::GpuMat& d_mat); + + _OutputArray(const Mat& m); + template _OutputArray(const vector<_Tp>& vec); + template _OutputArray(const vector >& vec); + _OutputArray(const vector& vec); + template _OutputArray(const vector >& vec); + template _OutputArray(const Mat_<_Tp>& m); + template _OutputArray(const Matx<_Tp, m, n>& matx); + template _OutputArray(const _Tp* vec, int n); + _OutputArray(const gpu::GpuMat& d_mat); + virtual bool fixedSize() const; virtual bool fixedType() const; virtual bool needed() const; virtual Mat& getMatRef(int i=-1) const; - virtual void create(Size sz, int type, int i=-1, bool allocateVector=false, int fixedDepthMask=0) const; + /*virtual*/ gpu::GpuMat& getGpuMatRef() const; + virtual void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; virtual void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; virtual void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const; virtual void release() const; virtual void clear() const; + +#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY + virtual ~_OutputArray(); +#endif }; typedef const _InputArray& InputArray; @@ -1351,7 +1431,7 @@ static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); } /*! Custom array allocator - + */ class CV_EXPORTS MatAllocator { @@ -1362,10 +1442,10 @@ class CV_EXPORTS MatAllocator uchar*& datastart, uchar*& data, size_t* step) = 0; virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; }; - + /*! The n-dimensional matrix class. - + The class represents an n-dimensional dense numerical array that can act as a matrix, image, optical flow map, 3-focal tensor etc. It is very similar to CvMat and CvMatND types from earlier versions of OpenCV, @@ -1454,13 +1534,13 @@ class CV_EXPORTS MatAllocator \endcode
  • for quick initialization of small matrices and/or super-fast element access - + \code double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv(); \endcode - - + + partial yet very common cases of this "user-allocated data" case are conversions from CvMat and IplImage to cv::Mat. For this purpose there are special constructors taking pointers to CvMat or IplImage and the optional @@ -1470,7 +1550,7 @@ class CV_EXPORTS MatAllocator cv::Mat::operator CvMat() an cv::Mat::operator IplImage(). The operators do not copy the data. - + \code IplImage* img = cvLoadImage("greatwave.jpg", 1); Mat mtx(img); // convert IplImage* -> cv::Mat @@ -1487,7 +1567,7 @@ class CV_EXPORTS MatAllocator \endcode
  • by using comma-separated initializer: - + \code // create 3x3 double-precision identity matrix Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); @@ -1511,7 +1591,7 @@ class CV_EXPORTS MatAllocator cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member, cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be a part of another matrix or because there can some padding space in the end of each row for a proper alignment. - + \image html roi.png Given these parameters, address of the matrix element M_{ij} is computed as following: @@ -1582,23 +1662,23 @@ class CV_EXPORTS Mat Mat(); //! constructs 2D matrix of the specified size and type // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) - Mat(int _rows, int _cols, int _type); - Mat(Size _size, int _type); + Mat(int rows, int cols, int type); + Mat(Size size, int type); //! constucts 2D matrix and fills it with the specified value _s. - Mat(int _rows, int _cols, int _type, const Scalar& _s); - Mat(Size _size, int _type, const Scalar& _s); - + Mat(int rows, int cols, int type, const Scalar& s); + Mat(Size size, int type, const Scalar& s); + //! constructs n-dimensional matrix - Mat(int _ndims, const int* _sizes, int _type); - Mat(int _ndims, const int* _sizes, int _type, const Scalar& _s); - + Mat(int ndims, const int* sizes, int type); + Mat(int ndims, const int* sizes, int type, const Scalar& s); + //! copy constructor Mat(const Mat& m); //! constructor for matrix headers pointing to user-allocated data - Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP); - Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP); - Mat(int _ndims, const int* _sizes, int _type, void* _data, const size_t* _steps=0); - + Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); + Mat(Size size, int type, void* data, size_t step=AUTO_STEP); + Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); + //! creates a matrix header for a part of the bigger matrix Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); Mat(const Mat& m, const Rect& roi); @@ -1612,17 +1692,19 @@ class CV_EXPORTS Mat //! builds matrix from std::vector with or without copying the data template explicit Mat(const vector<_Tp>& vec, bool copyData=false); //! builds matrix from cv::Vec; the data is copied by default - template explicit Mat(const Vec<_Tp, n>& vec, - bool copyData=true); + template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); //! builds matrix from cv::Matx; the data is copied by default - template explicit Mat(const Matx<_Tp, m, n>& mtx, - bool copyData=true); + template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); //! builds matrix from a 2D point template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); //! builds matrix from a 3D point template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); //! builds matrix from comma initializer template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); + + //! download data from GpuMat + explicit Mat(const gpu::GpuMat& m); + //! destructor - calls release() ~Mat(); //! assignment operators @@ -1665,8 +1747,8 @@ class CV_EXPORTS Mat Mat& setTo(InputArray value, InputArray mask=noArray()); //! creates alternative matrix header for the same data, with different // number of channels and/or different number of rows. see cvReshape. - Mat reshape(int _cn, int _rows=0) const; - Mat reshape(int _cn, int _newndims, const int* _newsz) const; + Mat reshape(int cn, int rows=0) const; + Mat reshape(int cn, int newndims, const int* newsz) const; //! matrix transposition by means of matrix expressions MatExpr t() const; @@ -1674,7 +1756,7 @@ class CV_EXPORTS Mat MatExpr inv(int method=DECOMP_LU) const; //! per-element matrix multiplication by means of matrix expressions MatExpr mul(InputArray m, double scale=1) const; - + //! computes cross-product of 2 3D vectors Mat cross(InputArray m) const; //! computes dot-product @@ -1692,21 +1774,21 @@ class CV_EXPORTS Mat //! allocates new matrix data unless the matrix already has specified size and type. // previous data is unreferenced if needed. - void create(int _rows, int _cols, int _type); - void create(Size _size, int _type); - void create(int _ndims, const int* _sizes, int _type); - + void create(int rows, int cols, int type); + void create(Size size, int type); + void create(int ndims, const int* sizes, int type); + //! increases the reference counter; use with care to avoid memleaks void addref(); //! decreases reference counter; // deallocates the data when reference counter reaches 0. void release(); - + //! deallocates the matrix data void deallocate(); //! internal use function; properly re-allocates _size, _step arrays void copySize(const Mat& m); - + //! reserves enough space to fit sz hyper-planes void reserve(size_t sz); //! resizes matrix to the specified number of hyper-planes @@ -1721,7 +1803,7 @@ class CV_EXPORTS Mat void push_back(const Mat& m); //! removes several hyper-planes from bottom of the matrix void pop_back(size_t nelems=1); - + //! locates matrix header within a parent matrix. See below void locateROI( Size& wholeSize, Point& ofs ) const; //! moves/resizes the current matrix ROI inside the parent matrix. @@ -1738,19 +1820,19 @@ class CV_EXPORTS Mat operator CvMatND() const; //! converts header to IplImage; no data is copied operator IplImage() const; - + template operator vector<_Tp>() const; template operator Vec<_Tp, n>() const; template operator Matx<_Tp, m, n>() const; - + //! returns true iff the matrix data is continuous // (i.e. when there are no gaps between successive rows). // similar to CV_IS_MAT_CONT(cvmat->type) bool isContinuous() const; - + //! returns true if the matrix is a submatrix of another matrix bool isSubmatrix() const; - + //! returns element size in bytes, // similar to CV_ELEM_SIZE(cvmat->type) size_t elemSize() const; @@ -1768,66 +1850,66 @@ class CV_EXPORTS Mat bool empty() const; //! returns the total number of matrix elements size_t total() const; - + //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; //! returns pointer to i0-th submatrix along the dimension #0 uchar* ptr(int i0=0); const uchar* ptr(int i0=0) const; - + //! returns pointer to (i0,i1) submatrix along the dimensions #0 and #1 uchar* ptr(int i0, int i1); const uchar* ptr(int i0, int i1) const; - + //! returns pointer to (i0,i1,i3) submatrix along the dimensions #0, #1, #2 uchar* ptr(int i0, int i1, int i2); const uchar* ptr(int i0, int i1, int i2) const; - + //! returns pointer to the matrix element uchar* ptr(const int* idx); //! returns read-only pointer to the matrix element const uchar* ptr(const int* idx) const; - + template uchar* ptr(const Vec& idx); template const uchar* ptr(const Vec& idx) const; //! template version of the above method template _Tp* ptr(int i0=0); template const _Tp* ptr(int i0=0) const; - + template _Tp* ptr(int i0, int i1); template const _Tp* ptr(int i0, int i1) const; - + template _Tp* ptr(int i0, int i1, int i2); template const _Tp* ptr(int i0, int i1, int i2) const; - + template _Tp* ptr(const int* idx); template const _Tp* ptr(const int* idx) const; - + template _Tp* ptr(const Vec& idx); template const _Tp* ptr(const Vec& idx) const; - + //! the same as above, with the pointer dereferencing template _Tp& at(int i0=0); template const _Tp& at(int i0=0) const; - + template _Tp& at(int i0, int i1); template const _Tp& at(int i0, int i1) const; - + template _Tp& at(int i0, int i1, int i2); template const _Tp& at(int i0, int i1, int i2) const; - + template _Tp& at(const int* idx); template const _Tp& at(const int* idx) const; - + template _Tp& at(const Vec& idx); template const _Tp& at(const Vec& idx) const; - + //! special versions for 2D arrays (especially convenient for referencing image pixels) template _Tp& at(Point pt); template const _Tp& at(Point pt) const; - + //! template methods for iteration over matrix elements. // the iterators take care of skipping gaps in the end of rows (if any) template MatIterator_<_Tp> begin(); @@ -1854,15 +1936,15 @@ class CV_EXPORTS Mat //! pointer to the reference counter; // when matrix points to user-allocated data, the pointer is NULL int* refcount; - + //! helper fields used in locateROI and adjustROI uchar* datastart; uchar* dataend; uchar* datalimit; - + //! custom allocator MatAllocator* allocator; - + struct CV_EXPORTS MSize { MSize(int* _p); @@ -1872,10 +1954,10 @@ class CV_EXPORTS Mat operator const int*() const; bool operator == (const MSize& sz) const; bool operator != (const MSize& sz) const; - + int* p; }; - + struct CV_EXPORTS MStep { MStep(); @@ -1884,21 +1966,24 @@ class CV_EXPORTS Mat size_t& operator[](int i); operator size_t() const; MStep& operator = (size_t s); - + size_t* p; size_t buf[2]; protected: MStep& operator = (const MStep&); }; - + MSize size; MStep step; + +protected: + void initEmpty(); }; /*! Random Number Generator - + The class implements RNG using Multiply-with-Carry algorithm */ class CV_EXPORTS RNG @@ -1907,7 +1992,7 @@ class CV_EXPORTS RNG enum { UNIFORM=0, NORMAL=1 }; RNG(); - RNG(uint64 _state); + RNG(uint64 state); //! updates the state and returns the next 32-bit unsigned integer random number unsigned next(); @@ -1917,7 +2002,7 @@ class CV_EXPORTS RNG operator short(); operator unsigned(); //! returns a random integer sampled uniformly from [0, N). - unsigned operator()(unsigned N); + unsigned operator ()(unsigned N); unsigned operator ()(); operator int(); operator float(); @@ -1928,7 +2013,7 @@ class CV_EXPORTS RNG float uniform(float a, float b); //! returns uniformly distributed double-precision floating-point random number from [a,b) range double uniform(double a, double b); - void fill( InputOutputArray mat, int distType, InputArray a, InputArray b ); + void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false ); //! returns Gaussian random variate with mean zero. double gaussian(double sigma); @@ -1957,46 +2042,55 @@ class CV_EXPORTS TermCriteria TermCriteria(const CvTermCriteria& criteria); //! conversion from CvTermCriteria operator CvTermCriteria() const; - + int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS int maxCount; // the maximum number of iterations/elements double epsilon; // the desired accuracy }; - + +typedef void (*BinaryFunc)(const uchar* src1, size_t step1, + const uchar* src2, size_t step2, + uchar* dst, size_t step, Size sz, + void*); + +CV_EXPORTS BinaryFunc getConvertFunc(int sdepth, int ddepth); +CV_EXPORTS BinaryFunc getConvertScaleFunc(int sdepth, int ddepth); +CV_EXPORTS BinaryFunc getCopyMaskFunc(size_t esz); + //! swaps two matrices CV_EXPORTS void swap(Mat& a, Mat& b); - + //! converts array (CvMat or IplImage) to cv::Mat CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, bool allowND=true, int coiMode=0); //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage -CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); +CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); //! adds one matrix to another (dst = src1 + src2) CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray(), int dtype=-1); -//! subtracts one matrix from another (dst = src1 - src2) +//! subtracts one matrix from another (dst = src1 - src2) CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray(), int dtype=-1); //! computes element-wise weighted product of the two arrays (dst = scale*src1*src2) CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, OutputArray dst, double scale=1, int dtype=-1); - + //! computes element-wise weighted quotient of the two arrays (dst = scale*src1/src2) CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, double scale=1, int dtype=-1); - + //! computes element-wise weighted reciprocal of an array (dst = scale/src2) CV_EXPORTS_W void divide(double scale, InputArray src2, OutputArray dst, int dtype=-1); //! adds scaled array to another one (dst = alpha*src1 + src2) CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); - + //! computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype=-1); @@ -2009,9 +2103,12 @@ CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst, int interpolation=0); //! computes sum of array elements -CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); +CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); //! computes the number of nonzero array elements CV_EXPORTS_W int countNonZero( InputArray src ); +//! returns the list of locations of non-zero pixels +CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); + //! computes mean value of selected array elements CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask=noArray()); //! computes mean value and standard deviation of all or selected array elements @@ -2022,7 +2119,15 @@ CV_EXPORTS_W double norm(InputArray src1, int normType=NORM_L2, InputArray mask= //! computes norm of selected part of the difference between two arrays CV_EXPORTS_W double norm(InputArray src1, InputArray src2, int normType=NORM_L2, InputArray mask=noArray()); -//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values + +//! naive nearest neighbor finder +CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, + OutputArray dist, int dtype, OutputArray nidx, + int normType=NORM_L2, int K=0, + InputArray mask=noArray(), int update=0, + bool crosscheck=false); + +//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values CV_EXPORTS_W void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0, int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray()); @@ -2032,20 +2137,24 @@ CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, CV_OUT Point* maxLoc=0, InputArray mask=noArray()); CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0, InputArray mask=noArray()); - + //! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1); //! makes multi-channel array out of several single-channel arrays CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); +CV_EXPORTS void merge(const vector& mv, OutputArray dst ); + //! makes multi-channel array out of several single-channel arrays -CV_EXPORTS_W void merge(const vector& mv, OutputArray dst); - +CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); + //! copies each plane of a multi-channel array to a dedicated array CV_EXPORTS void split(const Mat& src, Mat* mvbegin); +CV_EXPORTS void split(const Mat& m, vector& mv ); + //! copies each plane of a multi-channel array to a dedicated array -CV_EXPORTS_W void split(const Mat& m, CV_OUT vector& mv); - +CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); + //! copies selected channels from the input arrays to the selected channels of the output arrays CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, const int* fromTo, size_t npairs); @@ -2059,22 +2168,22 @@ CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); //! inserts a single channel to dst (coi is 0-based index) CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); - + //! reverses the order of the rows, columns or both in a matrix CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); //! replicates the input matrix the specified number of times in the horizontal and/or vertical direction CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst); CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx); - + CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst); CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); -CV_EXPORTS_W void hconcat(InputArray src, OutputArray dst); +CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); -CV_EXPORTS_W void vconcat(InputArray src, OutputArray dst); - +CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); + //! computes bitwise conjunction of the two arrays (dst = src1 & src2) CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray()); @@ -2089,9 +2198,9 @@ CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, InputArray mask=noArray()); //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2)) CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); -//! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) +//! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, - InputArray upperb, OutputArray dst); + InputArray upperb, OutputArray dst); //! compares elements of two arrays (dst = src1 src2) CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); //! computes per-element minimum of two arrays (dst = min(src1, src2)) @@ -2106,11 +2215,11 @@ CV_EXPORTS void min(const Mat& src1, double src2, Mat& dst); //! computes per-element maximum of two arrays (dst = max(src1, src2)) CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); //! computes per-element maximum of array and scalar (dst = max(src1, src2)) -CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst); - +CV_EXPORTS void max(const Mat& src1, double src2, Mat& dst); + //! computes square root of each matrix element (dst = src**0.5) CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); -//! raises the input matrix elements to the specified power (b = a**power) +//! raises the input matrix elements to the specified power (b = a**power) CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); //! computes exponent of each matrix element (dst = e**src) CV_EXPORTS_W void exp(InputArray src, OutputArray dst); @@ -2120,6 +2229,12 @@ CV_EXPORTS_W void log(InputArray src, OutputArray dst); CV_EXPORTS_W float cubeRoot(float val); //! computes the angle in degrees (0..360) of the vector (x,y) CV_EXPORTS_W float fastAtan2(float y, float x); + +CV_EXPORTS void exp(const float* src, float* dst, int n); +CV_EXPORTS void log(const float* src, float* dst, int n); +CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); + //! converts polar coordinates to Cartesian CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, OutputArray x, OutputArray y, bool angleInDegrees=false); @@ -2133,8 +2248,11 @@ CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, //! computes magnitude (magnitude(i)) of each (x(i), y(i)) vector CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); //! checks that each matrix element is within the specified range. -CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pt=0, +CV_EXPORTS_W bool checkRange(InputArray a, bool quiet=true, CV_OUT Point* pos=0, double minVal=-DBL_MAX, double maxVal=DBL_MAX); +//! converts NaN's to the given number +CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val=0); + //! implements generalized matrix product algorithm GEMM from BLAS CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, InputArray src3, double gamma, OutputArray dst, int flags=0); @@ -2149,7 +2267,7 @@ CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); //! performs perspective transformation of each element of multi-channel input matrix CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); -//! extends the symmetrical matrix from the lower half or from the upper half +//! extends the symmetrical matrix from the lower half or from the upper half CV_EXPORTS_W void completeSymm(InputOutputArray mtx, bool lowerToUpper=false); //! initializes scaled identity matrix CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s=Scalar(1)); @@ -2165,10 +2283,10 @@ CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, enum { - SORT_EVERY_ROW=0, - SORT_EVERY_COLUMN=1, - SORT_ASCENDING=0, - SORT_DESCENDING=16 + SORT_EVERY_ROW=0, + SORT_EVERY_COLUMN=1, + SORT_ASCENDING=0, + SORT_DESCENDING=16 }; //! sorts independently each matrix row or each matrix column @@ -2191,12 +2309,12 @@ CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors, enum { - COVAR_SCRAMBLED=0, - COVAR_NORMAL=1, - COVAR_USE_AVG=2, - COVAR_SCALE=4, - COVAR_ROWS=8, - COVAR_COLS=16 + COVAR_SCRAMBLED=0, + COVAR_NORMAL=1, + COVAR_USE_AVG=2, + COVAR_SCALE=4, + COVAR_ROWS=8, + COVAR_COLS=16 }; //! computes covariation matrix of a set of samples @@ -2208,7 +2326,7 @@ CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, /*! Principal Component Analysis - + The class PCA is used to compute the special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix computed from the input set of vectors. After PCA is performed, vectors can be transformed from @@ -2216,12 +2334,12 @@ CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, prominent eigenvectors (called the principal components), corresponding to the largest eigenvalues of the covariation matrix. Thus the dimensionality of the vector and the correlation between the coordinates is reduced. - + The following sample is the function that takes two matrices. The first one stores the set of vectors (a row per vector) that is used to compute PCA, the second one stores another "test" set of vectors (a row per vector) that are first compressed with PCA, then reconstructed back and then the reconstruction error norm is computed and printed for each vector. - + \code using namespace cv; @@ -2241,9 +2359,9 @@ CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, if( !testset.data ) return pca; CV_Assert( testset.cols == pcaset.cols ); - + compressed.create(testset.rows, maxComponents, testset.type()); - + Mat reconstructed; for( int i = 0; i < testset.rows; i++ ) { @@ -2267,8 +2385,10 @@ class CV_EXPORTS PCA PCA(); //! the constructor that performs PCA PCA(InputArray data, InputArray mean, int flags, int maxComponents=0); + PCA(InputArray data, InputArray mean, int flags, double retainedVariance); //! operator that performs PCA. The previously stored data, if any, is released PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0); + PCA& computeVar(InputArray data, InputArray mean, int flags, double retainedVariance); //! projects vector from the original space to the principal components subspace Mat project(InputArray vec) const; //! projects vector from the original space to the principal components subspace @@ -2285,7 +2405,10 @@ class CV_EXPORTS PCA CV_EXPORTS_W void PCACompute(InputArray data, CV_OUT InputOutputArray mean, OutputArray eigenvectors, int maxComponents=0); - + +CV_EXPORTS_W void PCAComputeVar(InputArray data, CV_OUT InputOutputArray mean, + OutputArray eigenvectors, double retainedVariance); + CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, InputArray eigenvectors, OutputArray result); @@ -2295,11 +2418,11 @@ CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, /*! Singular Value Decomposition class - + The class is used to compute Singular Value Decomposition of a floating-point matrix and then use it to solve least-square problems, under-determined linear systems, invert matrices, compute condition numbers etc. - + For a bit faster operation you can pass flags=SVD::MODIFY_A|... to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute condition number of a matrix or absolute value of its determinant - you do not need SVD::u or SVD::vt, @@ -2326,17 +2449,17 @@ class CV_EXPORTS SVD static void backSubst( InputArray w, InputArray u, InputArray vt, InputArray rhs, OutputArray dst ); - + template static void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); template static void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); template static void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); - + //! finds dst = arg min_{|dst|=1} |m*dst| static void solveZ( InputArray src, OutputArray dst ); - //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix + //! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix void backSubst( InputArray rhs, OutputArray dst ) const; Mat u, w, vt; @@ -2391,7 +2514,7 @@ template static inline _Tp randu() { return (_Tp)theRNG(); } //! fills array with uniformly-distributed random numbers from the range [low, high) CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); - + //! fills array with normally-distributed random numbers with the specified mean and the standard deviation CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); @@ -2400,32 +2523,32 @@ CV_EXPORTS void randShuffle(InputOutputArray dst, double iterFactor=1., RNG* rng CV_EXPORTS_AS(randShuffle) void randShuffle_(InputOutputArray dst, double iterFactor=1.); //! draws the line segment (pt1, pt2) in the image -CV_EXPORTS_W void line(Mat& img, Point pt1, Point pt2, const Scalar& color, +CV_EXPORTS_W void line(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0); //! draws the rectangle outline or a solid rectangle with the opposite corners pt1 and pt2 in the image -CV_EXPORTS_W void rectangle(Mat& img, Point pt1, Point pt2, +CV_EXPORTS_W void rectangle(CV_IN_OUT Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0); - -//! draws the rectangle outline or a solid rectangle covering rec in the image -CV_EXPORTS void rectangle(Mat& img, Rect rec, + +//! draws the rectangle outline or a solid rectangle covering rec in the image +CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0); //! draws the circle outline or a solid circle in the image -CV_EXPORTS_W void circle(Mat& img, Point center, int radius, +CV_EXPORTS_W void circle(CV_IN_OUT Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0); //! draws an elliptic arc, ellipse sector or a rotated ellipse in the image -CV_EXPORTS_W void ellipse(Mat& img, Point center, Size axes, +CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0); //! draws a rotated ellipse in the image -CV_EXPORTS_W void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, +CV_EXPORTS_W void ellipse(CV_IN_OUT Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=8); //! draws a filled convex polygon in the image @@ -2463,7 +2586,7 @@ CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_ /*! Line iterator class - + The class is used to iterate over all the pixels on the raster line segment connecting two specified points. */ @@ -2511,7 +2634,7 @@ enum //! renders text string in the image CV_EXPORTS_W void putText( Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, - int thickness=1, int linetype=8, + int thickness=1, int lineType=8, bool bottomLeftOrigin=false ); //! returns bounding box of the text string @@ -2523,11 +2646,11 @@ CV_EXPORTS_W Size getTextSize(const string& text, int fontFace, /*! Template matrix class derived from Mat - + The class Mat_ is a "thin" template wrapper on top of cv::Mat. It does not have any extra data fields, nor it or cv::Mat have any virtual methods and thus references or pointers to these two classes can be safely converted one to another. But do it with care, for example: - + \code // create 100x100 8-bit matrix Mat M(100,100,CV_8U); @@ -2536,12 +2659,12 @@ CV_EXPORTS_W Size getTextSize(const string& text, int fontFace, // the program will likely crash at the statement below M1(99,99) = 1.f; \endcode - + While cv::Mat is sufficient in most cases, cv::Mat_ can be more convenient if you use a lot of element access operations and if you know matrix type at compile time. Note that cv::Mat::at<_Tp>(int y, int x) and cv::Mat_<_Tp>::operator ()(int y, int x) do absolutely the same thing and run at the same speed, but the latter is certainly shorter: - + \code Mat_ M(20,20); for(int i = 0; i < M.rows; i++) @@ -2551,9 +2674,9 @@ CV_EXPORTS_W Size getTextSize(const string& text, int fontFace, eigen(M,E,V); cout << E.at(0,0)/E.at(M.rows-1,0); \endcode - + It is easy to use Mat_ for multi-channel images/matrices - just pass cv::Vec as cv::Mat_ template parameter: - + \code // allocate 320x240 color image and fill it with green (in RGB space) Mat_ img(240, 320, Vec3b(0,255,0)); @@ -2573,7 +2696,7 @@ template class CV_EXPORTS Mat_ : public Mat typedef typename DataType<_Tp>::channel_type channel_type; typedef MatIterator_<_Tp> iterator; typedef MatConstIterator_<_Tp> const_iterator; - + //! default constructor Mat_(); //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) @@ -2582,7 +2705,7 @@ template class CV_EXPORTS Mat_ : public Mat Mat_(int _rows, int _cols, const _Tp& value); //! equivalent to Mat(_size, DataType<_Tp>::type) explicit Mat_(Size _size); - //! constructor that sets each matrix element to specified value + //! constructor that sets each matrix element to specified value Mat_(Size _size, const _Tp& value); //! n-dim array constructor Mat_(int _ndims, const int* _sizes); @@ -2662,13 +2785,12 @@ template class CV_EXPORTS Mat_ : public Mat static MatExpr eye(Size size); //! some more overriden methods - Mat_ reshape(int _rows) const; Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); Mat_ operator()( const Range& rowRange, const Range& colRange ) const; Mat_ operator()( const Rect& roi ) const; Mat_ operator()( const Range* ranges ) const; - //! more convenient forms of row and element access operators + //! more convenient forms of row and element access operators _Tp* operator [](int y); const _Tp* operator [](int y) const; @@ -2676,12 +2798,12 @@ template class CV_EXPORTS Mat_ : public Mat _Tp& operator ()(const int* idx); //! returns read-only reference to the specified element const _Tp& operator ()(const int* idx) const; - + //! returns reference to the specified element template _Tp& operator ()(const Vec& idx); //! returns read-only reference to the specified element template const _Tp& operator ()(const Vec& idx) const; - + //! returns reference to the specified element (1D case) _Tp& operator ()(int idx0); //! returns read-only reference to the specified element (1D case) @@ -2694,7 +2816,7 @@ template class CV_EXPORTS Mat_ : public Mat _Tp& operator ()(int idx0, int idx1, int idx2); //! returns read-only reference to the specified element (3D case) const _Tp& operator ()(int idx0, int idx1, int idx2) const; - + _Tp& operator ()(Point pt); const _Tp& operator ()(Point pt) const; @@ -2746,10 +2868,10 @@ class CV_EXPORTS MatConstIterator typedef const uchar** pointer; typedef uchar* reference; typedef std::random_access_iterator_tag iterator_category; - + //! default constructor MatConstIterator(); - //! constructor that sets the iterator to the beginning of the matrix + //! constructor that sets the iterator to the beginning of the matrix MatConstIterator(const Mat* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, int _row, int _col=0); @@ -2759,14 +2881,14 @@ class CV_EXPORTS MatConstIterator MatConstIterator(const Mat* _m, const int* _idx); //! copy constructor MatConstIterator(const MatConstIterator& it); - + //! copy operator MatConstIterator& operator = (const MatConstIterator& it); //! returns the current matrix element uchar* operator *() const; //! returns the i-th matrix element, relative to the current uchar* operator [](ptrdiff_t i) const; - + //! shifts the iterator forward by the specified number of elements MatConstIterator& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements @@ -2786,18 +2908,18 @@ class CV_EXPORTS MatConstIterator ptrdiff_t lpos() const; void seek(ptrdiff_t ofs, bool relative=false); void seek(const int* _idx, bool relative=false); - + const Mat* m; size_t elemSize; uchar* ptr; uchar* sliceStart; uchar* sliceEnd; }; - + /*! Matrix read-only iterator - - */ + + */ template class CV_EXPORTS MatConstIterator_ : public MatConstIterator { @@ -2810,7 +2932,7 @@ class CV_EXPORTS MatConstIterator_ : public MatConstIterator //! default constructor MatConstIterator_(); - //! constructor that sets the iterator to the beginning of the matrix + //! constructor that sets the iterator to the beginning of the matrix MatConstIterator_(const Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); @@ -2827,7 +2949,7 @@ class CV_EXPORTS MatConstIterator_ : public MatConstIterator _Tp operator *() const; //! returns the i-th matrix element, relative to the current _Tp operator [](ptrdiff_t i) const; - + //! shifts the iterator forward by the specified number of elements MatConstIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements @@ -2847,7 +2969,7 @@ class CV_EXPORTS MatConstIterator_ : public MatConstIterator /*! Matrix read-write iterator - + */ template class CV_EXPORTS MatIterator_ : public MatConstIterator_<_Tp> @@ -2859,7 +2981,7 @@ class CV_EXPORTS MatIterator_ : public MatConstIterator_<_Tp> //! the default constructor MatIterator_(); - //! constructor that sets the iterator to the beginning of the matrix + //! constructor that sets the iterator to the beginning of the matrix MatIterator_(Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); @@ -2895,17 +3017,17 @@ template class CV_EXPORTS MatOp_Iter_; /*! Comma-separated Matrix Initializer - + The class instances are usually not created explicitly. Instead, they are created on "matrix << firstValue" operator. - + The sample below initializes 2x2 rotation matrix: - + \code double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); Mat R = (Mat_(2,2) << a, -b, b, a); \endcode -*/ +*/ template class CV_EXPORTS MatCommaInitializer_ { public: @@ -2939,10 +3061,10 @@ template class CV_EXPORTS VecCommaInitializer : public Matx template VecCommaInitializer<_Tp, m>& operator , (T2 val); Vec<_Tp, m> operator *() const; }; - + /*! Automatically Allocated Buffer Class - + The class is used for temporary buffers in functions and methods. If a temporary buffer is usually small (a few K's of memory), but its size depends on the parameters, it makes sense to create a small @@ -2951,15 +3073,15 @@ template class CV_EXPORTS VecCommaInitializer : public Matx and released after the processing. Therefore, in typical cases, when the buffer size is small, there is no overhead associated with malloc()/free(). At the same time, there is no limit on the size of processed data. - + This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and the number of stack-allocated elements. Here is how the class is used: - + \code void my_func(const cv::Mat& m) { cv::AutoBuffer buf; // create automatic buffer containing 1000 floats - + buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, // otherwise the buffer of "m.rows" floats will be allocated // dynamically and deallocated in cv::AutoBuffer destructor @@ -2977,10 +3099,10 @@ template class CV_EXPORTS Au AutoBuffer(); //! constructor taking the real buffer size AutoBuffer(size_t _size); - //! destructor. calls deallocate() + //! destructor. calls deallocate() ~AutoBuffer(); - //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used + //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used void allocate(size_t _size); //! deallocates the buffer if it was dynamically allocated void deallocate(); @@ -3002,18 +3124,18 @@ template class CV_EXPORTS Au /*! n-Dimensional Dense Matrix Iterator Class. - + The class cv::NAryMatIterator is used for iterating over one or more n-dimensional dense arrays (cv::Mat's). - + The iterator is completely different from cv::Mat_ and cv::SparseMat_ iterators. It iterates through the slices (or planes), not the elements, where "slice" is a continuous part of the arrays. - + Here is the example on how the iterator can be used to normalize 3D histogram: - + \code void normalizeColorHist(Mat& hist) { - #if 1 + #if 1 // intialize iterator (the style is different from STL). // after initialization the iterator will contain // the number of slices or planes @@ -3043,7 +3165,7 @@ template class CV_EXPORTS Au #endif } \endcode - + You can iterate through several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same), which is useful for binary and n-ary operations on such matrices. Just pass those matrices to cv::MatNDIterator. @@ -3062,7 +3184,7 @@ class CV_EXPORTS NAryMatIterator //! the separate iterator initialization method void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); - //! proceeds to the next plane of every iterated matrix + //! proceeds to the next plane of every iterated matrix NAryMatIterator& operator ++(); //! proceeds to the next plane of every iterated matrix (postfix increment operator) NAryMatIterator operator ++(int); @@ -3083,7 +3205,7 @@ class CV_EXPORTS NAryMatIterator int iterdepth; size_t idx; }; - + //typedef NAryMatIterator NAryMatNDIterator; typedef void (*ConvertData)(const void* from, void* to, int cn); @@ -3094,7 +3216,7 @@ CV_EXPORTS ConvertData getConvertElem(int fromType, int toType); //! returns the function for converting pixels from one data type to another with the optional scaling CV_EXPORTS ConvertScaleData getConvertScaleElem(int fromType, int toType); - + /////////////////////////// multi-dimensional sparse matrix ////////////////////////// class SparseMatIterator; @@ -3104,14 +3226,14 @@ template class SparseMatConstIterator_; /*! Sparse matrix class. - + The class represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that cv::Mat is able to store. "Sparse" means that only non-zero elements are stored (though, as a result of some operations on a sparse matrix, some of its stored elements can actually become 0. It's user responsibility to detect such elements and delete them using cv::SparseMat::erase(). The non-zero elements are stored in a hash table that grows when it's filled enough, so that the search time remains O(1) in average. Elements can be accessed using the following methods: - +
    1. Query operations: cv::SparseMat::ptr() and the higher-level cv::SparseMat::ref(), cv::SparseMat::value() and cv::SparseMat::find, for example: @@ -3127,7 +3249,7 @@ template class SparseMatConstIterator_; sparse_mat.ref(idx) += 1.f; } \endcode - +
    2. Sparse matrix iterators. Like cv::Mat iterators and unlike cv::Mat iterators, the sparse matrix iterators are STL-style, that is, the iteration is done as following: \code @@ -3144,7 +3266,7 @@ template class SparseMatConstIterator_; printf("(") for(int i = 0; i < dims; i++) printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')'); - printf(": %f\n", *it); + printf(": %f\n", *it); s += *it; } printf("Element sum is %g\n", s); @@ -3152,11 +3274,11 @@ template class SparseMatConstIterator_; If you run this loop, you will notice that elements are enumerated in no any logical order (lexicographical etc.), they come in the same order as they stored in the hash table, i.e. semi-randomly. - + You may collect pointers to the nodes and sort them to get the proper ordering. Note, however, that pointers to the nodes may become invalid when you add more elements to the matrix; this is because of possible buffer reallocation. - +
    3. A combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously, e.g. this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices: @@ -3231,13 +3353,13 @@ class CV_EXPORTS SparseMat \param m the input matrix \param try1d if true and m is a single-column matrix (Nx1), then the sparse matrix will be 1-dimensional. - */ + */ explicit SparseMat(const Mat& m); //! converts old-style sparse matrix to the new-style. All the data is copied SparseMat(const CvSparseMat* m); //! the destructor ~SparseMat(); - + //! assignment operator. This is O(1) operation, i.e. no data is copied SparseMat& operator = (const SparseMat& m); //! equivalent to the corresponding constructor @@ -3245,7 +3367,7 @@ class CV_EXPORTS SparseMat //! creates full copy of the matrix SparseMat clone() const; - + //! copies all the data to the destination matrix. All the previous content of m is erased void copyTo( SparseMat& m ) const; //! converts sparse matrix to dense matrix. @@ -3265,10 +3387,10 @@ class CV_EXPORTS SparseMat //! reallocates sparse matrix. /*! - If the matrix already had the proper size and type, + If the matrix already had the proper size and type, it is simply cleared with clear(), otherwise, the old matrix is released (using release()) and the new one is allocated. - */ + */ void create(int dims, const int* _sizes, int _type); //! sets all the sparse matrix elements to 0, which means clearing the hash table. void clear(); @@ -3283,14 +3405,14 @@ class CV_EXPORTS SparseMat size_t elemSize() const; //! returns elemSize()/channels() size_t elemSize1() const; - + //! returns type of sparse matrix elements int type() const; //! returns the depth of sparse matrix elements int depth() const; //! returns the number of channels int channels() const; - + //! returns the array of sizes, or NULL if the matrix is not allocated const int* size() const; //! returns the size of i-th matrix dimension (or 0) @@ -3299,7 +3421,7 @@ class CV_EXPORTS SparseMat int dims() const; //! returns the number of non-zero elements (=the number of hash table nodes) size_t nzcount() const; - + //! computes the element hash value (1D case) size_t hash(int i0) const; //! computes the element hash value (2D case) @@ -3308,11 +3430,11 @@ class CV_EXPORTS SparseMat size_t hash(int i0, int i1, int i2) const; //! computes the element hash value (nD case) size_t hash(const int* idx) const; - + //@{ /*! specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. - + return pointer to the matrix element.
      • if the element is there (it's non-zero), the pointer to it is returned @@ -3336,27 +3458,27 @@ class CV_EXPORTS SparseMat //@{ /*! return read-write reference to the specified sparse matrix element. - + ref<_Tp>(i0,...[,hashval]) is equivalent to *(_Tp*)ptr(i0,...,true[,hashval]). The methods always return a valid reference. - If the element did not exist, it is created and initialiazed with 0. + If the element did not exist, it is created and initialiazed with 0. */ //! returns reference to the specified element (1D case) - template _Tp& ref(int i0, size_t* hashval=0); + template _Tp& ref(int i0, size_t* hashval=0); //! returns reference to the specified element (2D case) - template _Tp& ref(int i0, int i1, size_t* hashval=0); + template _Tp& ref(int i0, int i1, size_t* hashval=0); //! returns reference to the specified element (3D case) template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! returns reference to the specified element (nD case) template _Tp& ref(const int* idx, size_t* hashval=0); //@} - + //@{ /*! return value of the specified sparse matrix element. - + value<_Tp>(i0,...[,hashval]) is equivalent - + \code { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } \endcode @@ -3372,13 +3494,13 @@ class CV_EXPORTS SparseMat //! returns value of the specified element (nD case) template _Tp value(const int* idx, size_t* hashval=0) const; //@} - + //@{ /*! Return pointer to the specified sparse matrix element if it exists - + find<_Tp>(i0,...[,hashval]) is equivalent to (_const Tp*)ptr(i0,...false[,hashval]). - + If the specified element does not exist, the methods return NULL. */ //! returns pointer to the specified element (1D case) @@ -3400,7 +3522,7 @@ class CV_EXPORTS SparseMat //@{ /*! return the sparse matrix iterator pointing to the first sparse matrix element - */ + */ //! returns the sparse matrix iterator at the matrix beginning SparseMatIterator begin(); //! returns the sparse matrix iterator at the matrix beginning @@ -3412,7 +3534,7 @@ class CV_EXPORTS SparseMat //@} /*! return the sparse matrix iterator pointing to the element following the last sparse matrix element - */ + */ //! returns the sparse matrix iterator at the matrix end SparseMatIterator end(); //! returns the read-only sparse matrix iterator at the matrix end @@ -3426,7 +3548,7 @@ class CV_EXPORTS SparseMat template _Tp& value(Node* n); //! returns the value stored in the sparse martix node template const _Tp& value(const Node* n) const; - + ////////////// some internal-use methods /////////////// Node* node(size_t nidx); const Node* node(size_t nidx) const; @@ -3446,13 +3568,13 @@ CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0); //! computes norm of a sparse matrix CV_EXPORTS double norm( const SparseMat& src, int normType ); -//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values +//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); /*! Read-Only Sparse Matrix Iterator. Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: - + \code SparseMatConstIterator it = m.begin(), it_end = m.end(); double s = 0; @@ -3478,7 +3600,7 @@ class CV_EXPORTS SparseMatConstIterator template const _Tp& value() const; //! returns the current node of the sparse matrix. it.node->idx is the current element index const SparseMat::Node* node() const; - + //! moves iterator to the previous element SparseMatConstIterator& operator --(); //! moves iterator to the previous element @@ -3487,7 +3609,7 @@ class CV_EXPORTS SparseMatConstIterator SparseMatConstIterator& operator ++(); //! moves iterator to the next element SparseMatConstIterator operator ++(int); - + //! moves iterator to the element after the last element void seekEnd(); @@ -3498,7 +3620,7 @@ class CV_EXPORTS SparseMatConstIterator /*! Read-write Sparse Matrix Iterator - + The class is similar to cv::SparseMatConstIterator, but can be used for in-place modification of the matrix elements. */ @@ -3520,7 +3642,7 @@ class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator template _Tp& value() const; //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) SparseMat::Node* node() const; - + //! moves iterator to the next element SparseMatIterator& operator ++(); //! moves iterator to the next element @@ -3529,9 +3651,9 @@ class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator /*! The Template Sparse Matrix class derived from cv::SparseMat - + The class provides slightly more convenient operations for accessing elements. - + \code SparseMat m; ... @@ -3539,7 +3661,7 @@ class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator m_.ref(1)++; // equivalent to m.ref(1)++; m_.ref(2) += m_(3); // equivalent to m.ref(2) += m.value(3); \endcode -*/ +*/ template class CV_EXPORTS SparseMat_ : public SparseMat { public: @@ -3560,7 +3682,7 @@ template class CV_EXPORTS SparseMat_ : public SparseMat SparseMat_(const CvSparseMat* m); //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted SparseMat_& operator = (const SparseMat& m); - //! the assignment operator. This is O(1) operation - no data is copied + //! the assignment operator. This is O(1) operation - no data is copied SparseMat_& operator = (const SparseMat_& m); //! converts dense matrix to the sparse form SparseMat_& operator = (const Mat& m); @@ -3578,7 +3700,7 @@ template class CV_EXPORTS SparseMat_ : public SparseMat int depth() const; //! returns the number of channels in each matrix element int channels() const; - + //! equivalent to SparseMat::ref<_Tp>(i0, hashval) _Tp& ref(int i0, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) @@ -3587,7 +3709,7 @@ template class CV_EXPORTS SparseMat_ : public SparseMat _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(idx, hashval) _Tp& ref(const int* idx, size_t* hashval=0); - + //! equivalent to SparseMat::value<_Tp>(i0, hashval) _Tp operator()(int i0, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) @@ -3610,7 +3732,7 @@ template class CV_EXPORTS SparseMat_ : public SparseMat /*! Template Read-Only Sparse Matrix Iterator Class. - + This is the derived from SparseMatConstIterator class that introduces more convenient operator *() for accessing the current element. */ @@ -3618,7 +3740,7 @@ template class CV_EXPORTS SparseMatConstIterator_ : public SparseM { public: typedef std::forward_iterator_tag iterator_category; - + //! the default constructor SparseMatConstIterator_(); //! the full constructor setting the iterator to the first sparse matrix element @@ -3630,7 +3752,7 @@ template class CV_EXPORTS SparseMatConstIterator_ : public SparseM SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); //! the element access operator const _Tp& operator *() const; - + //! moves iterator to the next element SparseMatConstIterator_& operator ++(); //! moves iterator to the next element @@ -3639,7 +3761,7 @@ template class CV_EXPORTS SparseMatConstIterator_ : public SparseM /*! Template Read-Write Sparse Matrix Iterator Class. - + This is the derived from cv::SparseMatConstIterator_ class that introduces more convenient operator *() for accessing the current element. */ @@ -3647,7 +3769,7 @@ template class CV_EXPORTS SparseMatIterator_ : public SparseMatCon { public: typedef std::forward_iterator_tag iterator_category; - + //! the default constructor SparseMatIterator_(); //! the full constructor setting the iterator to the first sparse matrix element @@ -3655,11 +3777,11 @@ template class CV_EXPORTS SparseMatIterator_ : public SparseMatCon //! the copy constructor SparseMatIterator_(const SparseMatIterator_& it); - //! the assignment operator + //! the assignment operator SparseMatIterator_& operator = (const SparseMatIterator_& it); //! returns the reference to the current element _Tp& operator *() const; - + //! moves the iterator to the next element SparseMatIterator_& operator ++(); //! moves the iterator to the next element @@ -3670,19 +3792,19 @@ template class CV_EXPORTS SparseMatIterator_ : public SparseMatCon /*! Fast Nearest Neighbor Search Class. - + The class implements D. Lowe BBF (Best-Bin-First) algorithm for the last approximate (or accurate) nearest neighbor search in multi-dimensional spaces. - + First, a set of vectors is passed to KDTree::KDTree() constructor or KDTree::build() method, where it is reordered. - + Then arbitrary vectors can be passed to KDTree::findNearest() methods, which find the K nearest neighbors among the vectors from the initial set. The user can balance between the speed and accuracy of the search by varying Emax parameter, which is the number of leaves that the algorithm checks. The larger parameter values yield more accurate results at the expense of lower processing speed. - + \code KDTree T(points, false); const int K = 3, Emax = INT_MAX; @@ -3691,13 +3813,13 @@ template class CV_EXPORTS SparseMatIterator_ : public SparseMatCon T.findNearest(query_vec, K, Emax, idx, 0, dist); CV_Assert(dist[0] <= dist[1] && dist[1] <= dist[2]); \endcode -*/ +*/ class CV_EXPORTS_W KDTree { public: /*! The node of the search tree. - */ + */ struct Node { Node() : idx(-1), left(-1), right(-1), boundary(0.f) {} @@ -3729,7 +3851,7 @@ class CV_EXPORTS_W KDTree OutputArray neighbors=noArray(), OutputArray dist=noArray(), OutputArray labels=noArray()) const; - //! finds all the points from the initial set that belong to the specified box + //! finds all the points from the initial set that belong to the specified box CV_WRAP void findOrthoRange(InputArray minBounds, InputArray maxBounds, OutputArray neighborsIdx, @@ -3756,34 +3878,34 @@ class CV_EXPORTS FileNode; /*! XML/YAML File Storage Class. - + The class describes an object associated with XML or YAML file. It can be used to store data to such a file or read and decode the data. - + The storage is organized as a tree of nested sequences (or lists) and mappings. Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator. Mapping is analogue of std::map or C structure, which elements are accessed by names. The most top level structure is a mapping. - Leaves of the file storage tree are integers, floating-point numbers and text strings. - + Leaves of the file storage tree are integers, floating-point numbers and text strings. + For example, the following code: - + \code // open file storage for writing. Type of the file is determined from the extension FileStorage fs("test.yml", FileStorage::WRITE); fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH"; fs << "test_mat" << Mat::eye(3,3,CV_32F); - + fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" << "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]"; fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:"; - + const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1}; fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0]))); - + fs << "]" << "}"; \endcode - + will produce the following file: \verbatim @@ -3810,9 +3932,9 @@ class CV_EXPORTS FileNode; height: 200 lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ] \endverbatim - + and to read the file above, the following code can be used: - + \code // open file storage for reading. // Type of the file is determined from the content, not the extension @@ -3820,10 +3942,10 @@ class CV_EXPORTS FileNode; int test_int = (int)fs["test_int"]; double test_real = (double)fs["test_real"]; string test_string = (string)fs["test_string"]; - + Mat M; fs["test_mat"] >> M; - + FileNode tl = fs["test_list"]; CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6); double tl0 = (double)tl[0]; @@ -3832,18 +3954,18 @@ class CV_EXPORTS FileNode; int tl3 = (int)tl[3]; string tl4 = (string)tl[4]; CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3); - + int month = (int)tl[5]["month"]; int day = (int)tl[5]["day"]; int year = (int)tl[5]["year"]; - + FileNode tm = fs["test_map"]; - + int x = (int)tm["x"]; int y = (int)tm["y"]; int width = (int)tm["width"]; int height = (int)tm["height"]; - + int lbp_val = 0; FileNodeIterator it = tm["lbp"].begin(); @@ -3859,11 +3981,16 @@ class CV_EXPORTS_W FileStorage { READ=0, //! read mode WRITE=1, //! write mode - APPEND=2 //! append mode + APPEND=2, //! append mode + MEMORY=4, + FORMAT_MASK=(7<<3), + FORMAT_AUTO=0, + FORMAT_XML=(1<<3), + FORMAT_YAML=(2<<3) }; enum { - UNDEFINED=0, + UNDEFINED=0, VALUE_EXPECTED=1, NAME_EXPECTED=2, INSIDE_MAP=4 @@ -3871,8 +3998,8 @@ class CV_EXPORTS_W FileStorage //! the default constructor CV_WRAP FileStorage(); //! the full constructor that opens file storage for reading or writing - CV_WRAP FileStorage(const string& filename, int flags, const string& encoding=string()); - //! the constructor that takes pointer to the C FileStorage structure + CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string()); + //! the constructor that takes pointer to the C FileStorage structure FileStorage(CvFileStorage* fs); //! the destructor. calls release() virtual ~FileStorage(); @@ -3883,6 +4010,8 @@ class CV_EXPORTS_W FileStorage CV_WRAP virtual bool isOpened() const; //! closes the file and releases all the memory buffers CV_WRAP virtual void release(); + //! closes the file, releases all the memory buffers and returns the text string + CV_WRAP string releaseAndGetString(); //! returns the first element of the top-level mapping CV_WRAP FileNode getFirstTopLevelNode() const; @@ -3915,11 +4044,11 @@ class CV_EXPORTS FileNodeIterator; /*! File Storage Node class - + The node is used to store each and every element of the file storage opened for reading - from the primitive objects, such as numbers and text strings, to the complex nodes: sequences, mappings and the registered objects. - + Note that file nodes are only used for navigating file storages opened for reading. When a file storage is opened for writing, no data is stored in memory after it is written. */ @@ -3935,7 +4064,7 @@ class CV_EXPORTS_W_SIMPLE FileNode FLOAT=REAL, //!< synonym or REAL STR=3, //!< text string in UTF-8 encoding STRING=STR, //!< synonym for STR - REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others + REF=4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others SEQ=5, //!< sequence MAP=6, //!< mapping TYPE_MASK=7, @@ -3959,9 +4088,9 @@ class CV_EXPORTS_W_SIMPLE FileNode //! returns type of the node CV_WRAP int type() const; - //! returns true if the node is empty + //! returns true if the node is empty CV_WRAP bool empty() const; - //! returns true if the node is a "none" object + //! returns true if the node is a "none" object CV_WRAP bool isNone() const; //! returns true if the node is a sequence CV_WRAP bool isSeq() const; @@ -3987,7 +4116,7 @@ class CV_EXPORTS_W_SIMPLE FileNode operator double() const; //! returns the node content as text string operator string() const; - + //! returns pointer to the underlying file node CvFileNode* operator *(); //! returns pointer to the underlying file node @@ -4011,7 +4140,7 @@ class CV_EXPORTS_W_SIMPLE FileNode /*! File Node Iterator - + The class is used for iterating sequences (usually) and mappings. */ class CV_EXPORTS FileNodeIterator @@ -4037,14 +4166,14 @@ class CV_EXPORTS FileNodeIterator //! moves iterator to the previous node FileNodeIterator operator -- (int); //! moves iterator forward by the specified offset (possibly negative) - FileNodeIterator& operator += (int); + FileNodeIterator& operator += (int ofs); //! moves iterator backward by the specified offset (possibly negative) - FileNodeIterator& operator -= (int); + FileNodeIterator& operator -= (int ofs); //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format FileNodeIterator& readRaw( const string& fmt, uchar* vec, size_t maxCount=(size_t)INT_MAX ); - + const CvFileStorage* fs; const CvFileNode* container; CvSeqReader reader; @@ -4062,7 +4191,7 @@ typedef Ptr MemStorage; The class provides more convenient access to sequence elements, STL-style operations and iterators. - + \note The class is targeted for simple data types, i.e. no constructors or destructors are called for the sequence elements. @@ -4072,7 +4201,7 @@ template class CV_EXPORTS Seq public: typedef SeqIterator<_Tp> iterator; typedef SeqIterator<_Tp> const_iterator; - + //! the default constructor Seq(); //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. @@ -4115,7 +4244,7 @@ template class CV_EXPORTS Seq void remove(int idx); //! removes the specified subsequence void remove(const Range& r); - + //! returns reference to the first sequence element _Tp& front(); //! returns read-only reference to the first sequence element @@ -4142,11 +4271,11 @@ template class CV_EXPORTS Seq void copyTo(vector<_Tp>& vec, const Range& range=Range::all()) const; //! returns the vector containing all the sequence elements operator vector<_Tp>() const; - + CvSeq* seq; }; - + /*! STL-style Sequence Iterator inherited from the CvSeqReader structure */ @@ -4185,53 +4314,271 @@ template class CV_EXPORTS SeqIterator : public CvSeqReader }; -#if 0 -class CV_EXPORTS AlgorithmImpl; +class CV_EXPORTS Algorithm; +class CV_EXPORTS AlgorithmInfo; +struct CV_EXPORTS AlgorithmInfoData; + +template struct ParamType {}; /*! Base class for high-level OpenCV algorithms -*/ -class CV_EXPORTS Algorithm +*/ +class CV_EXPORTS_W Algorithm { public: + Algorithm(); virtual ~Algorithm(); - virtual string name() const; - - template _Tp get(int paramId) const; - template bool set(int paramId, const _Tp& value); - string paramName(int paramId) const; - string paramHelp(int paramId) const; - int paramType(int paramId) const; - int findParam(const string& name) const; - template _Tp paramDefaultValue(int paramId) const; - template bool paramRange(int paramId, _Tp& minVal, _Tp& maxVal) const; - - virtual void getParams(vector& ids) const; - virtual void write(vector& buf) const; - virtual bool read(const vector& buf); - + string name() const; + + template typename ParamType<_Tp>::member_type get(const string& name) const; + template typename ParamType<_Tp>::member_type get(const char* name) const; + + CV_WRAP int getInt(const string& name) const; + CV_WRAP double getDouble(const string& name) const; + CV_WRAP bool getBool(const string& name) const; + CV_WRAP string getString(const string& name) const; + CV_WRAP Mat getMat(const string& name) const; + CV_WRAP vector getMatVector(const string& name) const; + CV_WRAP Ptr getAlgorithm(const string& name) const; + + void set(const string& name, int value); + void set(const string& name, double value); + void set(const string& name, bool value); + void set(const string& name, const string& value); + void set(const string& name, const Mat& value); + void set(const string& name, const vector& value); + void set(const string& name, const Ptr& value); + template void set(const string& name, const Ptr<_Tp>& value); + + CV_WRAP void setInt(const string& name, int value); + CV_WRAP void setDouble(const string& name, double value); + CV_WRAP void setBool(const string& name, bool value); + CV_WRAP void setString(const string& name, const string& value); + CV_WRAP void setMat(const string& name, const Mat& value); + CV_WRAP void setMatVector(const string& name, const vector& value); + CV_WRAP void setAlgorithm(const string& name, const Ptr& value); + template void setAlgorithm(const string& name, const Ptr<_Tp>& value); + + void set(const char* name, int value); + void set(const char* name, double value); + void set(const char* name, bool value); + void set(const char* name, const string& value); + void set(const char* name, const Mat& value); + void set(const char* name, const vector& value); + void set(const char* name, const Ptr& value); + template void set(const char* name, const Ptr<_Tp>& value); + + void setInt(const char* name, int value); + void setDouble(const char* name, double value); + void setBool(const char* name, bool value); + void setString(const char* name, const string& value); + void setMat(const char* name, const Mat& value); + void setMatVector(const char* name, const vector& value); + void setAlgorithm(const char* name, const Ptr& value); + template void setAlgorithm(const char* name, const Ptr<_Tp>& value); + + CV_WRAP string paramHelp(const string& name) const; + int paramType(const char* name) const; + CV_WRAP int paramType(const string& name) const; + CV_WRAP void getParams(CV_OUT vector& names) const; + + + virtual void write(FileStorage& fs) const; + virtual void read(const FileNode& fn); + typedef Algorithm* (*Constructor)(void); - static void add(const string& name, Constructor create); - static void getList(vector& algorithms); - static Ptr create(const string& name); - + typedef int (Algorithm::*Getter)() const; + typedef void (Algorithm::*Setter)(int); + + CV_WRAP static void getList(CV_OUT vector& algorithms); + CV_WRAP static Ptr _create(const string& name); + template static Ptr<_Tp> create(const string& name); + + virtual AlgorithmInfo* info() const /* TODO: make it = 0;*/ { return 0; } +}; + + +class CV_EXPORTS AlgorithmInfo +{ +public: + friend class Algorithm; + AlgorithmInfo(const string& name, Algorithm::Constructor create); + ~AlgorithmInfo(); + void get(const Algorithm* algo, const char* name, int argType, void* value) const; + void addParam_(Algorithm& algo, const char* name, int argType, + void* value, bool readOnly, + Algorithm::Getter getter, Algorithm::Setter setter, + const string& help=string()); + string paramHelp(const char* name) const; + int paramType(const char* name) const; + void getParams(vector& names) const; + + void write(const Algorithm* algo, FileStorage& fs) const; + void read(Algorithm* algo, const FileNode& fn) const; + string name() const; + + void addParam(Algorithm& algo, const char* name, + int& value, bool readOnly=false, + int (Algorithm::*getter)()=0, + void (Algorithm::*setter)(int)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + short& value, bool readOnly=false, + int (Algorithm::*getter)()=0, + void (Algorithm::*setter)(int)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + bool& value, bool readOnly=false, + int (Algorithm::*getter)()=0, + void (Algorithm::*setter)(int)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + double& value, bool readOnly=false, + double (Algorithm::*getter)()=0, + void (Algorithm::*setter)(double)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + string& value, bool readOnly=false, + string (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const string&)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + Mat& value, bool readOnly=false, + Mat (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const Mat&)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + vector& value, bool readOnly=false, + vector (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const vector&)=0, + const string& help=string()); + void addParam(Algorithm& algo, const char* name, + Ptr& value, bool readOnly=false, + Ptr (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const Ptr&)=0, + const string& help=string()); + template void addParam(Algorithm& algo, const char* name, + Ptr<_Tp>& value, bool readOnly=false, + Ptr<_Tp> (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const Ptr<_Tp>&)=0, + const string& help=string()); + template void addParam(Algorithm& algo, const char* name, + Ptr<_Tp>& value, bool readOnly=false, + Ptr<_Tp> (Algorithm::*getter)()=0, + void (Algorithm::*setter)(const Ptr<_Tp>&)=0, + const string& help=string()); protected: - template void addParam(int propId, _Tp& value, bool readOnly, const string& name, - const string& help=string(), const _Tp& defaultValue=_Tp(), - _Tp (Algorithm::*getter)()=0, bool (Algorithm::*setter)(const _Tp&)=0); - template void setParamRange(int propId, const _Tp& minVal, const _Tp& maxVal); - - bool set_(int paramId, int argType, const void* value); - void get_(int paramId, int argType, void* value); - void paramDefaultValue_(int paramId, int argType, void* value); - void paramRange_(int paramId, int argType, void* minval, void* maxval); - void addParam_(int propId, int argType, void* value, bool readOnly, const string& name, - const string& help, const void* defaultValue, void* getter, void* setter); - void setParamRange_(int propId, int argType, const void* minVal, const void* maxVal); - - Ptr impl; + AlgorithmInfoData* data; + void set(Algorithm* algo, const char* name, int argType, + const void* value, bool force=false) const; }; -#endif + + +struct CV_EXPORTS Param +{ + enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, UNSIGNED_INT=8, UINT64=9, SHORT=10 }; + + Param(); + Param(int _type, bool _readonly, int _offset, + Algorithm::Getter _getter=0, + Algorithm::Setter _setter=0, + const string& _help=string()); + int type; + int offset; + bool readonly; + Algorithm::Getter getter; + Algorithm::Setter setter; + string help; +}; + +template<> struct ParamType +{ + typedef bool const_param_type; + typedef bool member_type; + + enum { type = Param::BOOLEAN }; +}; + +template<> struct ParamType +{ + typedef int const_param_type; + typedef int member_type; + + enum { type = Param::INT }; +}; + +template<> struct ParamType +{ + typedef int const_param_type; + typedef int member_type; + + enum { type = Param::SHORT }; +}; + +template<> struct ParamType +{ + typedef double const_param_type; + typedef double member_type; + + enum { type = Param::REAL }; +}; + +template<> struct ParamType +{ + typedef const string& const_param_type; + typedef string member_type; + + enum { type = Param::STRING }; +}; + +template<> struct ParamType +{ + typedef const Mat& const_param_type; + typedef Mat member_type; + + enum { type = Param::MAT }; +}; + +template<> struct ParamType > +{ + typedef const vector& const_param_type; + typedef vector member_type; + + enum { type = Param::MAT_VECTOR }; +}; + +template<> struct ParamType +{ + typedef const Ptr& const_param_type; + typedef Ptr member_type; + + enum { type = Param::ALGORITHM }; +}; + +template<> struct ParamType +{ + typedef float const_param_type; + typedef float member_type; + + enum { type = Param::FLOAT }; +}; + +template<> struct ParamType +{ + typedef unsigned const_param_type; + typedef unsigned member_type; + + enum { type = Param::UNSIGNED_INT }; +}; + +template<> struct ParamType +{ + typedef uint64 const_param_type; + typedef uint64 member_type; + + enum { type = Param::UINT64 }; +}; + /*! "\nThe CommandLineParser class is designed for command line arguments parsing\n" @@ -4340,6 +4687,47 @@ float CommandLineParser::analyzeValue(const std::string& str, bool space_ template<> CV_EXPORTS double CommandLineParser::analyzeValue(const std::string& str, bool space_delete); + +/////////////////////////////// Parallel Primitives ////////////////////////////////// + +// a base body class +class CV_EXPORTS ParallelLoopBody +{ +public: + virtual ~ParallelLoopBody(); + virtual void operator() (const Range& range) const = 0; +}; + +CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); + +/////////////////////////// Synchronization Primitives /////////////////////////////// + +class CV_EXPORTS Mutex +{ +public: + Mutex(); + ~Mutex(); + Mutex(const Mutex& m); + Mutex& operator = (const Mutex& m); + + void lock(); + bool trylock(); + void unlock(); + + struct Impl; +protected: + Impl* impl; +}; + +class CV_EXPORTS AutoLock +{ +public: + AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); } + ~AutoLock() { mutex->unlock(); } +protected: + Mutex* mutex; +}; + } #endif // __cplusplus diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core_c.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core_c.h old mode 100755 new mode 100644 similarity index 98% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core_c.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core_c.h index 05d8c72..df763ab --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/core_c.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/core_c.h @@ -666,7 +666,7 @@ CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); /* Finds all real and complex roots of a polynomial equation */ CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, - int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); + int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); /****************************************************************************************\ * Matrix operations * @@ -940,11 +940,11 @@ CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); /* Allocates string in memory storage */ CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, - int len CV_DEFAULT(-1) ); + int len CV_DEFAULT(-1) ); /* Creates new empty sequence that will reside in the specified storage */ -CVAPI(CvSeq*) cvCreateSeq( int seq_flags, int header_size, - int elem_size, CvMemStorage* storage ); +CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, + size_t elem_size, CvMemStorage* storage ); /* Changes default size (granularity) of sequence blocks. The default size is ~1Kbyte */ @@ -1127,9 +1127,9 @@ CVAPI(void) cvSetRemove( CvSet* set_header, int index ); /* Returns a set element by index. If the element doesn't belong to the set, NULL is returned */ -CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int index ) +CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) { - CvSetElem* elem = (CvSetElem*)cvGetSeqElem( (CvSeq*)set_header, index ); + CvSetElem* elem = (CvSetElem*)cvGetSeqElem( (CvSeq*)set_header, idx ); return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; } @@ -1283,8 +1283,8 @@ CVAPI(void) cvRectangleR( CvArr* img, CvRect r, CvScalar color, int thickness CV_DEFAULT(1), int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - - + + /* Draws a circle with specified center and radius. Thickness works in the same way as with cvRectangle */ CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, @@ -1374,17 +1374,17 @@ CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, /* Font structure */ typedef struct CvFont { - const char* nameFont; //Qt:nameFont - CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red\_component[, alpha_component]) - int font_face; //Qt: bool italic /* =CV_FONT_* */ - const int* ascii; /* font data and metrics */ + const char* nameFont; //Qt:nameFont + CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red\_component[, alpha_component]) + int font_face; //Qt: bool italic /* =CV_FONT_* */ + const int* ascii; /* font data and metrics */ const int* greek; const int* cyrillic; float hscale, vscale; - float shear; /* slope coefficient: 0 - normal, >0 - italic */ - int thickness; //Qt: weight /* letters thickness */ - float dx; /* horizontal interval between letters */ - int line_type; //Qt: PointSize + float shear; /* slope coefficient: 0 - normal, >0 - italic */ + int thickness; //Qt: weight /* letters thickness */ + float dx; /* horizontal interval between letters */ + int line_type; //Qt: PointSize } CvFont; @@ -1696,7 +1696,7 @@ CVAPI(double) cvGetTickFrequency( void ); /*********************************** CPU capabilities ***********************************/ -#define CV_CPU_NONE 0 +#define CV_CPU_NONE 0 #define CV_CPU_MMX 1 #define CV_CPU_SSE 2 #define CV_CPU_SSE2 3 @@ -1718,9 +1718,9 @@ CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); /* get index of the thread being executed */ CVAPI(int) cvGetThreadNum( void ); - + /********************************** Error Handling **************************************/ - + /* Get current OpenCV error status */ CVAPI(int) cvGetErrStatus( void ); @@ -1774,37 +1774,37 @@ CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_ms const char* file_name, int line, void* userdata ); CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - + const char* file_name, int line, void* userdata ); + #define OPENCV_ERROR(status,func,context) \ cvError((status),(func),(context),__FILE__,__LINE__) - + #define OPENCV_ERRCHK(func,context) \ {if (cvGetErrStatus() >= 0) \ {OPENCV_ERROR(CV_StsBackTrace,(func),(context));}} - + #define OPENCV_ASSERT(expr,func,context) \ {if (! (expr)) \ {OPENCV_ERROR(CV_StsInternal,(func),(context));}} - + #define OPENCV_RSTERR() (cvSetErrStatus(CV_StsOk)) - + #define OPENCV_CALL( Func ) \ { \ Func; \ -} - - +} + + /* CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ #ifdef CV_NO_FUNC_NAMES #define CV_FUNCNAME( Name ) #define cvFuncName "" -#else +#else #define CV_FUNCNAME( Name ) \ static char cvFuncName[] = Name #endif - - + + /* CV_ERROR macro unconditionally raises error with passed code and message. After raising error, control will be transferred to the exit label. @@ -1814,11 +1814,11 @@ static char cvFuncName[] = Name cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ __CV_EXIT__; \ } - + /* Simplified form of CV_ERROR */ #define CV_ERROR_FROM_CODE( code ) \ CV_ERROR( code, "" ) - + /* CV_CHECK macro checks error status after CV (or IPL) function call. If error detected, control will be transferred to the exit @@ -1829,8 +1829,8 @@ static char cvFuncName[] = Name if( cvGetErrStatus() < 0 ) \ CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ } - - + + /* CV_CALL macro calls CV (or IPL) function, checks error status and signals a error if the function failed. Useful in "parent node" @@ -1841,19 +1841,19 @@ static char cvFuncName[] = Name Func; \ CV_CHECK(); \ } - - + + /* Runtime assertion macro */ #define CV_ASSERT( Condition ) \ { \ if( !(Condition) ) \ CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ } - + #define __CV_BEGIN__ { #define __CV_END__ goto exit; exit: ; } -#define __CV_EXIT__ goto exit - +#define __CV_EXIT__ goto exit + #ifdef __cplusplus } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/devmem2d.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/cuda_devptrs.hpp old mode 100755 new mode 100644 similarity index 61% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/devmem2d.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/cuda_devptrs.hpp index e454f00..373ff29 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/gpu/devmem2d.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/cuda_devptrs.hpp @@ -1,161 +1,185 @@ -/*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. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. -// -// * The name of the copyright holders 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 __OPENCV_GPU_DevMem2D_HPP__ -#define __OPENCV_GPU_DevMem2D_HPP__ - - -namespace cv -{ - namespace gpu - { - // Simple lightweight structures that encapsulates information about an image on device. - // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile - -#if defined(__CUDACC__) - #define __CV_GPU_HOST_DEVICE__ __host__ __device__ __forceinline__ -#else - #define __CV_GPU_HOST_DEVICE__ -#endif - - template struct StaticAssert; - template <> struct StaticAssert {static __CV_GPU_HOST_DEVICE__ void check(){}}; - - template struct DevPtr - { - typedef T elem_type; - typedef int index_type; - - enum { elem_size = sizeof(elem_type) }; - - T* data; - - __CV_GPU_HOST_DEVICE__ DevPtr() : data(0) {} - __CV_GPU_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} - - __CV_GPU_HOST_DEVICE__ size_t elemSize() const { return elem_size; } - __CV_GPU_HOST_DEVICE__ operator T*() { return data; } - __CV_GPU_HOST_DEVICE__ operator const T*() const { return data; } - }; - - template struct PtrSz : public DevPtr - { - __CV_GPU_HOST_DEVICE__ PtrSz() : size(0) {} - __CV_GPU_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} - - size_t size; - }; - - template struct PtrStep : public DevPtr - { - __CV_GPU_HOST_DEVICE__ PtrStep() : step(0) {} - __CV_GPU_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} - - /** \brief stride between two consecutive rows in bytes. Step is stored always and everywhere in bytes!!! */ - size_t step; - - __CV_GPU_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)DevPtr::data + y * step); } - __CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)DevPtr::data + y * step); } - - __CV_GPU_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } - __CV_GPU_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } - }; - - template struct PtrStepSz : public PtrStep - { - __CV_GPU_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} - __CV_GPU_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) - : PtrStep(data_, step_), cols(cols_), rows(rows_) {} - - int cols; - int rows; - }; - - template struct DevMem2D_ : public PtrStepSz - { - DevMem2D_() {} - DevMem2D_(int rows_, int cols_, T *data_, size_t step_) : PtrStepSz(rows_, cols_, data_, step_) {} - - template - explicit DevMem2D_(const DevMem2D_& d) : PtrStepSz(d.rows, d.cols, (T*)d.data, d.step) {} - }; - - template struct PtrElemStep_ : public PtrStep - { - PtrElemStep_(const DevMem2D_& mem) : PtrStep(mem.data, mem.step) - { - StaticAssert<256 % sizeof(T) == 0>::check(); - - PtrStep::step /= PtrStep::elem_size; - } - __CV_GPU_HOST_DEVICE__ T* ptr(int y = 0) { return PtrStep::data + y * PtrStep::step; } - __CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const { return PtrStep::data + y * PtrStep::step; } - - __CV_GPU_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } - __CV_GPU_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } - }; - - template struct PtrStep_ : public PtrStep - { - PtrStep_() {} - PtrStep_(const DevMem2D_& mem) : PtrStep(mem.data, mem.step) {} - }; - -#undef __CV_GPU_HOST_DEVICE__ - - - typedef DevMem2D_ DevMem2Db; - typedef DevMem2Db DevMem2D; - typedef DevMem2D_ DevMem2Df; - typedef DevMem2D_ DevMem2Di; - - typedef PtrStep PtrStepb; - typedef PtrStep PtrStepf; - typedef PtrStep PtrStepi; - - typedef PtrElemStep_ PtrElemStep; - typedef PtrElemStep_ PtrElemStepf; - typedef PtrElemStep_ PtrElemStepi; - } -} - -#endif /* __OPENCV_GPU_DevMem2D_HPP__ */ +/*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. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. +// +// * The name of the copyright holders 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 __OPENCV_CORE_DEVPTRS_HPP__ +#define __OPENCV_CORE_DEVPTRS_HPP__ + +#ifdef __cplusplus + +#ifdef __CUDACC__ + #define __CV_GPU_HOST_DEVICE__ __host__ __device__ __forceinline__ +#else + #define __CV_GPU_HOST_DEVICE__ +#endif + +namespace cv +{ + namespace gpu + { + // Simple lightweight structures that encapsulates information about an image on device. + // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile + + template struct StaticAssert; + template <> struct StaticAssert {static __CV_GPU_HOST_DEVICE__ void check(){}}; + + template struct DevPtr + { + typedef T elem_type; + typedef int index_type; + + enum { elem_size = sizeof(elem_type) }; + + T* data; + + __CV_GPU_HOST_DEVICE__ DevPtr() : data(0) {} + __CV_GPU_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} + + __CV_GPU_HOST_DEVICE__ size_t elemSize() const { return elem_size; } + __CV_GPU_HOST_DEVICE__ operator T*() { return data; } + __CV_GPU_HOST_DEVICE__ operator const T*() const { return data; } + }; + + template struct PtrSz : public DevPtr + { + __CV_GPU_HOST_DEVICE__ PtrSz() : size(0) {} + __CV_GPU_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} + + size_t size; + }; + + template struct PtrStep : public DevPtr + { + __CV_GPU_HOST_DEVICE__ PtrStep() : step(0) {} + __CV_GPU_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} + + /** \brief stride between two consecutive rows in bytes. Step is stored always and everywhere in bytes!!! */ + size_t step; + + __CV_GPU_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)DevPtr::data + y * step); } + __CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)DevPtr::data + y * step); } + + __CV_GPU_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } + __CV_GPU_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } + }; + + template struct PtrStepSz : public PtrStep + { + __CV_GPU_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} + __CV_GPU_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) + : PtrStep(data_, step_), cols(cols_), rows(rows_) {} + + template + explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} + + int cols; + int rows; + }; + + typedef PtrStepSz PtrStepSzb; + typedef PtrStepSz PtrStepSzf; + typedef PtrStepSz PtrStepSzi; + + typedef PtrStep PtrStepb; + typedef PtrStep PtrStepf; + typedef PtrStep PtrStepi; + + +#if defined __GNUC__ + #define __CV_GPU_DEPR_BEFORE__ + #define __CV_GPU_DEPR_AFTER__ __attribute__ ((deprecated)) +#elif defined(__MSVC__) //|| defined(__CUDACC__) + #pragma deprecated(DevMem2D_) + #define __CV_GPU_DEPR_BEFORE__ __declspec(deprecated) + #define __CV_GPU_DEPR_AFTER__ +#else + #define __CV_GPU_DEPR_BEFORE__ + #define __CV_GPU_DEPR_AFTER__ +#endif + + template struct __CV_GPU_DEPR_BEFORE__ DevMem2D_ : public PtrStepSz + { + DevMem2D_() {} + DevMem2D_(int rows_, int cols_, T* data_, size_t step_) : PtrStepSz(rows_, cols_, data_, step_) {} + + template + explicit __CV_GPU_DEPR_BEFORE__ DevMem2D_(const DevMem2D_& d) : PtrStepSz(d.rows, d.cols, (T*)d.data, d.step) {} + } __CV_GPU_DEPR_AFTER__ ; + + typedef DevMem2D_ DevMem2Db; + typedef DevMem2Db DevMem2D; + typedef DevMem2D_ DevMem2Df; + typedef DevMem2D_ DevMem2Di; + + template struct PtrElemStep_ : public PtrStep + { + PtrElemStep_(const DevMem2D_& mem) : PtrStep(mem.data, mem.step) + { + StaticAssert<256 % sizeof(T) == 0>::check(); + + PtrStep::step /= PtrStep::elem_size; + } + __CV_GPU_HOST_DEVICE__ T* ptr(int y = 0) { return PtrStep::data + y * PtrStep::step; } + __CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const { return PtrStep::data + y * PtrStep::step; } + + __CV_GPU_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } + __CV_GPU_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } + }; + + template struct PtrStep_ : public PtrStep + { + PtrStep_() {} + PtrStep_(const DevMem2D_& mem) : PtrStep(mem.data, mem.step) {} + }; + + typedef PtrElemStep_ PtrElemStep; + typedef PtrElemStep_ PtrElemStepf; + typedef PtrElemStep_ PtrElemStepi; + +//#undef __CV_GPU_DEPR_BEFORE__ +//#undef __CV_GPU_DEPR_AFTER__ + + } +} + +#endif // __cplusplus + +#endif /* __OPENCV_CORE_DEVPTRS_HPP__ */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxeigen.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/devmem2d.hpp old mode 100755 new mode 100644 similarity index 90% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxeigen.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/devmem2d.hpp index c503f71..fc2d2f2 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cxeigen.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/devmem2d.hpp @@ -7,7 +7,7 @@ // copy or use the software. // // -// License Agreement +// License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. @@ -22,7 +22,7 @@ // // * 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. +// and/or other GpuMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. @@ -40,10 +40,4 @@ // //M*/ -#ifndef __OPENCV_OLD_EIGEN_HPP__ -#define __OPENCV_OLD_EIGEN_HPP__ - -#include "opencv2/core/eigen.hpp" - -#endif - +#include "opencv2/core/cuda_devptrs.hpp" diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/eigen.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/eigen.hpp old mode 100755 new mode 100644 similarity index 67% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/eigen.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/eigen.hpp index 505652f..751734e --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/eigen.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/eigen.hpp @@ -45,7 +45,14 @@ #ifdef __cplusplus -#include "cxcore.h" +#include "opencv2/core/core_c.h" +#include "opencv2/core/core.hpp" + +#if defined _MSC_VER && _MSC_VER >= 1200 +#pragma warning( disable: 4714 ) //__forceinline is not inlined +#pragma warning( disable: 4127 ) //conditional expression is constant +#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data +#endif namespace cv { @@ -66,7 +73,7 @@ void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCo _src.copyTo(dst); } } - + template void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) @@ -96,6 +103,27 @@ void cv2eigen( const Mat& src, } } +// Matx case +template +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) +{ + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + Mat _dst(_cols, _rows, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + transpose(src, _dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } + else + { + Mat _dst(_rows, _cols, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } +} + template void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) @@ -125,14 +153,35 @@ void cv2eigen( const Mat& src, } } - +// Matx case +template +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) +{ + dst.resize(_rows, _cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + Mat _dst(_cols, _rows, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + transpose(src, _dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } + else + { + Mat _dst(_rows, _cols, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } +} + template void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { CV_Assert(src.cols == 1); dst.resize(src.rows); - + if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(src.cols, src.rows, DataType<_Tp>::type, @@ -152,6 +201,29 @@ void cv2eigen( const Mat& src, } } +// Matx case +template +void cv2eigen( const Matx<_Tp, _rows, 1>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) +{ + dst.resize(_rows); + + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + Mat _dst(1, _rows, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + transpose(src, _dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } + else + { + Mat _dst(_rows, 1, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + src.copyTo(_dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } +} + template void cv2eigen( const Mat& src, @@ -176,8 +248,31 @@ void cv2eigen( const Mat& src, src.convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } -} - +} + +//Matx +template +void cv2eigen( const Matx<_Tp, 1, _cols>& src, + Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) +{ + dst.resize(_cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + Mat _dst(_cols, 1, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + transpose(src, _dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } + else + { + Mat _dst(1, _cols, DataType<_Tp>::type, + dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + CV_DbgAssert(_dst.data == (uchar*)dst.data()); + } +} + + } #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/gpumat.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/gpumat.hpp new file mode 100644 index 0000000..dffb344 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/gpumat.hpp @@ -0,0 +1,577 @@ +/*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. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. +// +// * The name of the copyright holders 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 __OPENCV_GPUMAT_HPP__ +#define __OPENCV_GPUMAT_HPP__ + +#ifdef __cplusplus + +#include "opencv2/core/core.hpp" +#include "opencv2/core/cuda_devptrs.hpp" + +namespace cv { namespace gpu +{ + //////////////////////////////// Initialization & Info //////////////////////// + + //! This is the only function that do not throw exceptions if the library is compiled without Cuda. + CV_EXPORTS int getCudaEnabledDeviceCount(); + + //! Functions below throw cv::Expception if the library is compiled without Cuda. + + CV_EXPORTS void setDevice(int device); + CV_EXPORTS int getDevice(); + + //! Explicitly destroys and cleans up all resources associated with the current device in the current process. + //! Any subsequent API call to this device will reinitialize the device. + CV_EXPORTS void resetDevice(); + + enum FeatureSet + { + FEATURE_SET_COMPUTE_10 = 10, + FEATURE_SET_COMPUTE_11 = 11, + FEATURE_SET_COMPUTE_12 = 12, + FEATURE_SET_COMPUTE_13 = 13, + FEATURE_SET_COMPUTE_20 = 20, + FEATURE_SET_COMPUTE_21 = 21, + FEATURE_SET_COMPUTE_30 = 30, + GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, + SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, + NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, + WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30 + }; + + // Gives information about what GPU archs this OpenCV GPU module was + // compiled for + class CV_EXPORTS TargetArchs + { + public: + static bool builtWith(FeatureSet feature_set); + static bool has(int major, int minor); + static bool hasPtx(int major, int minor); + static bool hasBin(int major, int minor); + static bool hasEqualOrLessPtx(int major, int minor); + static bool hasEqualOrGreater(int major, int minor); + static bool hasEqualOrGreaterPtx(int major, int minor); + static bool hasEqualOrGreaterBin(int major, int minor); + private: + TargetArchs(); + }; + + // Gives information about the given GPU + class CV_EXPORTS DeviceInfo + { + public: + // Creates DeviceInfo object for the current GPU + DeviceInfo() : device_id_(getDevice()) { query(); } + + // Creates DeviceInfo object for the given GPU + DeviceInfo(int device_id) : device_id_(device_id) { query(); } + + std::string name() const { return name_; } + + // Return compute capability versions + int majorVersion() const { return majorVersion_; } + int minorVersion() const { return minorVersion_; } + + int multiProcessorCount() const { return multi_processor_count_; } + + size_t freeMemory() const; + size_t totalMemory() const; + + // Checks whether device supports the given feature + bool supports(FeatureSet feature_set) const; + + // Checks whether the GPU module can be run on the given device + bool isCompatible() const; + + int deviceID() const { return device_id_; } + + private: + void query(); + void queryMemory(size_t& free_memory, size_t& total_memory) const; + + int device_id_; + + std::string name_; + int multi_processor_count_; + int majorVersion_; + int minorVersion_; + }; + + CV_EXPORTS void printCudaDeviceInfo(int device); + CV_EXPORTS void printShortCudaDeviceInfo(int device); + + //////////////////////////////// GpuMat /////////////////////////////// + + //! Smart pointer for GPU memory with reference counting. Its interface is mostly similar with cv::Mat. + class CV_EXPORTS GpuMat + { + public: + //! default constructor + GpuMat(); + + //! constructs GpuMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) + GpuMat(int rows, int cols, int type); + GpuMat(Size size, int type); + + //! constucts GpuMatrix and fills it with the specified value _s. + GpuMat(int rows, int cols, int type, Scalar s); + GpuMat(Size size, int type, Scalar s); + + //! copy constructor + GpuMat(const GpuMat& m); + + //! constructor for GpuMatrix headers pointing to user-allocated data + GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); + GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); + + //! creates a matrix header for a part of the bigger matrix + GpuMat(const GpuMat& m, Range rowRange, Range colRange); + GpuMat(const GpuMat& m, Rect roi); + + //! builds GpuMat from Mat. Perfom blocking upload to device. + explicit GpuMat(const Mat& m); + + //! destructor - calls release() + ~GpuMat(); + + //! assignment operators + GpuMat& operator = (const GpuMat& m); + + //! pefroms blocking upload data to GpuMat. + void upload(const Mat& m); + + //! downloads data from device to host memory. Blocking calls. + void download(Mat& m) const; + + //! returns a new GpuMatrix header for the specified row + GpuMat row(int y) const; + //! returns a new GpuMatrix header for the specified column + GpuMat col(int x) const; + //! ... for the specified row span + GpuMat rowRange(int startrow, int endrow) const; + GpuMat rowRange(Range r) const; + //! ... for the specified column span + GpuMat colRange(int startcol, int endcol) const; + GpuMat colRange(Range r) const; + + //! returns deep copy of the GpuMatrix, i.e. the data is copied + GpuMat clone() const; + //! copies the GpuMatrix content to "m". + // It calls m.create(this->size(), this->type()). + void copyTo(GpuMat& m) const; + //! copies those GpuMatrix elements to "m" that are marked with non-zero mask elements. + void copyTo(GpuMat& m, const GpuMat& mask) const; + //! converts GpuMatrix to another datatype with optional scalng. See cvConvertScale. + void convertTo(GpuMat& m, int rtype, double alpha = 1, double beta = 0) const; + + void assignTo(GpuMat& m, int type=-1) const; + + //! sets every GpuMatrix element to s + GpuMat& operator = (Scalar s); + //! sets some of the GpuMatrix elements to s, according to the mask + GpuMat& setTo(Scalar s, const GpuMat& mask = GpuMat()); + //! creates alternative GpuMatrix header for the same data, with different + // number of channels and/or different number of rows. see cvReshape. + GpuMat reshape(int cn, int rows = 0) const; + + //! allocates new GpuMatrix data unless the GpuMatrix already has specified size and type. + // previous data is unreferenced if needed. + void create(int rows, int cols, int type); + void create(Size size, int type); + //! decreases reference counter; + // deallocate the data when reference counter reaches 0. + void release(); + + //! swaps with other smart pointer + void swap(GpuMat& mat); + + //! locates GpuMatrix header within a parent GpuMatrix. See below + void locateROI(Size& wholeSize, Point& ofs) const; + //! moves/resizes the current GpuMatrix ROI inside the parent GpuMatrix. + GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); + //! extracts a rectangular sub-GpuMatrix + // (this is a generalized form of row, rowRange etc.) + GpuMat operator()(Range rowRange, Range colRange) const; + GpuMat operator()(Rect roi) const; + + //! returns true iff the GpuMatrix data is continuous + // (i.e. when there are no gaps between successive rows). + // similar to CV_IS_GpuMat_CONT(cvGpuMat->type) + bool isContinuous() const; + //! returns element size in bytes, + // similar to CV_ELEM_SIZE(cvMat->type) + size_t elemSize() const; + //! returns the size of element channel in bytes. + size_t elemSize1() const; + //! returns element type, similar to CV_MAT_TYPE(cvMat->type) + int type() const; + //! returns element type, similar to CV_MAT_DEPTH(cvMat->type) + int depth() const; + //! returns element type, similar to CV_MAT_CN(cvMat->type) + int channels() const; + //! returns step/elemSize1() + size_t step1() const; + //! returns GpuMatrix size: + // width == number of columns, height == number of rows + Size size() const; + //! returns true if GpuMatrix data is NULL + bool empty() const; + + //! returns pointer to y-th row + uchar* ptr(int y = 0); + const uchar* ptr(int y = 0) const; + + //! template version of the above method + template _Tp* ptr(int y = 0); + template const _Tp* ptr(int y = 0) const; + + template operator PtrStepSz<_Tp>() const; + template operator PtrStep<_Tp>() const; + + // Deprecated function + __CV_GPU_DEPR_BEFORE__ template operator DevMem2D_<_Tp>() const __CV_GPU_DEPR_AFTER__; + __CV_GPU_DEPR_BEFORE__ template operator PtrStep_<_Tp>() const __CV_GPU_DEPR_AFTER__; + #undef __CV_GPU_DEPR_BEFORE__ + #undef __CV_GPU_DEPR_AFTER__ + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! the number of rows and columns + int rows, cols; + + //! a distance between successive rows in bytes; includes the gap if any + size_t step; + + //! pointer to the data + uchar* data; + + //! pointer to the reference counter; + // when GpuMatrix points to user-allocated data, the pointer is NULL + int* refcount; + + //! helper fields used in locateROI and adjustROI + uchar* datastart; + uchar* dataend; + }; + + //! Creates continuous GPU matrix + CV_EXPORTS void createContinuous(int rows, int cols, int type, GpuMat& m); + CV_EXPORTS GpuMat createContinuous(int rows, int cols, int type); + CV_EXPORTS void createContinuous(Size size, int type, GpuMat& m); + CV_EXPORTS GpuMat createContinuous(Size size, int type); + + //! Ensures that size of the given matrix is not less than (rows, cols) size + //! and matrix type is match specified one too + CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, GpuMat& m); + CV_EXPORTS void ensureSizeIsEnough(Size size, int type, GpuMat& m); + + CV_EXPORTS GpuMat allocMatFromBuf(int rows, int cols, int type, GpuMat &mat); + + //////////////////////////////////////////////////////////////////////// + // Error handling + + CV_EXPORTS void error(const char* error_string, const char* file, const int line, const char* func = ""); + + //////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////// + + inline GpuMat::GpuMat() + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) + { + } + + inline GpuMat::GpuMat(int rows_, int cols_, int type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) + { + if (rows_ > 0 && cols_ > 0) + create(rows_, cols_, type_); + } + + inline GpuMat::GpuMat(Size size_, int type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) + { + if (size_.height > 0 && size_.width > 0) + create(size_.height, size_.width, type_); + } + + inline GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) + { + if (rows_ > 0 && cols_ > 0) + { + create(rows_, cols_, type_); + setTo(s_); + } + } + + inline GpuMat::GpuMat(Size size_, int type_, Scalar s_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0) + { + if (size_.height > 0 && size_.width > 0) + { + create(size_.height, size_.width, type_); + setTo(s_); + } + } + + inline GpuMat::~GpuMat() + { + release(); + } + + inline GpuMat GpuMat::clone() const + { + GpuMat m; + copyTo(m); + return m; + } + + inline void GpuMat::assignTo(GpuMat& m, int _type) const + { + if (_type < 0) + m = *this; + else + convertTo(m, _type); + } + + inline size_t GpuMat::step1() const + { + return step / elemSize1(); + } + + inline bool GpuMat::empty() const + { + return data == 0; + } + + template inline _Tp* GpuMat::ptr(int y) + { + return (_Tp*)ptr(y); + } + + template inline const _Tp* GpuMat::ptr(int y) const + { + return (const _Tp*)ptr(y); + } + + inline void swap(GpuMat& a, GpuMat& b) + { + a.swap(b); + } + + inline GpuMat GpuMat::row(int y) const + { + return GpuMat(*this, Range(y, y+1), Range::all()); + } + + inline GpuMat GpuMat::col(int x) const + { + return GpuMat(*this, Range::all(), Range(x, x+1)); + } + + inline GpuMat GpuMat::rowRange(int startrow, int endrow) const + { + return GpuMat(*this, Range(startrow, endrow), Range::all()); + } + + inline GpuMat GpuMat::rowRange(Range r) const + { + return GpuMat(*this, r, Range::all()); + } + + inline GpuMat GpuMat::colRange(int startcol, int endcol) const + { + return GpuMat(*this, Range::all(), Range(startcol, endcol)); + } + + inline GpuMat GpuMat::colRange(Range r) const + { + return GpuMat(*this, Range::all(), r); + } + + inline void GpuMat::create(Size size_, int type_) + { + create(size_.height, size_.width, type_); + } + + inline GpuMat GpuMat::operator()(Range _rowRange, Range _colRange) const + { + return GpuMat(*this, _rowRange, _colRange); + } + + inline GpuMat GpuMat::operator()(Rect roi) const + { + return GpuMat(*this, roi); + } + + inline bool GpuMat::isContinuous() const + { + return (flags & Mat::CONTINUOUS_FLAG) != 0; + } + + inline size_t GpuMat::elemSize() const + { + return CV_ELEM_SIZE(flags); + } + + inline size_t GpuMat::elemSize1() const + { + return CV_ELEM_SIZE1(flags); + } + + inline int GpuMat::type() const + { + return CV_MAT_TYPE(flags); + } + + inline int GpuMat::depth() const + { + return CV_MAT_DEPTH(flags); + } + + inline int GpuMat::channels() const + { + return CV_MAT_CN(flags); + } + + inline Size GpuMat::size() const + { + return Size(cols, rows); + } + + inline uchar* GpuMat::ptr(int y) + { + CV_DbgAssert((unsigned)y < (unsigned)rows); + return data + step * y; + } + + inline const uchar* GpuMat::ptr(int y) const + { + CV_DbgAssert((unsigned)y < (unsigned)rows); + return data + step * y; + } + + inline GpuMat& GpuMat::operator = (Scalar s) + { + setTo(s); + return *this; + } + + template inline GpuMat::operator PtrStepSz() const + { + return PtrStepSz(rows, cols, (T*)data, step); + } + + template inline GpuMat::operator PtrStep() const + { + return PtrStep((T*)data, step); + } + + template inline GpuMat::operator DevMem2D_() const + { + return DevMem2D_(rows, cols, (T*)data, step); + } + + template inline GpuMat::operator PtrStep_() const + { + return PtrStep_(static_cast< DevMem2D_ >(*this)); + } + + inline GpuMat createContinuous(int rows, int cols, int type) + { + GpuMat m; + createContinuous(rows, cols, type, m); + return m; + } + + inline void createContinuous(Size size, int type, GpuMat& m) + { + createContinuous(size.height, size.width, type, m); + } + + inline GpuMat createContinuous(Size size, int type) + { + GpuMat m; + createContinuous(size, type, m); + return m; + } + + inline void ensureSizeIsEnough(Size size, int type, GpuMat& m) + { + ensureSizeIsEnough(size.height, size.width, type, m); + } + + inline void createContinuous(int rows, int cols, int type, GpuMat& m) + { + int area = rows * cols; + if (!m.isContinuous() || m.type() != type || m.size().area() != area) + ensureSizeIsEnough(1, area, type, m); + m = m.reshape(0, rows); + } + + inline void ensureSizeIsEnough(int rows, int cols, int type, GpuMat& m) + { + if (m.type() == type && m.rows >= rows && m.cols >= cols) + m = m(Rect(0, 0, cols, rows)); + else + m.create(rows, cols, type); + } + + inline GpuMat allocMatFromBuf(int rows, int cols, int type, GpuMat &mat) + { + if (!mat.empty() && mat.type() == type && mat.rows >= rows && mat.cols >= cols) + return mat(Rect(0, 0, cols, rows)); + return mat = GpuMat(rows, cols, type); + } +}} + +#endif // __cplusplus + +#endif // __OPENCV_GPUMAT_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/internal.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/internal.hpp old mode 100755 new mode 100644 similarity index 78% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/internal.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/internal.hpp index 7c9a900..93e56c3 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/internal.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/internal.hpp @@ -59,36 +59,27 @@ # endif #endif -#if defined WIN32 || defined WINCE -#ifndef _WIN32_WINNT // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?) -#define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx -#endif -#include -#undef small -#undef min -#undef max -#else -#include -#include +#if !defined WIN32 && !defined WINCE +# include #endif #ifdef __BORLANDC__ -#ifndef WIN32 - #define WIN32 -#endif -#ifndef _WIN32 - #define _WIN32 -#endif - #define CV_DLL - #undef _CV_ALWAYS_PROFILE_ - #define _CV_ALWAYS_NO_PROFILE_ +# ifndef WIN32 +# define WIN32 +# endif +# ifndef _WIN32 +# define _WIN32 +# endif +# define CV_DLL +# undef _CV_ALWAYS_PROFILE_ +# define _CV_ALWAYS_NO_PROFILE_ #endif #ifndef FALSE -#define FALSE 0 +# define FALSE 0 #endif #ifndef TRUE -#define TRUE 1 +# define TRUE 1 #endif #define __BEGIN__ __CV_BEGIN__ @@ -96,7 +87,7 @@ #define EXIT __CV_EXIT__ #ifdef HAVE_IPP -#include "ipp.h" +# include "ipp.h" CV_INLINE IppiSize ippiSize(int width, int height) { @@ -105,139 +96,191 @@ CV_INLINE IppiSize ippiSize(int width, int height) } #endif -#if defined __SSE2__ || _MSC_VER >= 1300 -#include "emmintrin.h" -#define CV_SSE 1 -#define CV_SSE2 1 -#if defined __SSE3__ || _MSC_VER >= 1500 -#include "pmmintrin.h" -#define CV_SSE3 1 -#endif -#else -#define CV_SSE 0 -#define CV_SSE2 0 -#define CV_SSE3 0 +#ifndef IPPI_CALL +# define IPPI_CALL(func) CV_Assert((func) >= 0) #endif -#if defined ANDROID && defined __ARM_NEON__ && defined __GNUC__ -#include "arm_neon.h" -#define CV_NEON 1 +#if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) +# include "emmintrin.h" +# define CV_SSE 1 +# define CV_SSE2 1 +# if defined __SSE3__ || (defined _MSC_VER && _MSC_VER >= 1500) +# include "pmmintrin.h" +# define CV_SSE3 1 +# endif +# if defined __SSSE3__ || (defined _MSC_VER && _MSC_VER >= 1500) +# include "tmmintrin.h" +# define CV_SSSE3 1 +# endif +# if defined __SSE4_1__ || (defined _MSC_VER && _MSC_VER >= 1500) +# include +# define CV_SSE4_1 1 +# endif +# if defined __SSE4_2__ || (defined _MSC_VER && _MSC_VER >= 1500) +# include +# define CV_SSE4_2 1 +# endif +# if defined __AVX__ || (defined _MSC_FULL_VER && _MSC_FULL_VER >= 160040219) +// MS Visual Studio 2010 (2012?) has no macro pre-defined to identify the use of /arch:AVX +// See: http://connect.microsoft.com/VisualStudio/feedback/details/605858/arch-avx-should-define-a-predefined-macro-in-x64-and-set-a-unique-value-for-m-ix86-fp-in-win32 +# include +# define CV_AVX 1 +# if defined(_XCR_XFEATURE_ENABLED_MASK) +# define __xgetbv() _xgetbv(_XCR_XFEATURE_ENABLED_MASK) +# else +# define __xgetbv() 0 +# endif +# endif +#endif -#define CPU_HAS_NEON_FEATURE (true) -//TODO: make real check using stuff from "cpu-features.h" -//((bool)android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) -#else -#define CV_NEON 0 -#define CPU_HAS_NEON_FEATURE (false) +#ifdef __ARM_NEON__ +# include +# define CV_NEON 1 +# define CPU_HAS_NEON_FEATURE (true) #endif -#ifndef IPPI_CALL -#define IPPI_CALL(func) CV_Assert((func) >= 0) +#ifndef CV_SSE +# define CV_SSE 0 +#endif +#ifndef CV_SSE2 +# define CV_SSE2 0 +#endif +#ifndef CV_SSE3 +# define CV_SSE3 0 +#endif +#ifndef CV_SSSE3 +# define CV_SSSE3 0 +#endif +#ifndef CV_SSE4_1 +# define CV_SSE4_1 0 +#endif +#ifndef CV_SSE4_2 +# define CV_SSE4_2 0 +#endif +#ifndef CV_AVX +# define CV_AVX 0 +#endif +#ifndef CV_NEON +# define CV_NEON 0 #endif #ifdef HAVE_TBB - #include "tbb/tbb_stddef.h" - #if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202 - #include "tbb/tbb.h" - #include "tbb/task.h" - #undef min - #undef max - #else - #undef HAVE_TBB - #endif +# include "tbb/tbb_stddef.h" +# if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202 +# include "tbb/tbb.h" +# include "tbb/task.h" +# undef min +# undef max +# else +# undef HAVE_TBB +# endif #endif #ifdef HAVE_EIGEN - #include - #include "opencv2/core/eigen.hpp" +# if defined __GNUC__ && defined __APPLE__ +# pragma GCC diagnostic ignored "-Wshadow" +# endif +# include +# include "opencv2/core/eigen.hpp" #endif #ifdef __cplusplus +namespace cv +{ #ifdef HAVE_TBB - namespace cv + + typedef tbb::blocked_range BlockedRange; + + template static inline + void parallel_for( const BlockedRange& range, const Body& body ) { - typedef tbb::blocked_range BlockedRange; - - template static inline - void parallel_for( const BlockedRange& range, const Body& body ) - { - tbb::parallel_for(range, body); - } - - template static inline - void parallel_do( Iterator first, Iterator last, const Body& body ) - { - tbb::parallel_do(first, last, body); - } - - typedef tbb::split Split; - - template static inline - void parallel_reduce( const BlockedRange& range, Body& body ) - { - tbb::parallel_reduce(range, body); - } - - typedef tbb::concurrent_vector ConcurrentRectVector; - typedef tbb::concurrent_vector ConcurrentDoubleVector; + tbb::parallel_for(range, body); } -#else - namespace cv + + template static inline + void parallel_do( Iterator first, Iterator last, const Body& body ) { - class BlockedRange - { - public: - BlockedRange() : _begin(0), _end(0), _grainsize(0) {} - BlockedRange(int b, int e, int g=1) : _begin(b), _end(e), _grainsize(g) {} - int begin() const { return _begin; } - int end() const { return _end; } - int grainsize() const { return _grainsize; } - - protected: - int _begin, _end, _grainsize; - }; - - -#ifdef HAVE_THREADING_FRAMEWORK -#include "opencv2/core/threading_framework.hpp" - - template - static void parallel_for( const BlockedRange& range, const Body& body ) - { - tf::parallel_for(range, body); - } - - typedef tf::ConcurrentVector ConcurrentRectVector; - typedef tf::ConcurrentVector ConcurrentDoubleVector; + tbb::parallel_do(first, last, body); + } + + typedef tbb::split Split; + + template static inline + void parallel_reduce( const BlockedRange& range, Body& body ) + { + tbb::parallel_reduce(range, body); + } + + typedef tbb::concurrent_vector ConcurrentRectVector; + typedef tbb::concurrent_vector ConcurrentDoubleVector; #else - template static inline - void parallel_for( const BlockedRange& range, const Body& body ) - { - body(range); - } - typedef std::vector ConcurrentRectVector; - typedef std::vector ConcurrentDoubleVector; -#endif - - template static inline - void parallel_do( Iterator first, Iterator last, const Body& body ) - { - for( ; first != last; ++first ) - body(*first); - } - - class Split {}; - - template static inline - void parallel_reduce( const BlockedRange& range, Body& body ) - { - body(range); - } - + class BlockedRange + { + public: + BlockedRange() : _begin(0), _end(0), _grainsize(0) {} + BlockedRange(int b, int e, int g=1) : _begin(b), _end(e), _grainsize(g) {} + int begin() const { return _begin; } + int end() const { return _end; } + int grainsize() const { return _grainsize; } + + protected: + int _begin, _end, _grainsize; + }; + + template static inline + void parallel_for( const BlockedRange& range, const Body& body ) + { + body(range); + } + typedef std::vector ConcurrentRectVector; + typedef std::vector ConcurrentDoubleVector; + + template static inline + void parallel_do( Iterator first, Iterator last, const Body& body ) + { + for( ; first != last; ++first ) + body(*first); + } + + class Split {}; + + template static inline + void parallel_reduce( const BlockedRange& range, Body& body ) + { + body(range); } #endif -#endif +} //namespace cv + +#define CV_INIT_ALGORITHM(classname, algname, memberinit) \ + static ::cv::Algorithm* create##classname() \ + { \ + return new classname; \ + } \ + \ + static ::cv::AlgorithmInfo& classname##_info() \ + { \ + static ::cv::AlgorithmInfo classname##_info_var(algname, create##classname); \ + return classname##_info_var; \ + } \ + \ + static ::cv::AlgorithmInfo& classname##_info_auto = classname##_info(); \ + \ + ::cv::AlgorithmInfo* classname::info() const \ + { \ + static volatile bool initialized = false; \ + \ + if( !initialized ) \ + { \ + initialized = true; \ + classname obj; \ + memberinit; \ + } \ + return &classname##_info(); \ + } + +#endif //__cplusplus /* maximal size of vector to run matrix operations on it inline (i.e. w/o ipp calls) */ #define CV_MAX_INLINE_MAT_OP_SIZE 10 @@ -281,9 +324,9 @@ CV_INLINE IppiSize ippiSize(int width, int height) #define CV_MAX_STRLEN 1024 #if 0 /*def CV_CHECK_FOR_NANS*/ - #define CV_CHECK_NANS( arr ) cvCheckArray((arr)) +# define CV_CHECK_NANS( arr ) cvCheckArray((arr)) #else - #define CV_CHECK_NANS( arr ) +# define CV_CHECK_NANS( arr ) #endif /****************************************************************************************\ @@ -292,38 +335,38 @@ CV_INLINE IppiSize ippiSize(int width, int height) /* get alloca declaration */ #ifdef __GNUC__ - #undef alloca - #define alloca __builtin_alloca - #define CV_HAVE_ALLOCA 1 +# undef alloca +# define alloca __builtin_alloca +# define CV_HAVE_ALLOCA 1 #elif defined WIN32 || defined _WIN32 || \ defined WINCE || defined _MSC_VER || defined __BORLANDC__ - #include - #define CV_HAVE_ALLOCA 1 +# include +# define CV_HAVE_ALLOCA 1 #elif defined HAVE_ALLOCA_H - #include - #define CV_HAVE_ALLOCA 1 +# include +# define CV_HAVE_ALLOCA 1 #elif defined HAVE_ALLOCA - #include - #define CV_HAVE_ALLOCA 1 +# include +# define CV_HAVE_ALLOCA 1 #else - #undef CV_HAVE_ALLOCA +# undef CV_HAVE_ALLOCA #endif #ifdef __GNUC__ -#define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) +# define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) #elif defined _MSC_VER -#define CV_DECL_ALIGNED(x) __declspec(align(x)) +# define CV_DECL_ALIGNED(x) __declspec(align(x)) #else -#define CV_DECL_ALIGNED(x) +# define CV_DECL_ALIGNED(x) #endif #if CV_HAVE_ALLOCA /* ! DO NOT make it an inline function */ -#define cvStackAlloc(size) cvAlignPtr( alloca((size) + CV_MALLOC_ALIGN), CV_MALLOC_ALIGN ) +# define cvStackAlloc(size) cvAlignPtr( alloca((size) + CV_MALLOC_ALIGN), CV_MALLOC_ALIGN ) #endif #ifndef CV_IMPL -#define CV_IMPL CV_EXTERN_C +# define CV_IMPL CV_EXTERN_C #endif #define CV_DBG_BREAK() { volatile int* crashMe = 0; *crashMe = 0; } @@ -663,25 +706,25 @@ typedef enum CvStatus CV_UNSUPPORTED_DEPTH_ERR = -101, CV_UNSUPPORTED_FORMAT_ERR = -100, - CV_BADARG_ERR = -49, //ipp comp - CV_NOTDEFINED_ERR = -48, //ipp comp - - CV_BADCHANNELS_ERR = -47, //ipp comp - CV_BADRANGE_ERR = -44, //ipp comp - CV_BADSTEP_ERR = -29, //ipp comp - - CV_BADFLAG_ERR = -12, - CV_DIV_BY_ZERO_ERR = -11, //ipp comp - CV_BADCOEF_ERR = -10, - - CV_BADFACTOR_ERR = -7, - CV_BADPOINT_ERR = -6, - CV_BADSCALE_ERR = -4, - CV_OUTOFMEM_ERR = -3, - CV_NULLPTR_ERR = -2, - CV_BADSIZE_ERR = -1, - CV_NO_ERR = 0, - CV_OK = CV_NO_ERR + CV_BADARG_ERR = -49, //ipp comp + CV_NOTDEFINED_ERR = -48, //ipp comp + + CV_BADCHANNELS_ERR = -47, //ipp comp + CV_BADRANGE_ERR = -44, //ipp comp + CV_BADSTEP_ERR = -29, //ipp comp + + CV_BADFLAG_ERR = -12, + CV_DIV_BY_ZERO_ERR = -11, //ipp comp + CV_BADCOEF_ERR = -10, + + CV_BADFACTOR_ERR = -7, + CV_BADPOINT_ERR = -6, + CV_BADSCALE_ERR = -4, + CV_OUTOFMEM_ERR = -3, + CV_NULLPTR_ERR = -2, + CV_BADSIZE_ERR = -1, + CV_NO_ERR = 0, + CV_OK = CV_NO_ERR } CvStatus; @@ -696,8 +739,7 @@ CvFuncTable; typedef struct CvBigFuncTable { void* fn_2d[CV_DEPTH_MAX*4]; -} -CvBigFuncTable; +} CvBigFuncTable; #define CV_INIT_FUNC_TAB( tab, FUNCNAME, FLAG ) \ (tab).fn_2d[CV_8U] = (void*)FUNCNAME##_8u##FLAG; \ @@ -708,4 +750,39 @@ CvBigFuncTable; (tab).fn_2d[CV_32F] = (void*)FUNCNAME##_32f##FLAG; \ (tab).fn_2d[CV_64F] = (void*)FUNCNAME##_64f##FLAG +#ifdef __cplusplus +//! OpenGL extension table +class CV_EXPORTS CvOpenGlFuncTab +{ +public: + virtual ~CvOpenGlFuncTab(); + + virtual void genBuffers(int n, unsigned int* buffers) const = 0; + virtual void deleteBuffers(int n, const unsigned int* buffers) const = 0; + + virtual void bufferData(unsigned int target, ptrdiff_t size, const void* data, unsigned int usage) const = 0; + virtual void bufferSubData(unsigned int target, ptrdiff_t offset, ptrdiff_t size, const void* data) const = 0; + + virtual void bindBuffer(unsigned int target, unsigned int buffer) const = 0; + + virtual void* mapBuffer(unsigned int target, unsigned int access) const = 0; + virtual void unmapBuffer(unsigned int target) const = 0; + + virtual void generateBitmapFont(const std::string& family, int height, int weight, bool italic, bool underline, int start, int count, int base) const = 0; + + virtual bool isGlContextInitialized() const = 0; +}; + +CV_EXPORTS void icvSetOpenGlFuncTab(const CvOpenGlFuncTab* tab); + +CV_EXPORTS bool icvCheckGlError(const char* file, const int line, const char* func = ""); + +#if defined(__GNUC__) + #define CV_CheckGlError() CV_DbgAssert( (::icvCheckGlError(__FILE__, __LINE__, __func__)) ) +#else + #define CV_CheckGlError() CV_DbgAssert( (::icvCheckGlError(__FILE__, __LINE__)) ) #endif + +#endif //__cplusplus + +#endif // __OPENCV_CORE_INTERNAL_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/mat.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/mat.hpp old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/mat.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/mat.hpp index 6f444e4..92301cf --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/mat.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/mat.hpp @@ -55,56 +55,58 @@ namespace cv //////////////////////////////// Mat //////////////////////////////// -inline Mat::Mat() - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) +inline void Mat::initEmpty() { + flags = MAGIC_VAL; + dims = rows = cols = 0; + data = datastart = dataend = datalimit = 0; + refcount = 0; + allocator = 0; +} + +inline Mat::Mat() : size(&rows) +{ + initEmpty(); } -inline Mat::Mat(int _rows, int _cols, int _type) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) +inline Mat::Mat(int _rows, int _cols, int _type) : size(&rows) { + initEmpty(); create(_rows, _cols, _type); } -inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) +inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s) : size(&rows) { + initEmpty(); create(_rows, _cols, _type); *this = _s; } -inline Mat::Mat(Size _sz, int _type) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) +inline Mat::Mat(Size _sz, int _type) : size(&rows) { + initEmpty(); create( _sz.height, _sz.width, _type ); } - -inline Mat::Mat(Size _sz, int _type, const Scalar& _s) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) + +inline Mat::Mat(Size _sz, int _type, const Scalar& _s) : size(&rows) { + initEmpty(); create(_sz.height, _sz.width, _type); *this = _s; } - -inline Mat::Mat(int _dims, const int* _sz, int _type) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) + +inline Mat::Mat(int _dims, const int* _sz, int _type) : size(&rows) { + initEmpty(); create(_dims, _sz, _type); } -inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s) - : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), - datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows) +inline Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s) : size(&rows) { + initEmpty(); create(_dims, _sz, _type); *this = _s; -} +} inline Mat::Mat(const Mat& m) : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data), @@ -169,27 +171,6 @@ inline Mat::Mat(Size _sz, int _type, void* _data, size_t _step) } -inline Mat::Mat(const CvMat* m, bool copyData) - : flags(MAGIC_VAL + (m->type & (CV_MAT_TYPE_MASK|CV_MAT_CONT_FLAG))), - dims(2), rows(m->rows), cols(m->cols), data(m->data.ptr), refcount(0), - datastart(m->data.ptr), allocator(0), size(&rows) -{ - if( !copyData ) - { - size_t esz = CV_ELEM_SIZE(m->type), minstep = cols*esz, _step = m->step; - if( _step == 0 ) - _step = minstep; - datalimit = datastart + _step*rows; - dataend = datalimit - _step + minstep; - step[0] = _step; step[1] = esz; - } - else - { - data = datastart = dataend = 0; - Mat(m->rows, m->cols, m->type, m->data.ptr, m->step).copyTo(*this); - } -} - template inline Mat::Mat(const vector<_Tp>& vec, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), cols(1), data(0), refcount(0), @@ -206,8 +187,8 @@ template inline Mat::Mat(const vector<_Tp>& vec, bool copyData) else Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this); } - - + + template inline Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), refcount(0), @@ -237,10 +218,10 @@ template inline Mat::Mat(const Matx<_Tp,m,n>& M, boo datalimit = dataend = datastart + rows*step[0]; } else - Mat(m, n, DataType<_Tp>::type, (uchar*)M.val).copyTo(*this); + Mat(m, n, DataType<_Tp>::type, (uchar*)M.val).copyTo(*this); } - + template inline Mat::Mat(const Point_<_Tp>& pt, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), refcount(0), @@ -259,7 +240,7 @@ template inline Mat::Mat(const Point_<_Tp>& pt, bool copyData) ((_Tp*)data)[1] = pt.y; } } - + template inline Mat::Mat(const Point3_<_Tp>& pt, bool copyData) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), @@ -281,7 +262,7 @@ template inline Mat::Mat(const Point3_<_Tp>& pt, bool copyData) } } - + template inline Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), refcount(0), @@ -289,7 +270,7 @@ template inline Mat::Mat(const MatCommaInitializer_<_Tp>& commaIni { *this = *commaInitializer; } - + inline Mat::~Mat() { release(); @@ -324,7 +305,7 @@ inline Mat& Mat::operator = (const Mat& m) } return *this; } - + inline Mat Mat::row(int y) const { return Mat(*this, Range(y, y+1), Range::all()); } inline Mat Mat::col(int x) const { return Mat(*this, Range::all(), Range(x, x+1)); } inline Mat Mat::rowRange(int startrow, int endrow) const @@ -338,9 +319,13 @@ inline Mat Mat::colRange(const Range& r) const inline Mat Mat::diag(const Mat& d) { - CV_Assert( d.cols == 1 ); - Mat m(d.rows, d.rows, d.type(), Scalar(0)), md = m.diag(); - d.copyTo(md); + CV_Assert( d.cols == 1 || d.rows == 1 ); + int len = d.rows + d.cols - 1; + Mat m(len, len, d.type(), Scalar(0)), md = m.diag(); + if( d.cols == 1 ) + d.copyTo(md); + else + transpose(d, md); return m; } @@ -351,12 +336,12 @@ inline Mat Mat::clone() const return m; } -inline void Mat::assignTo( Mat& m, int type ) const +inline void Mat::assignTo( Mat& m, int _type ) const { - if( type < 0 ) + if( _type < 0 ) m = *this; else - convertTo(m, type); + convertTo(m, _type); } inline void Mat::create(int _rows, int _cols, int _type) @@ -385,19 +370,19 @@ inline void Mat::release() refcount = 0; } -inline Mat Mat::operator()( Range rowRange, Range colRange ) const +inline Mat Mat::operator()( Range _rowRange, Range _colRange ) const { - return Mat(*this, rowRange, colRange); + return Mat(*this, _rowRange, _colRange); } - + inline Mat Mat::operator()( const Rect& roi ) const { return Mat(*this, roi); } inline Mat Mat::operator()(const Range* ranges) const { return Mat(*this, ranges); -} - +} + inline Mat::operator CvMat() const { CV_DbgAssert(dims <= 2); @@ -419,7 +404,7 @@ inline bool Mat::empty() const { return data == 0 || total() == 0; } inline size_t Mat::total() const { if( dims <= 2 ) - return rows*cols; + return (size_t)rows*cols; size_t p = 1; for( int i = 0; i < dims; i++ ) p *= size[i]; @@ -450,7 +435,7 @@ template inline const _Tp* Mat::ptr(int y) const return (const _Tp*)(data + step.p[0]*y); } - + inline uchar* Mat::ptr(int i0, int i1) { CV_DbgAssert( dims >= 2 && data && @@ -520,7 +505,7 @@ template inline const _Tp* Mat::ptr(int i0, int i1, int i2) const } inline uchar* Mat::ptr(const int* idx) -{ +{ int i, d = dims; uchar* p = data; CV_DbgAssert( d >= 1 && p ); @@ -543,8 +528,8 @@ inline const uchar* Mat::ptr(const int* idx) const p += idx[i]*step.p[i]; } return p; -} - +} + template inline _Tp& Mat::at(int i0, int i1) { CV_DbgAssert( dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] && @@ -560,7 +545,7 @@ template inline const _Tp& Mat::at(int i0, int i1) const CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1()); return ((const _Tp*)(data + step.p[0]*i0))[i1]; } - + template inline _Tp& Mat::at(Point pt) { CV_DbgAssert( dims <= 2 && data && (unsigned)pt.y < (unsigned)size.p[0] && @@ -579,20 +564,30 @@ template inline const _Tp& Mat::at(Point pt) const template inline _Tp& Mat::at(int i0) { - CV_DbgAssert( dims <= 2 && data && (size.p[0] == 1 || size.p[1] == 1) && - (unsigned)i0 < (unsigned)(size.p[0] + size.p[1] - 1) && + CV_DbgAssert( dims <= 2 && data && + (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) && elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(_Tp*)(data + step.p[size.p[0]==1]*i0); + if( isContinuous() || size.p[0] == 1 ) + return ((_Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(_Tp*)(data + step.p[0]*i0); + int i = i0/cols, j = i0 - i*cols; + return ((_Tp*)(data + step.p[0]*i))[j]; } - + template inline const _Tp& Mat::at(int i0) const { - CV_DbgAssert( dims <= 2 && data && (size.p[0] == 1 || size.p[1] == 1) && - (unsigned)i0 < (unsigned)(size.p[0] + size.p[1] - 1) && + CV_DbgAssert( dims <= 2 && data && + (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) && elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); - return *(_Tp*)(data + step.p[size.p[0]==1]*i0); + if( isContinuous() || size.p[0] == 1 ) + return ((const _Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(const _Tp*)(data + step.p[0]*i0); + int i = i0/cols, j = i0 - i*cols; + return ((const _Tp*)(data + step.p[0]*i))[j]; } - + template inline _Tp& Mat::at(int i0, int i1, int i2) { CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); @@ -613,8 +608,18 @@ template inline const _Tp& Mat::at(const int* idx) const CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); return *(const _Tp*)ptr(idx); } - - +template _Tp& Mat::at(const Vec& idx) +{ + CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); + return *(_Tp*)ptr(idx.val); +} +template inline const _Tp& Mat::at(const Vec& idx) const +{ + CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) ); + return *(const _Tp*)ptr(idx.val); +} + + template inline MatConstIterator_<_Tp> Mat::begin() const { CV_DbgAssert( elemSize() == sizeof(_Tp) ); @@ -654,18 +659,18 @@ template inline Mat::operator Vec<_Tp, n>() const { CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && rows + cols - 1 == n && channels() == 1 ); - + if( isContinuous() && type() == DataType<_Tp>::type ) return Vec<_Tp, n>((_Tp*)data); Vec<_Tp, n> v; Mat tmp(rows, cols, DataType<_Tp>::type, v.val); convertTo(tmp, tmp.type()); return v; } - + template inline Mat::operator Matx<_Tp, m, n>() const { CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); - + if( isContinuous() && type() == DataType<_Tp>::type ) return Matx<_Tp, m, n>((_Tp*)data); Matx<_Tp, m, n> mtx; Mat tmp(rows, cols, DataType<_Tp>::type, mtx.val); @@ -677,11 +682,11 @@ template inline Mat::operator Matx<_Tp, m, n>() cons template inline void Mat::push_back(const _Tp& elem) { if( !data ) - { - *this = Mat(1, 1, DataType<_Tp>::type, (void*)&elem).clone(); - return; - } - CV_Assert(DataType<_Tp>::type == type() && cols == 1 + { + *this = Mat(1, 1, DataType<_Tp>::type, (void*)&elem).clone(); + return; + } + CV_Assert(DataType<_Tp>::type == type() && cols == 1 /* && dims == 2 (cols == 1 implies dims == 2) */); uchar* tmp = dataend + step[0]; if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) @@ -692,16 +697,16 @@ template inline void Mat::push_back(const _Tp& elem) else push_back_(&elem); } - + template inline void Mat::push_back(const Mat_<_Tp>& m) { push_back((const Mat&)m); -} - +} + inline Mat::MSize::MSize(int* _p) : p(_p) {} inline Size Mat::MSize::operator()() const { - CV_DbgAssert(p[-1] <= 2); + CV_DbgAssert(p[-1] <= 2); return Size(p[1], p[0]); } inline const int& Mat::MSize::operator[](int i) const { return p[i]; } @@ -715,18 +720,18 @@ inline bool Mat::MSize::operator == (const MSize& sz) const return false; if( d == 2 ) return p[0] == sz.p[0] && p[1] == sz.p[1]; - + for( int i = 0; i < d; i++ ) if( p[i] != sz.p[i] ) return false; return true; -} +} inline bool Mat::MSize::operator != (const MSize& sz) const { return !(*this == sz); } - + inline Mat::MStep::MStep() { p = buf; p[0] = p[1] = 0; } inline Mat::MStep::MStep(size_t s) { p = buf; p[0] = s; p[1] = 0; } inline const size_t& Mat::MStep::operator[](int i) const { return p[i]; } @@ -742,7 +747,7 @@ inline Mat::MStep& Mat::MStep::operator = (size_t s) buf[0] = s; return *this; } - + static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) { return cvarrToMat(arr, copyData, true, coiMode); @@ -754,7 +759,8 @@ inline SVD::SVD() {} inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } inline void SVD::solveZ( InputArray m, OutputArray _dst ) { - SVD svd(m); + Mat mtx = m.getMat(); + SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); _dst.create(svd.vt.cols, 1, svd.vt.type()); Mat dst = _dst.getMat(); svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); @@ -768,7 +774,7 @@ template inline void SVD::compute(_a, _w, _u, _vt); CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); } - + template inline void SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) { @@ -777,7 +783,7 @@ SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) SVD::compute(_a, _w); CV_Assert(_w.data == (uchar*)&w.val[0]); } - + template inline void SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, @@ -788,12 +794,12 @@ SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, SVD::backSubst(_w, _u, _vt, _rhs, _dst); CV_Assert(_dst.data == (uchar*)&dst.val[0]); } - + ///////////////////////////////// Mat_<_Tp> //////////////////////////////////// template inline Mat_<_Tp>::Mat_() : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; } - + template inline Mat_<_Tp>::Mat_(int _rows, int _cols) : Mat(_rows, _cols, DataType<_Tp>::type) {} @@ -802,19 +808,19 @@ template inline Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& v template inline Mat_<_Tp>::Mat_(Size _sz) : Mat(_sz.height, _sz.width, DataType<_Tp>::type) {} - + template inline Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) : Mat(_sz.height, _sz.width, DataType<_Tp>::type) { *this = value; } - + template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz) : Mat(_dims, _sz, DataType<_Tp>::type) {} - + template inline Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) : Mat(_dims, _sz, DataType<_Tp>::type, Scalar(_s)) {} - + template inline Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) : Mat(m, ranges) {} - + template inline Mat_<_Tp>::Mat_(const Mat& m) : Mat() { flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type; *this = m; } @@ -824,8 +830,8 @@ template inline Mat_<_Tp>::Mat_(const Mat_& m) template inline Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) : Mat(_rows, _cols, DataType<_Tp>::type, _data, steps) {} -template inline Mat_<_Tp>::Mat_(const Mat_& m, const Range& rowRange, const Range& colRange) - : Mat(m, rowRange, colRange) {} +template inline Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) + : Mat(m, _rowRange, _colRange) {} template inline Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) : Mat(m, roi) {} @@ -847,7 +853,7 @@ template template inline if( copyData ) *this = clone(); } - + template inline Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) : Mat(2/DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt) { @@ -866,7 +872,7 @@ template inline Mat_<_Tp>::Mat_(const Point3_ inline Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) : Mat(commaInitializer) {} - + template inline Mat_<_Tp>::Mat_(const vector<_Tp>& vec, bool copyData) : Mat(vec, copyData) {} @@ -912,9 +918,9 @@ template inline void Mat_<_Tp>::create(Size _sz) template inline void Mat_<_Tp>::create(int _dims, const int* _sz) { Mat::create(_dims, _sz, DataType<_Tp>::type); -} - - +} + + template inline Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const { return Mat_<_Tp>(Mat::cross(m)); } @@ -959,21 +965,18 @@ template inline int Mat_<_Tp>::channels() const template inline size_t Mat_<_Tp>::stepT(int i) const { return step.p[i]/elemSize(); } template inline size_t Mat_<_Tp>::step1(int i) const { return step.p[i]/elemSize1(); } -template inline Mat_<_Tp> Mat_<_Tp>::reshape(int _rows) const -{ return Mat_<_Tp>(Mat::reshape(0,_rows)); } - template inline Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) { return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); } -template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range& rowRange, const Range& colRange ) const -{ return Mat_<_Tp>(*this, rowRange, colRange); } +template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const +{ return Mat_<_Tp>(*this, _rowRange, _colRange); } template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const { return Mat_<_Tp>(*this, roi); } template inline Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const -{ return Mat_<_Tp>(*this, ranges); } - +{ return Mat_<_Tp>(*this, ranges); } + template inline _Tp* Mat_<_Tp>::operator [](int y) { return (_Tp*)ptr(y); } template inline const _Tp* Mat_<_Tp>::operator [](int y) const @@ -1025,6 +1028,16 @@ template inline const _Tp& Mat_<_Tp>::operator ()(const int* idx) return Mat::at<_Tp>(idx); } +template template inline _Tp& Mat_<_Tp>::operator ()(const Vec& idx) +{ + return Mat::at<_Tp>(idx); +} + +template template inline const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const +{ + return Mat::at<_Tp>(idx); +} + template inline _Tp& Mat_<_Tp>::operator ()(int i0) { return this->at<_Tp>(i0); @@ -1033,7 +1046,7 @@ template inline _Tp& Mat_<_Tp>::operator ()(int i0) template inline const _Tp& Mat_<_Tp>::operator ()(int i0) const { return this->at<_Tp>(i0); -} +} template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) { @@ -1043,9 +1056,9 @@ template inline _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2 template inline const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const { return this->at<_Tp>(i0, i1, i2); -} - - +} + + template inline Mat_<_Tp>::operator vector<_Tp>() const { vector<_Tp> v; @@ -1063,13 +1076,12 @@ template template inline Mat_<_Tp>::operator Matx::channels == 0); return this->Mat::operator Matx::channel_type, m, n>(); -} +} template inline void process( const Mat_& m1, Mat_& m2, Op op ) { int y, x, rows = m1.rows, cols = m1.cols; - int c1 = m1.channels(), c2 = m2.channels(); CV_DbgAssert( m1.size() == m2.size() ); @@ -1101,33 +1113,65 @@ process( const Mat_& m1, const Mat_& m2, Mat_& m3, Op op ) } } - + /////////////////////////////// Input/Output Arrays ///////////////////////////////// - + template inline _InputArray::_InputArray(const vector<_Tp>& vec) - : flags(STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} + : flags(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} template inline _InputArray::_InputArray(const vector >& vec) - : flags(STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} + : flags(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {} + +template inline _InputArray::_InputArray(const vector >& vec) + : flags(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type), obj((void*)&vec) {} template inline _InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) - : flags(MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m) {} + : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m) {} + +template inline _InputArray::_InputArray(const _Tp* vec, int n) + : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)vec), sz(n, 1) {} inline _InputArray::_InputArray(const Scalar& s) - : flags(MATX + CV_64F), obj((void*)&s), sz(1, 4) {} - -template inline _OutputArray::_OutputArray(vector<_Tp>& vec) : _InputArray(vec) {} -template inline _OutputArray::_OutputArray(vector >& vec) : _InputArray(vec) {} -template inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) : _InputArray(mtx) {} - + : flags(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F), obj((void*)&s), sz(1, 4) {} + +template inline _InputArray::_InputArray(const Mat_<_Tp>& m) + : flags(FIXED_TYPE + MAT + DataType<_Tp>::type), obj((void*)&m) {} + +template inline _OutputArray::_OutputArray(vector<_Tp>& vec) + : _InputArray(vec) {} +template inline _OutputArray::_OutputArray(vector >& vec) + : _InputArray(vec) {} +template inline _OutputArray::_OutputArray(vector >& vec) + : _InputArray(vec) {} +template inline _OutputArray::_OutputArray(Mat_<_Tp>& m) + : _InputArray(m) {} +template inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) + : _InputArray(mtx) {} +template inline _OutputArray::_OutputArray(_Tp* vec, int n) + : _InputArray(vec, n) {} + +template inline _OutputArray::_OutputArray(const vector<_Tp>& vec) + : _InputArray(vec) {flags |= FIXED_SIZE;} +template inline _OutputArray::_OutputArray(const vector >& vec) + : _InputArray(vec) {flags |= FIXED_SIZE;} +template inline _OutputArray::_OutputArray(const vector >& vec) + : _InputArray(vec) {flags |= FIXED_SIZE;} + +template inline _OutputArray::_OutputArray(const Mat_<_Tp>& m) + : _InputArray(m) {flags |= FIXED_SIZE;} +template inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) + : _InputArray(mtx) {} +template inline _OutputArray::_OutputArray(const _Tp* vec, int n) + : _InputArray(vec, n) {} + //////////////////////////////////// Matrix Expressions ///////////////////////////////////////// class CV_EXPORTS MatOp -{ +{ public: MatOp() {}; virtual ~MatOp() {}; - + virtual bool elementWise(const MatExpr& expr) const; virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; virtual void roi(const MatExpr& expr, const Range& rowRange, @@ -1140,30 +1184,30 @@ class CV_EXPORTS MatOp virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; virtual void augAssignOr(const MatExpr& expr, Mat& m) const; virtual void augAssignXor(const MatExpr& expr, Mat& m) const; - + virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; - + virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; - + virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; - + virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; - + virtual void abs(const MatExpr& expr, MatExpr& res) const; - + virtual void transpose(const MatExpr& expr, MatExpr& res) const; virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; - + virtual Size size(const MatExpr& expr) const; virtual int type(const MatExpr& expr) const; }; - + class CV_EXPORTS MatExpr { public: @@ -1178,39 +1222,39 @@ class CV_EXPORTS MatExpr op->assign(*this, m); return m; } - + template operator Mat_<_Tp>() const { Mat_<_Tp> m; op->assign(*this, m, DataType<_Tp>::type); return m; } - + MatExpr row(int y) const; MatExpr col(int x) const; MatExpr diag(int d=0) const; MatExpr operator()( const Range& rowRange, const Range& colRange ) const; MatExpr operator()( const Rect& roi ) const; - + Mat cross(const Mat& m) const; double dot(const Mat& m) const; - + MatExpr t() const; MatExpr inv(int method = DECOMP_LU) const; MatExpr mul(const MatExpr& e, double scale=1) const; MatExpr mul(const Mat& m, double scale=1) const; - + Size size() const; int type() const; - + const MatOp* op; int flags; - + Mat a, b, c; double alpha, beta; Scalar s; }; - + CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); @@ -1241,7 +1285,7 @@ CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); - + CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator / (const Mat& a, double s); CV_EXPORTS MatExpr operator / (double s, const Mat& a); @@ -1249,7 +1293,7 @@ CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); -CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); +CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator < (const Mat& a, double s); @@ -1273,8 +1317,8 @@ CV_EXPORTS MatExpr operator >= (double s, const Mat& a); CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator > (const Mat& a, double s); -CV_EXPORTS MatExpr operator > (double s, const Mat& a); - +CV_EXPORTS MatExpr operator > (double s, const Mat& a); + CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); CV_EXPORTS MatExpr min(const Mat& a, double s); CV_EXPORTS MatExpr min(double s, const Mat& a); @@ -1296,7 +1340,7 @@ template static inline MatExpr min(const Mat_<_Tp>& a, double s) template static inline MatExpr min(double s, const Mat_<_Tp>& a) { return cv::min((const Mat&)a, s); -} +} template static inline MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) { @@ -1311,7 +1355,7 @@ template static inline MatExpr max(const Mat_<_Tp>& a, double s) template static inline MatExpr max(double s, const Mat_<_Tp>& a) { return cv::max((const Mat&)a, s); -} +} template static inline void min(const Mat_<_Tp>& a, const Mat_<_Tp>& b, Mat_<_Tp>& c) { @@ -1330,20 +1374,20 @@ template static inline void min(double s, const Mat_<_Tp>& a, Mat_ template static inline void max(const Mat_<_Tp>& a, const Mat_<_Tp>& b, Mat_<_Tp>& c) { - cv::min((const Mat&)a, (const Mat&)b, (Mat&)c); + cv::max((const Mat&)a, (const Mat&)b, (Mat&)c); } template static inline void max(const Mat_<_Tp>& a, double s, Mat_<_Tp>& c) { - cv::min((const Mat&)a, s, (Mat&)c); + cv::max((const Mat&)a, s, (Mat&)c); } template static inline void max(double s, const Mat_<_Tp>& a, Mat_<_Tp>& c) { - cv::min((const Mat&)a, s, (Mat&)c); + cv::max((const Mat&)a, s, (Mat&)c); } - + CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); @@ -1357,22 +1401,22 @@ CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator ~(const Mat& m); - + CV_EXPORTS MatExpr abs(const Mat& m); CV_EXPORTS MatExpr abs(const MatExpr& e); - + template static inline MatExpr abs(const Mat_<_Tp>& m) { return cv::abs((const Mat&)m); } ////////////////////////////// Augmenting algebraic operations ////////////////////////////////// - + inline Mat& Mat::operator = (const MatExpr& e) { e.op->assign(e, *this); return *this; -} +} template inline Mat_<_Tp>::Mat_(const MatExpr& e) { @@ -1395,7 +1439,7 @@ static inline Mat& operator += (const Mat& a, const Scalar& s) { add(a, s, (Mat&)a); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const Mat_<_Tp>& b) @@ -1409,11 +1453,11 @@ Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const Scalar& s) { add(a, s, (Mat&)a); return (Mat_<_Tp>&)a; -} +} static inline Mat& operator += (const Mat& a, const MatExpr& b) { - b.op->augAssignAdd(b, (Mat&)a); + b.op->augAssignAdd(b, (Mat&)a); return (Mat&)a; } @@ -1423,7 +1467,7 @@ Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) b.op->augAssignAdd(b, (Mat&)a); return (Mat_<_Tp>&)a; } - + static inline Mat& operator -= (const Mat& a, const Mat& b) { subtract(a, b, (Mat&)a); @@ -1434,7 +1478,7 @@ static inline Mat& operator -= (const Mat& a, const Scalar& s) { subtract(a, s, (Mat&)a); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) @@ -1448,11 +1492,11 @@ Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const Scalar& s) { subtract(a, s, (Mat&)a); return (Mat_<_Tp>&)a; -} +} static inline Mat& operator -= (const Mat& a, const MatExpr& b) { - b.op->augAssignSubtract(b, (Mat&)a); + b.op->augAssignSubtract(b, (Mat&)a); return (Mat&)a; } @@ -1461,7 +1505,7 @@ Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignSubtract(b, (Mat&)a); return (Mat_<_Tp>&)a; -} +} static inline Mat& operator *= (const Mat& a, const Mat& b) { @@ -1473,7 +1517,7 @@ static inline Mat& operator *= (const Mat& a, double s) { a.convertTo((Mat&)a, -1, s); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) @@ -1487,11 +1531,11 @@ Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, double s) { a.convertTo((Mat&)a, -1, s); return (Mat_<_Tp>&)a; -} +} static inline Mat& operator *= (const Mat& a, const MatExpr& b) { - b.op->augAssignMultiply(b, (Mat&)a); + b.op->augAssignMultiply(b, (Mat&)a); return (Mat&)a; } @@ -1500,8 +1544,8 @@ Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) { b.op->augAssignMultiply(b, (Mat&)a); return (Mat_<_Tp>&)a; -} - +} + static inline Mat& operator /= (const Mat& a, const Mat& b) { divide(a, b, (Mat&)a); @@ -1512,7 +1556,7 @@ static inline Mat& operator /= (const Mat& a, double s) { a.convertTo((Mat&)a, -1, 1./s); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) @@ -1526,11 +1570,11 @@ Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, double s) { a.convertTo((Mat&)a, -1, 1./s); return (Mat_<_Tp>&)a; -} +} static inline Mat& operator /= (const Mat& a, const MatExpr& b) { - b.op->augAssignDivide(b, (Mat&)a); + b.op->augAssignDivide(b, (Mat&)a); return (Mat&)a; } @@ -1553,22 +1597,22 @@ static inline Mat& operator &= (const Mat& a, const Scalar& s) { bitwise_and(a, s, (Mat&)a); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator &= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) { bitwise_and(a, b, (Mat&)a); return (Mat_<_Tp>&)a; -} +} template static inline Mat_<_Tp>& operator &= (const Mat_<_Tp>& a, const Scalar& s) { bitwise_and(a, s, (Mat&)a); return (Mat_<_Tp>&)a; -} - +} + static inline Mat& operator |= (const Mat& a, const Mat& b) { bitwise_or(a, b, (Mat&)a); @@ -1579,22 +1623,22 @@ static inline Mat& operator |= (const Mat& a, const Scalar& s) { bitwise_or(a, s, (Mat&)a); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator |= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) { bitwise_or(a, b, (Mat&)a); return (Mat_<_Tp>&)a; -} +} template static inline Mat_<_Tp>& operator |= (const Mat_<_Tp>& a, const Scalar& s) { bitwise_or(a, s, (Mat&)a); return (Mat_<_Tp>&)a; -} - +} + static inline Mat& operator ^= (const Mat& a, const Mat& b) { bitwise_xor(a, b, (Mat&)a); @@ -1605,39 +1649,39 @@ static inline Mat& operator ^= (const Mat& a, const Scalar& s) { bitwise_xor(a, s, (Mat&)a); return (Mat&)a; -} +} template static inline Mat_<_Tp>& operator ^= (const Mat_<_Tp>& a, const Mat_<_Tp>& b) { bitwise_xor(a, b, (Mat&)a); return (Mat_<_Tp>&)a; -} +} template static inline Mat_<_Tp>& operator ^= (const Mat_<_Tp>& a, const Scalar& s) { bitwise_xor(a, s, (Mat&)a); return (Mat_<_Tp>&)a; -} +} /////////////////////////////// Miscellaneous operations ////////////////////////////// - + template void split(const Mat& src, vector >& mv) { split(src, (vector&)mv ); } ////////////////////////////////////////////////////////////// - + template inline MatExpr Mat_<_Tp>::zeros(int rows, int cols) { return Mat::zeros(rows, cols, DataType<_Tp>::type); } - + template inline MatExpr Mat_<_Tp>::zeros(Size sz) { return Mat::zeros(sz, DataType<_Tp>::type); -} - +} + template inline MatExpr Mat_<_Tp>::ones(int rows, int cols) { return Mat::ones(rows, cols, DataType<_Tp>::type); @@ -1646,8 +1690,8 @@ template inline MatExpr Mat_<_Tp>::ones(int rows, int cols) template inline MatExpr Mat_<_Tp>::ones(Size sz) { return Mat::ones(sz, DataType<_Tp>::type); -} - +} + template inline MatExpr Mat_<_Tp>::eye(int rows, int cols) { return Mat::eye(rows, cols, DataType<_Tp>::type); @@ -1656,8 +1700,8 @@ template inline MatExpr Mat_<_Tp>::eye(int rows, int cols) template inline MatExpr Mat_<_Tp>::eye(Size sz) { return Mat::eye(sz, DataType<_Tp>::type); -} - +} + //////////////////////////////// Iterators & Comma initializers ////////////////////////////////// inline MatConstIterator::MatConstIterator() @@ -1699,7 +1743,7 @@ inline MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) int idx[]={_pt.y, _pt.x}; seek(idx); } - + inline MatConstIterator::MatConstIterator(const MatConstIterator& it) : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) {} @@ -1712,7 +1756,7 @@ inline MatConstIterator& MatConstIterator::operator = (const MatConstIterator& i } inline uchar* MatConstIterator::operator *() const { return ptr; } - + inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) { if( !m || ofs == 0 ) @@ -1735,7 +1779,7 @@ inline MatConstIterator& MatConstIterator::operator --() if( m && (ptr -= elemSize) < sliceStart ) { ptr += elemSize; - seek(-1, true); + seek(-1, true); } return *this; } @@ -1752,7 +1796,7 @@ inline MatConstIterator& MatConstIterator::operator ++() if( m && (ptr += elemSize) >= sliceEnd ) { ptr -= elemSize; - seek(1, true); + seek(1, true); } return *this; } @@ -1835,10 +1879,10 @@ template inline MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int template inline MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, Point _pt) : MatConstIterator_<_Tp>(_m, _pt) {} - + template inline MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, const int* _idx) : MatConstIterator_<_Tp>(_m, _idx) {} - + template inline MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) : MatConstIterator_<_Tp>(it) {} @@ -1929,8 +1973,8 @@ operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) template static inline bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ return a.m != b.m || a.ptr != b.ptr; } - +{ return a.m != b.m || a.ptr != b.ptr; } + static inline bool operator < (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr < b.ptr; } @@ -1938,7 +1982,7 @@ operator < (const MatConstIterator& a, const MatConstIterator& b) static inline bool operator > (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr > b.ptr; } - + static inline bool operator <= (const MatConstIterator& a, const MatConstIterator& b) { return a.ptr <= b.ptr; } @@ -1957,7 +2001,7 @@ static inline MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator static inline MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) { MatConstIterator b = a; return b += -ofs; } - + template static inline MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } @@ -1965,14 +2009,14 @@ operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) template static inline MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) { MatConstIterator t = (const MatConstIterator&)a + ofs; return (MatConstIterator_<_Tp>&)t; } - + template static inline MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatConstIterator_<_Tp>&)t; } inline uchar* MatConstIterator::operator [](ptrdiff_t i) const { return *(*this + i); } - + template inline _Tp MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const { return *(_Tp*)MatConstIterator::operator [](i); } @@ -1987,7 +2031,7 @@ operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) template static inline MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) { MatConstIterator t = (const MatConstIterator&)a - ofs; return (MatIterator_<_Tp>&)t; } - + template inline _Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const { return *(*this + i); } @@ -2023,8 +2067,8 @@ template inline MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() co { CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); return Mat_<_Tp>(*this->it.m); -} - +} + template static inline MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) { @@ -2080,12 +2124,12 @@ inline SparseMat SparseMat::clone() const } -inline void SparseMat::assignTo( SparseMat& m, int type ) const +inline void SparseMat::assignTo( SparseMat& m, int _type ) const { - if( type < 0 ) + if( _type < 0 ) m = *this; else - convertTo(m, type); + convertTo(m, _type); } inline void SparseMat::addref() @@ -2166,7 +2210,7 @@ inline size_t SparseMat::hash(const int* idx) const template inline _Tp& SparseMat::ref(int i0, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); } - + template inline _Tp& SparseMat::ref(int i0, int i1, size_t* hashval) { return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); } @@ -2180,8 +2224,8 @@ template inline _Tp SparseMat::value(int i0, size_t* hashval) cons { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); return p ? *p : _Tp(); -} - +} + template inline _Tp SparseMat::value(int i0, int i1, size_t* hashval) const { const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); @@ -2202,7 +2246,7 @@ template inline _Tp SparseMat::value(const int* idx, size_t* hashv template inline const _Tp* SparseMat::find(int i0, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); } - + template inline const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const { return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); } @@ -2232,23 +2276,23 @@ inline SparseMatConstIterator SparseMat::begin() const inline SparseMatIterator SparseMat::end() { SparseMatIterator it(this); it.seekEnd(); return it; } - + inline SparseMatConstIterator SparseMat::end() const { SparseMatConstIterator it(this); it.seekEnd(); return it; } - + template inline SparseMatIterator_<_Tp> SparseMat::begin() { return SparseMatIterator_<_Tp>(this); } - + template inline SparseMatConstIterator_<_Tp> SparseMat::begin() const { return SparseMatConstIterator_<_Tp>(this); } - + template inline SparseMatIterator_<_Tp> SparseMat::end() { SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } template inline SparseMatConstIterator_<_Tp> SparseMat::end() const { SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } - - + + inline SparseMatConstIterator::SparseMatConstIterator() : m(0), hashidx(0), ptr(0) { @@ -2260,7 +2304,7 @@ inline SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterat } static inline bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ return it1.m == it2.m && it1.hashidx == it2.hashidx && it1.ptr == it2.ptr; } +{ return it1.m == it2.m && it1.ptr == it2.ptr; } static inline bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) { return !(it1 == it2); } @@ -2293,7 +2337,7 @@ inline SparseMatConstIterator SparseMatConstIterator::operator ++(int) return it; } - + inline void SparseMatConstIterator::seekEnd() { if( m && m->hdr ) @@ -2302,7 +2346,7 @@ inline void SparseMatConstIterator::seekEnd() ptr = 0; } } - + inline SparseMatIterator::SparseMatIterator() {} @@ -2439,8 +2483,8 @@ SparseMat_<_Tp>::ref(int i0, size_t* hashval) template inline _Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const -{ return SparseMat::value<_Tp>(i0, hashval); } - +{ return SparseMat::value<_Tp>(i0, hashval); } + template inline _Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) { return SparseMat::ref<_Tp>(i0, i1, hashval); } @@ -2473,7 +2517,7 @@ template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begi template inline SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() { SparseMatIterator_<_Tp> it(this); it.seekEnd(); return it; } - + template inline SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const { SparseMatConstIterator_<_Tp> it(this); it.seekEnd(); return it; } @@ -2493,7 +2537,9 @@ SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterat template inline SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) -{ return ((SparseMatConstIterator&)*this = it); } +{ return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); } template inline const _Tp& SparseMatConstIterator_<_Tp>::operator *() const @@ -2530,7 +2576,9 @@ SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) template inline SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) -{ return ((SparseMatIterator&)*this = it); } +{ return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); } template inline _Tp& SparseMatIterator_<_Tp>::operator *() const @@ -2550,7 +2598,7 @@ SparseMatIterator_<_Tp>::operator ++(int) SparseMatConstIterator::operator ++(); return it; } - + } #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/opengl_interop.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/opengl_interop.hpp new file mode 100644 index 0000000..24aa546 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/opengl_interop.hpp @@ -0,0 +1,335 @@ +/*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. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., 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 GpuMaterials provided with the distribution. +// +// * The name of the copyright holders 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 __OPENCV_OPENGL_INTEROP_HPP__ +#define __OPENCV_OPENGL_INTEROP_HPP__ + +#ifdef __cplusplus + +#include "opencv2/core/core.hpp" + +namespace cv +{ +//! Smart pointer for OpenGL buffer memory with reference counting. +class CV_EXPORTS GlBuffer +{ +public: + enum Usage + { + ARRAY_BUFFER = 0x8892, // buffer will use for OpenGL arrays (vertices, colors, normals, etc) + TEXTURE_BUFFER = 0x88EC // buffer will ise for OpenGL textures + }; + + //! create empty buffer + explicit GlBuffer(Usage usage); + + //! create buffer + GlBuffer(int rows, int cols, int type, Usage usage); + GlBuffer(Size size, int type, Usage usage); + + //! copy from host/device memory + GlBuffer(InputArray mat, Usage usage); + + void create(int rows, int cols, int type, Usage usage); + void create(Size size, int type, Usage usage); + void create(int rows, int cols, int type); + void create(Size size, int type); + + void release(); + + //! copy from host/device memory + void copyFrom(InputArray mat); + + void bind() const; + void unbind() const; + + //! map to host memory + Mat mapHost(); + void unmapHost(); + + //! map to device memory + gpu::GpuMat mapDevice(); + void unmapDevice(); + + inline int rows() const { return rows_; } + inline int cols() const { return cols_; } + inline Size size() const { return Size(cols_, rows_); } + inline bool empty() const { return rows_ == 0 || cols_ == 0; } + + inline int type() const { return type_; } + inline int depth() const { return CV_MAT_DEPTH(type_); } + inline int channels() const { return CV_MAT_CN(type_); } + inline int elemSize() const { return CV_ELEM_SIZE(type_); } + inline int elemSize1() const { return CV_ELEM_SIZE1(type_); } + + inline Usage usage() const { return usage_; } + + class Impl; +private: + int rows_; + int cols_; + int type_; + Usage usage_; + + Ptr impl_; +}; + +template <> CV_EXPORTS void Ptr::delete_obj(); + +//! Smart pointer for OpenGL 2d texture memory with reference counting. +class CV_EXPORTS GlTexture +{ +public: + //! create empty texture + GlTexture(); + + //! create texture + GlTexture(int rows, int cols, int type); + GlTexture(Size size, int type); + + //! copy from host/device memory + explicit GlTexture(InputArray mat, bool bgra = true); + + void create(int rows, int cols, int type); + void create(Size size, int type); + void release(); + + //! copy from host/device memory + void copyFrom(InputArray mat, bool bgra = true); + + void bind() const; + void unbind() const; + + inline int rows() const { return rows_; } + inline int cols() const { return cols_; } + inline Size size() const { return Size(cols_, rows_); } + inline bool empty() const { return rows_ == 0 || cols_ == 0; } + + inline int type() const { return type_; } + inline int depth() const { return CV_MAT_DEPTH(type_); } + inline int channels() const { return CV_MAT_CN(type_); } + inline int elemSize() const { return CV_ELEM_SIZE(type_); } + inline int elemSize1() const { return CV_ELEM_SIZE1(type_); } + + class Impl; +private: + int rows_; + int cols_; + int type_; + + Ptr impl_; + GlBuffer buf_; +}; + +template <> CV_EXPORTS void Ptr::delete_obj(); + +//! OpenGL Arrays +class CV_EXPORTS GlArrays +{ +public: + inline GlArrays() + : vertex_(GlBuffer::ARRAY_BUFFER), color_(GlBuffer::ARRAY_BUFFER), bgra_(true), normal_(GlBuffer::ARRAY_BUFFER), texCoord_(GlBuffer::ARRAY_BUFFER) + { + } + + void setVertexArray(InputArray vertex); + inline void resetVertexArray() { vertex_.release(); } + + void setColorArray(InputArray color, bool bgra = true); + inline void resetColorArray() { color_.release(); } + + void setNormalArray(InputArray normal); + inline void resetNormalArray() { normal_.release(); } + + void setTexCoordArray(InputArray texCoord); + inline void resetTexCoordArray() { texCoord_.release(); } + + void bind() const; + void unbind() const; + + inline int rows() const { return vertex_.rows(); } + inline int cols() const { return vertex_.cols(); } + inline Size size() const { return vertex_.size(); } + inline bool empty() const { return vertex_.empty(); } + +private: + GlBuffer vertex_; + GlBuffer color_; + bool bgra_; + GlBuffer normal_; + GlBuffer texCoord_; +}; + +//! OpenGL Font +class CV_EXPORTS GlFont +{ +public: + enum Weight + { + WEIGHT_LIGHT = 300, + WEIGHT_NORMAL = 400, + WEIGHT_SEMIBOLD = 600, + WEIGHT_BOLD = 700, + WEIGHT_BLACK = 900 + }; + + enum Style + { + STYLE_NORMAL = 0, + STYLE_ITALIC = 1, + STYLE_UNDERLINE = 2 + }; + + static Ptr get(const std::string& family, int height = 12, Weight weight = WEIGHT_NORMAL, Style style = STYLE_NORMAL); + + void draw(const char* str, int len) const; + + inline const std::string& family() const { return family_; } + inline int height() const { return height_; } + inline Weight weight() const { return weight_; } + inline Style style() const { return style_; } + +private: + GlFont(const std::string& family, int height, Weight weight, Style style); + + std::string family_; + int height_; + Weight weight_; + Style style_; + + unsigned int base_; + + GlFont(const GlFont&); + GlFont& operator =(const GlFont&); +}; + +//! render functions + +//! render texture rectangle in window +CV_EXPORTS void render(const GlTexture& tex, + Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), + Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); + +//! render mode +namespace RenderMode { + enum { + POINTS = 0x0000, + LINES = 0x0001, + LINE_LOOP = 0x0002, + LINE_STRIP = 0x0003, + TRIANGLES = 0x0004, + TRIANGLE_STRIP = 0x0005, + TRIANGLE_FAN = 0x0006, + QUADS = 0x0007, + QUAD_STRIP = 0x0008, + POLYGON = 0x0009 + }; +} + +//! render OpenGL arrays +CV_EXPORTS void render(const GlArrays& arr, int mode = RenderMode::POINTS, Scalar color = Scalar::all(255)); + +CV_EXPORTS void render(const std::string& str, const Ptr& font, Scalar color, Point2d pos); + +//! OpenGL camera +class CV_EXPORTS GlCamera +{ +public: + GlCamera(); + + void lookAt(Point3d eye, Point3d center, Point3d up); + void setCameraPos(Point3d pos, double yaw, double pitch, double roll); + + void setScale(Point3d scale); + + void setProjectionMatrix(const Mat& projectionMatrix, bool transpose = true); + void setPerspectiveProjection(double fov, double aspect, double zNear, double zFar); + void setOrthoProjection(double left, double right, double bottom, double top, double zNear, double zFar); + + void setupProjectionMatrix() const; + void setupModelViewMatrix() const; + +private: + Point3d eye_; + Point3d center_; + Point3d up_; + + Point3d pos_; + double yaw_; + double pitch_; + double roll_; + + bool useLookAtParams_; + + Point3d scale_; + + Mat projectionMatrix_; + + double fov_; + double aspect_; + + double left_; + double right_; + double bottom_; + double top_; + + double zNear_; + double zFar_; + + bool perspectiveProjection_; +}; + +inline void GlBuffer::create(Size _size, int _type, Usage _usage) { create(_size.height, _size.width, _type, _usage); } +inline void GlBuffer::create(int _rows, int _cols, int _type) { create(_rows, _cols, _type, usage()); } +inline void GlBuffer::create(Size _size, int _type) { create(_size.height, _size.width, _type, usage()); } +inline void GlTexture::create(Size _size, int _type) { create(_size.height, _size.width, _type); } + +namespace gpu +{ + //! set a CUDA device to use OpenGL interoperability + CV_EXPORTS void setGlDevice(int device = 0); +} +} // namespace cv + +#endif // __cplusplus + +#endif // __OPENCV_OPENGL_INTEROP_HPP__ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/operations.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/operations.hpp old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/operations.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/operations.hpp index 999a7d2..4b6e606 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/operations.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/operations.hpp @@ -48,12 +48,21 @@ #include #endif // SKIP_INCLUDES + #ifdef __cplusplus /////// exchange-add operation for atomic operations on reference counters /////// -#ifdef __GNUC__ - - #if __GNUC__*10 + __GNUC_MINOR__ >= 42 +#if defined __INTEL_COMPILER && !(defined WIN32 || defined _WIN32) // atomic increment on the linux version of the Intel(tm) compiler + #define CV_XADD(addr,delta) _InterlockedExchangeAdd(const_cast(reinterpret_cast(addr)), delta) +#elif defined __GNUC__ + + #if defined __clang__ && __clang_major__ >= 3 + #ifdef __ATOMIC_SEQ_CST + #define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), (delta), __ATOMIC_SEQ_CST) + #else + #define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), (delta), 5) + #endif + #elif __GNUC__*10 + __GNUC_MINOR__ >= 42 #if !defined WIN32 && (defined __i486__ || defined __i586__ || \ defined __i686__ || defined __MMX__ || defined __SSE__ || defined __ppc__) @@ -71,26 +80,26 @@ #define CV_XADD __exchange_and_add #endif #endif - -#elif defined WIN32 || defined _WIN32 - #define WIN32_MEAN_AND_LEAN - #include - #undef min - #undef max - #undef abs - #define CV_XADD(addr,delta) InterlockedExchangeAdd((long volatile*)(addr), (delta)) -#else +#elif defined WIN32 || defined _WIN32 || defined WINCE + namespace cv { CV_EXPORTS int _interlockedExchangeAdd(int* addr, int delta); } + #define CV_XADD cv::_interlockedExchangeAdd + +#else static inline int CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } - #endif #include +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4127) //conditional expression is constant +#endif + namespace cv { - + using std::cos; using std::sin; using std::max; @@ -100,7 +109,7 @@ using std::log; using std::pow; using std::sqrt; - + /////////////// saturate_cast (used in image & signal processing) /////////////////// template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } @@ -179,7 +188,7 @@ template<> inline int saturate_cast(double v) { return cvRound(v); } // we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. template<> inline unsigned saturate_cast(float v){ return cvRound(v); } template<> inline unsigned saturate_cast(double v) { return cvRound(v); } - + inline int fast_abs(uchar v) { return v; } inline int fast_abs(schar v) { return std::abs((int)v); } inline int fast_abs(ushort v) { return v; } @@ -279,7 +288,7 @@ template inline Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1 for(int i = 10; i < channels; i++) val[i] = _Tp(0); } - + template inline Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, @@ -344,7 +353,7 @@ template inline _Tp Matx<_Tp, m, n>::dot(const Matx< return s; } - + template inline double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const { double s = 0; @@ -355,7 +364,7 @@ template inline double Matx<_Tp, m, n>::ddot(const M template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const Matx<_Tp,MIN(m,n),1>& d) +Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) { Matx<_Tp,m,n> M; for(int i = 0; i < MIN(m,n); i++) @@ -371,7 +380,7 @@ Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) cv::randu(matM, Scalar(a), Scalar(b)); return M; } - + template inline Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) { @@ -380,7 +389,7 @@ Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) cv::randn(matM, Scalar(a), Scalar(b)); return M; } - + template template inline Matx<_Tp, m, n>::operator Matx() const { @@ -388,7 +397,7 @@ inline Matx<_Tp, m, n>::operator Matx() const for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); return M; } - + template template inline Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const @@ -418,7 +427,7 @@ Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const return Matx<_Tp, 1, n>(&val[i*n]); } - + template inline Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const { @@ -429,9 +438,9 @@ Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const return v; } - + template inline -Matx<_Tp, MIN(m,n), 1> Matx<_Tp, m, n>::diag() const +typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const { diag_type d; for( int i = 0; i < MIN(m, n); i++ ) @@ -439,7 +448,7 @@ Matx<_Tp, MIN(m,n), 1> Matx<_Tp, m, n>::diag() const return d; } - + template inline const _Tp& Matx<_Tp, m, n>::operator ()(int i, int j) const { @@ -447,7 +456,7 @@ const _Tp& Matx<_Tp, m, n>::operator ()(int i, int j) const return this->val[i*n + j]; } - + template inline _Tp& Matx<_Tp, m, n>::operator ()(int i, int j) { @@ -471,23 +480,23 @@ _Tp& Matx<_Tp, m, n>::operator ()(int i) return val[i]; } - + template static inline Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); return a; -} +} + - template static inline Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); return a; -} +} template inline @@ -497,31 +506,31 @@ Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_Add val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); } - + template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) { for( int i = 0; i < m*n; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); } - - + + template template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) { for( int i = 0; i < m*n; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] * alpha); } - - + + template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) { for( int i = 0; i < m*n; i++ ) val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); } - - + + template template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) { @@ -534,8 +543,8 @@ Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_Mat val[i*n + j] = s; } } - - + + template inline Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) { @@ -544,20 +553,20 @@ Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) val[i*n + j] = a(j, i); } - + template static inline Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { return Matx<_Tp, m, n>(a, b, Matx_AddOp()); } - - + + template static inline Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { return Matx<_Tp, m, n>(a, b, Matx_SubOp()); -} - +} + template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) @@ -565,15 +574,15 @@ Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; -} - +} + template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) { for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; -} +} template static inline Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) @@ -581,44 +590,44 @@ Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) for( int i = 0; i < m*n; i++ ) a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); return a; -} +} template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} +} template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} +} template static inline Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - +} + template static inline Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} +} template static inline Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} +} template static inline Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) { return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - +} + template static inline Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) { @@ -632,7 +641,15 @@ Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); } - + +template static inline +Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) +{ + Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); + return reinterpret_cast&>(c); +} + + template static inline Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) { @@ -640,13 +657,13 @@ Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) return Point_<_Tp>(tmp.val[0], tmp.val[1]); } - + template static inline Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a*Vec<_Tp,3>(b.x, b.y, b.z); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} +} template static inline @@ -654,22 +671,31 @@ Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a*Vec<_Tp,3>(b.x, b.y, 1); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} +} + - template static inline Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) { return a*Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); -} +} + - template static inline Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) { - return Scalar(a*Matx<_Tp, 4, 1>(b[0],b[1],b[2],b[3])); -} - + Matx c(Matx(a), b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + + +static inline +Scalar operator * (const Matx& a, const Scalar& b) +{ + Matx c(a, b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + template inline Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const @@ -677,11 +703,11 @@ Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); } - + CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); template struct CV_EXPORTS Matx_DetOp @@ -697,7 +723,7 @@ template struct CV_EXPORTS Matx_DetOp return p; } }; - + template struct CV_EXPORTS Matx_DetOp<_Tp, 1> { @@ -726,13 +752,13 @@ template struct CV_EXPORTS Matx_DetOp<_Tp, 3> a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); } }; - + template static inline double determinant(const Matx<_Tp, m, m>& a) { - return Matx_DetOp<_Tp, m>()(a); + return Matx_DetOp<_Tp, m>()(a); } - + template static inline double trace(const Matx<_Tp, m, n>& a) @@ -741,9 +767,9 @@ double trace(const Matx<_Tp, m, n>& a) for( int i = 0; i < std::min(m, n); i++ ) s += a(i,i); return s; -} +} + - template inline Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const { @@ -756,19 +782,19 @@ template struct CV_EXPORTS Matx_FastInvOp bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const { Matx<_Tp, m, m> temp = a; - + // assume that b is all 0's on input => make it a unity matrix for( int i = 0; i < m; i++ ) b(i, i) = (_Tp)1; - + if( method == DECOMP_CHOLESKY ) return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); - + return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; } }; - + template struct CV_EXPORTS Matx_FastInvOp<_Tp, 2> { bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int) const @@ -785,7 +811,7 @@ template struct CV_EXPORTS Matx_FastInvOp<_Tp, 2> } }; - + template struct CV_EXPORTS Matx_FastInvOp<_Tp, 3> { bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int) const @@ -797,11 +823,11 @@ template struct CV_EXPORTS Matx_FastInvOp<_Tp, 3> b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; - + b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; - + b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; @@ -809,7 +835,7 @@ template struct CV_EXPORTS Matx_FastInvOp<_Tp, 3> } }; - + template inline Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method) const { @@ -820,7 +846,7 @@ Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method) const else { Mat A(*this, false), B(b, false); - ok = (0.0 == invert(A, B, method)); + ok = (invert(A, B, method) != 0); } return ok ? b : Matx<_Tp, n, m>::zeros(); } @@ -835,7 +861,7 @@ template struct CV_EXPORTS Matx_FastSolveOp x = b; if( method == DECOMP_CHOLESKY ) return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); - + return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; } }; @@ -844,7 +870,7 @@ template struct CV_EXPORTS Matx_FastSolveOp template struct CV_EXPORTS Matx_FastSolveOp<_Tp, 2, 1> { bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, - Matx<_Tp, 2, 1>& x, int method) const + Matx<_Tp, 2, 1>& x, int) const { _Tp d = determinant(a); if( d == 0 ) @@ -856,32 +882,32 @@ template struct CV_EXPORTS Matx_FastSolveOp<_Tp, 2, 1> } }; - + template struct CV_EXPORTS Matx_FastSolveOp<_Tp, 3, 1> { bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, - Matx<_Tp, 3, 1>& x, int method) const + Matx<_Tp, 3, 1>& x, int) const { - _Tp d = determinant(a); + _Tp d = (_Tp)determinant(a); if( d == 0 ) return false; d = 1/d; x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); - + x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); - + x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); return true; } }; - - + + template template inline Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const { @@ -898,17 +924,25 @@ Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) c return ok ? x : Matx<_Tp, n, l>::zeros(); } - +template inline +Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const +{ + Matx<_Tp, n, 1> x = solve(reinterpret_cast&>(rhs), method); + return reinterpret_cast&>(x); +} + template static inline _AccTp normL2Sqr(const _Tp* a, int n) { _AccTp s = 0; - int i; - for( i = 0; i <= n - 4; i += 4 ) + int i=0; + #if CV_ENABLE_UNROLLED + for( ; i <= n - 4; i += 4 ) { _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; s += v0*v0 + v1*v1 + v2*v2 + v3*v3; } +#endif for( ; i < n; i++ ) { _AccTp v = a[i]; @@ -922,12 +956,14 @@ template static inline _AccTp normL1(const _Tp* a, int n) { _AccTp s = 0; - int i; - for( i = 0; i <= n - 4; i += 4 ) + int i = 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) { s += (_AccTp)fast_abs(a[i]) + (_AccTp)fast_abs(a[i+1]) + (_AccTp)fast_abs(a[i+2]) + (_AccTp)fast_abs(a[i+3]); } +#endif for( ; i < n; i++ ) s += fast_abs(a[i]); return s; @@ -942,21 +978,23 @@ _AccTp normInf(const _Tp* a, int n) s = std::max(s, (_AccTp)fast_abs(a[i])); return s; } - - + + template static inline _AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) { _AccTp s = 0; - int i; - for( i = 0; i <= n - 4; i += 4 ) + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) { - _AccTp v0 = a[i] - b[i], v1 = a[i+1] - b[i+1], v2 = a[i+2] - b[i+2], v3 = a[i+3] - b[i+3]; + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); s += v0*v0 + v1*v1 + v2*v2 + v3*v3; } +#endif for( ; i < n; i++ ) { - _AccTp v = a[i] - b[i]; + _AccTp v = _AccTp(a[i] - b[i]); s += v*v; } return s; @@ -967,7 +1005,7 @@ CV_EXPORTS float normL1_(const float* a, const float* b, int n); CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); - + template<> inline float normL2Sqr(const float* a, const float* b, int n) { if( n >= 8 ) @@ -981,20 +1019,22 @@ template<> inline float normL2Sqr(const float* a, const float* b, int n) return s; } - + template static inline _AccTp normL1(const _Tp* a, const _Tp* b, int n) { _AccTp s = 0; - int i; - for( i = 0; i <= n - 4; i += 4 ) + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) { - _AccTp v0 = a[i] - b[i], v1 = a[i+1] - b[i+1], v2 = a[i+2] - b[i+2], v3 = a[i+3] - b[i+3]; + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); } +#endif for( ; i < n; i++ ) { - _AccTp v = a[i] - b[i]; + _AccTp v = _AccTp(a[i] - b[i]); s += std::abs(v); } return s; @@ -1016,7 +1056,7 @@ template<> inline float normL1(const float* a, const float* b, int n) template<> inline int normL1(const uchar* a, const uchar* b, int n) { return normL1_(a, b, n); -} +} template static inline _AccTp normInf(const _Tp* a, const _Tp* b, int n) @@ -1029,7 +1069,7 @@ _AccTp normInf(const _Tp* a, const _Tp* b, int n) } return s; } - + template static inline double norm(const Matx<_Tp, m, n>& M) @@ -1037,16 +1077,16 @@ double norm(const Matx<_Tp, m, n>& M) return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); } - + template static inline double norm(const Matx<_Tp, m, n>& M, int normType) { - return normType == NORM_INF ? (double)normInf<_Tp, DataType<_Tp>::work_type>(M.val, m*n) : - normType == NORM_L1 ? (double)normL1<_Tp, DataType<_Tp>::work_type>(M.val, m*n) : - std::sqrt((double)normL2Sqr<_Tp, DataType<_Tp>::work_type>(M.val, m*n)); + return normType == NORM_INF ? (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n) : + normType == NORM_L1 ? (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n) : + std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); } - - + + template static inline bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { @@ -1054,7 +1094,7 @@ bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) if( a.val[i] != b.val[i] ) return false; return true; } - + template static inline bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) { @@ -1087,7 +1127,7 @@ Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const { CV_DbgAssert( idx == n*m ); return *dst; -} +} /////////////////////////// short vector (Vec) ///////////////////////////// @@ -1139,11 +1179,11 @@ template inline Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v8, _Tp v9) : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} - + template inline Vec<_Tp, cn>::Vec(const _Tp* values) : Matx<_Tp, cn, 1>(values) {} - + template inline Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) : Matx<_Tp, cn, 1>(m.val) @@ -1162,8 +1202,8 @@ Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_Sub template template inline Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) : Matx<_Tp, cn, 1>(a, alpha, op) -{} - +{} + template inline Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) { Vec v; @@ -1186,8 +1226,8 @@ template Vec<_Tp, 2> conjugate(const Vec<_Tp, 2>& v) template Vec<_Tp, 4> conjugate(const Vec<_Tp, 4>& v) { return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); -} - +} + template<> inline Vec Vec::conj() const { return conjugate(*this); @@ -1207,13 +1247,13 @@ template<> inline Vec Vec::conj() const { return conjugate(*this); } - -template inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>& v) const + +template inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const { CV_Error(CV_StsError, "for arbitrary-size vector there is no cross-product defined"); return Vec<_Tp, cn>(); } - + template template inline Vec<_Tp, cn>::operator Vec() const { @@ -1236,7 +1276,7 @@ template inline const _Tp& Vec<_Tp, cn>::operator [](int i CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; } - + template inline _Tp& Vec<_Tp, cn>::operator [](int i) { CV_DbgAssert( (unsigned)i < (unsigned)cn ); @@ -1253,15 +1293,15 @@ template inline _Tp& Vec<_Tp, cn>::operator ()(int i) { CV_DbgAssert( (unsigned)i < (unsigned)cn ); return this->val[i]; -} - +} + template static inline Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) { for( int i = 0; i < cn; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); return a; -} +} template static inline Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) @@ -1269,8 +1309,8 @@ operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) for( int i = 0; i < cn; i++ ) a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); return a; -} - +} + template static inline Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) { @@ -1298,7 +1338,7 @@ Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) a[i] = saturate_cast<_Tp>(a[i]*alpha); return a; } - + template static inline Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) { @@ -1315,7 +1355,7 @@ Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) a[i] = saturate_cast<_Tp>(a[i]*ialpha); return a; } - + template static inline Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) { @@ -1332,8 +1372,8 @@ Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) for( int i = 0; i < cn; i++ ) a[i] = saturate_cast<_Tp>(a[i]*ialpha); return a; -} - +} + template static inline Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) { @@ -1368,7 +1408,7 @@ template static inline Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) { return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} +} template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) @@ -1380,14 +1420,14 @@ template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) { return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); -} +} template static inline Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) { return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - +} + template static inline Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) { @@ -1403,13 +1443,13 @@ template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, con saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); } - + template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) { v1 = v1 * v2; return v1; } - + template<> inline Vec Vec::cross(const Vec& v) const { return Vec(val[1]*v.val[2] - val[2]*v.val[1], @@ -1429,14 +1469,14 @@ template inline Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& double nv = norm(v); return v * (nv ? 1./nv : 0.); } - + template static inline VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) { VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); return (commaInitializer, val); } - + template inline VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) : MatxCommaInitializer<_Tp, cn, 1>(_vec) @@ -1455,7 +1495,7 @@ Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const { CV_DbgAssert( this->idx == cn ); return *this->dst; -} +} //////////////////////////////// Complex ////////////////////////////// @@ -1472,8 +1512,8 @@ bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) template static inline bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ return a.re != b.re || a.im != b.im; } - +{ return a.re != b.re || a.im != b.im; } + template static inline Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re + b.re, a.im + b.im ); } @@ -1599,6 +1639,9 @@ template inline _Tp Point_<_Tp>::dot(const Point_& pt) const template inline double Point_<_Tp>::ddot(const Point_& pt) const { return (double)x*pt.x + (double)y*pt.y; } +template inline double Point_<_Tp>::cross(const Point_& pt) const +{ return (double)x*pt.y - (double)y*pt.x; } + template static inline Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) { @@ -1637,8 +1680,8 @@ operator *= (Point_<_Tp>& a, double b) a.x = saturate_cast<_Tp>(a.x*b); a.y = saturate_cast<_Tp>(a.y*b); return a; -} - +} + template static inline double norm(const Point_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); } @@ -1662,7 +1705,7 @@ template static inline Point_<_Tp> operator * (const Point_<_Tp>& template static inline Point_<_Tp> operator * (int a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } - + template static inline Point_<_Tp> operator * (const Point_<_Tp>& a, float b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } @@ -1673,8 +1716,8 @@ template static inline Point_<_Tp> operator * (const Point_<_Tp>& { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template static inline Point_<_Tp> operator * (double a, const Point_<_Tp>& b) -{ return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } - +{ return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } + //////////////////////////////// 3D Point //////////////////////////////// template inline Point3_<_Tp>::Point3_() : x(0), y(0), z(0) {} @@ -1701,7 +1744,7 @@ template inline _Tp Point3_<_Tp>::dot(const Point3_& pt) const { return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); } template inline double Point3_<_Tp>::ddot(const Point3_& pt) const { return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; } - + template inline Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const { return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); @@ -1715,7 +1758,7 @@ operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) a.z = saturate_cast<_Tp>(a.z + b.z); return a; } - + template static inline Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) { @@ -1723,8 +1766,8 @@ operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) a.y = saturate_cast<_Tp>(a.y - b.y); a.z = saturate_cast<_Tp>(a.z - b.z); return a; -} - +} + template static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) { @@ -1750,8 +1793,8 @@ operator *= (Point3_<_Tp>& a, double b) a.y = saturate_cast<_Tp>(a.y*b); a.z = saturate_cast<_Tp>(a.z*b); return a; -} - +} + template static inline double norm(const Point3_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); } @@ -1760,7 +1803,7 @@ template static inline bool operator == (const Point3_<_Tp>& a, co template static inline bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } - + template static inline Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), @@ -1805,7 +1848,7 @@ template static inline Point3_<_Tp> operator * (double a, const Po { return Point3_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a), saturate_cast<_Tp>(b.z*a) ); } - + //////////////////////////////// Size //////////////////////////////// template inline Size_<_Tp>::Size_() @@ -1919,8 +1962,8 @@ template static inline bool operator == (const Rect_<_Tp>& a, cons template static inline bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; -} - +} + template static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) { return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); @@ -1963,7 +2006,7 @@ inline RotatedRect::operator CvBox2D() const CvBox2D box; box.center = center; box.size = size; box.angle = angle; return box; } - + //////////////////////////////// Scalar_ /////////////////////////////// template inline Scalar_<_Tp>::Scalar_() @@ -2078,7 +2121,7 @@ template static inline Scalar_<_Tp> operator - (const Scalar_<_Tp> saturate_cast<_Tp>(-a.val[2]), saturate_cast<_Tp>(-a.val[3])); } - + template static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { @@ -2087,14 +2130,14 @@ operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); } - + template static inline Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a = a*b; return a; -} - +} + template inline Scalar_<_Tp> Scalar_<_Tp>::conj() const { return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0]), @@ -2107,7 +2150,7 @@ template inline bool Scalar_<_Tp>::isReal() const { return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; } - + template static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) { @@ -2115,36 +2158,36 @@ Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) saturate_cast<_Tp>(a.val[1] / alpha), saturate_cast<_Tp>(a.val[2] / alpha), saturate_cast<_Tp>(a.val[3] / alpha)); -} +} template static inline Scalar_ operator / (const Scalar_& a, float alpha) { float s = 1/alpha; return Scalar_(a.val[0]*s, a.val[1]*s, a.val[2]*s, a.val[3]*s); -} +} template static inline Scalar_ operator / (const Scalar_& a, double alpha) { double s = 1/alpha; return Scalar_(a.val[0]*s, a.val[1]*s, a.val[2]*s, a.val[3]*s); -} - +} + template static inline Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) { a = a/alpha; return a; } - + template static inline Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) { _Tp s = a/(b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); return b.conj()*s; -} - +} + template static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { @@ -2157,7 +2200,7 @@ Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) a = a/b; return a; } - + //////////////////////////////// Range ///////////////////////////////// inline Range::Range() : start(0), end(0) {} @@ -2212,8 +2255,8 @@ static inline Range operator - (const Range& r1, int delta) inline Range::operator CvSlice() const { return *this != Range::all() ? cvSlice(start, end) : CV_WHOLE_SEQ; } - - + + //////////////////////////////// Vector //////////////////////////////// // template vector class. It is similar to STL's vector, @@ -2229,7 +2272,7 @@ template class CV_EXPORTS Vector typedef const _Tp* const_iterator; typedef _Tp& reference; typedef const _Tp& const_reference; - + struct CV_EXPORTS Hdr { Hdr() : data(0), datastart(0), refcount(0), size(0), capacity(0) {}; @@ -2239,7 +2282,7 @@ template class CV_EXPORTS Vector size_t size; size_t capacity; }; - + Vector() {} Vector(size_t _size) { resize(_size); } Vector(size_t _size, const _Tp& val) @@ -2250,15 +2293,15 @@ template class CV_EXPORTS Vector } Vector(_Tp* _data, size_t _size, bool _copyData=false) { set(_data, _size, _copyData); } - + template Vector(const Vec<_Tp, n>& vec) - { set((_Tp*)&vec.val[0], n, true); } - + { set((_Tp*)&vec.val[0], n, true); } + Vector(const std::vector<_Tp>& vec, bool _copyData=false) - { set((_Tp*)&vec[0], vec.size(), _copyData); } - + { set(!vec.empty() ? (_Tp*)&vec[0] : 0, vec.size(), _copyData); } + Vector(const Vector& d) { *this = d; } - + Vector(const Vector& d, const Range& r_) { Range r = r_ == Range::all() ? Range(0, d.size()) : r_; @@ -2274,7 +2317,7 @@ template class CV_EXPORTS Vector hdr.capacity = hdr.size = r.size(); } } - + Vector<_Tp>& operator = (const Vector& d) { if( this != &d ) @@ -2286,12 +2329,12 @@ template class CV_EXPORTS Vector } return *this; } - + ~Vector() { release(); } - + Vector<_Tp> clone() const { return hdr.data ? Vector<_Tp>(hdr.data, hdr.size, true) : Vector<_Tp>(); } - + void copyTo(Vector<_Tp>& vec) const { size_t i, sz = size(); @@ -2301,7 +2344,7 @@ template class CV_EXPORTS Vector for( i = 0; i < sz; i++ ) dst[i] = src[i]; } - + void copyTo(std::vector<_Tp>& vec) const { size_t i, sz = size(); @@ -2311,10 +2354,10 @@ template class CV_EXPORTS Vector for( i = 0; i < sz; i++ ) dst[i] = src[i]; } - + operator CvMat() const { return cvMat((int)size(), 1, type(), (void*)hdr.data); } - + _Tp& operator [] (size_t i) { CV_DbgAssert( i < size() ); return hdr.data[i]; } const _Tp& operator [] (size_t i) const { CV_DbgAssert( i < size() ); return hdr.data[i]; } Vector operator() (const Range& r) const { return Vector(*this, r); } @@ -2322,12 +2365,12 @@ template class CV_EXPORTS Vector const _Tp& back() const { CV_DbgAssert(!empty()); return hdr.data[hdr.size-1]; } _Tp& front() { CV_DbgAssert(!empty()); return hdr.data[0]; } const _Tp& front() const { CV_DbgAssert(!empty()); return hdr.data[0]; } - + _Tp* begin() { return hdr.data; } _Tp* end() { return hdr.data + hdr.size; } const _Tp* begin() const { return hdr.data; } const _Tp* end() const { return hdr.data + hdr.size; } - + void addref() { if( hdr.refcount ) CV_XADD(hdr.refcount, 1); } void release() { @@ -2338,7 +2381,7 @@ template class CV_EXPORTS Vector } hdr = Hdr(); } - + void set(_Tp* _data, size_t _size, bool _copyData=false) { if( !_copyData ) @@ -2356,7 +2399,7 @@ template class CV_EXPORTS Vector hdr.size = _size; } } - + void reserve(size_t newCapacity) { _Tp* newData; @@ -2375,7 +2418,7 @@ template class CV_EXPORTS Vector hdr.size = oldSize; hdr.refcount = newRefcount; } - + void resize(size_t newSize) { size_t i; @@ -2388,7 +2431,7 @@ template class CV_EXPORTS Vector hdr.data[i] = _Tp(); hdr.size = newSize; } - + Vector<_Tp>& push_back(const _Tp& elem) { if( hdr.size == hdr.capacity ) @@ -2396,42 +2439,40 @@ template class CV_EXPORTS Vector hdr.data[hdr.size++] = elem; return *this; } - + Vector<_Tp>& pop_back() { if( hdr.size > 0 ) --hdr.size; return *this; } - + size_t size() const { return hdr.size; } size_t capacity() const { return hdr.capacity; } bool empty() const { return hdr.size == 0; } void clear() { resize(0); } int type() const { return DataType<_Tp>::type; } - + protected: Hdr hdr; -}; +}; + - template inline typename DataType<_Tp>::work_type dot(const Vector<_Tp>& v1, const Vector<_Tp>& v2) { typedef typename DataType<_Tp>::work_type _Tw; - size_t i, n = v1.size(); + size_t i = 0, n = v1.size(); assert(v1.size() == v2.size()); _Tw s = 0; const _Tp *ptr1 = &v1[0], *ptr2 = &v2[0]; - for( i = 0; i <= n - 4; i += 4 ) - s += (_Tw)ptr1[i]*ptr2[i] + (_Tw)ptr1[i+1]*ptr2[i+1] + - (_Tw)ptr1[i+2]*ptr2[i+2] + (_Tw)ptr1[i+3]*ptr2[i+3]; for( ; i < n; i++ ) s += (_Tw)ptr1[i]*ptr2[i]; + return s; } - + // Multiply-with-Carry RNG inline RNG::RNG() { state = 0xffffffff; } inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } @@ -2456,7 +2497,7 @@ inline RNG::operator double() unsigned t = next(); return (((uint64)t << 32) | next())*5.4210108624275221700372640043497e-20; } -inline int RNG::uniform(int a, int b) { return a == b ? a : next()%(b - a) + a; } +inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next()%(b - a) + a); } inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } @@ -2489,7 +2530,7 @@ inline Point LineIterator::pos() const p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize); return p; } - + /////////////////////////////// AutoBuffer //////////////////////////////////////// template inline AutoBuffer<_Tp, fixed_size>::AutoBuffer() @@ -2572,20 +2613,20 @@ template inline void Ptr<_Tp>::delete_obj() template inline Ptr<_Tp>::~Ptr() { release(); } -template inline Ptr<_Tp>::Ptr(const Ptr<_Tp>& ptr) +template inline Ptr<_Tp>::Ptr(const Ptr<_Tp>& _ptr) { - obj = ptr.obj; - refcount = ptr.refcount; + obj = _ptr.obj; + refcount = _ptr.refcount; addref(); } -template inline Ptr<_Tp>& Ptr<_Tp>::operator = (const Ptr<_Tp>& ptr) +template inline Ptr<_Tp>& Ptr<_Tp>::operator = (const Ptr<_Tp>& _ptr) { - int* _refcount = ptr.refcount; + int* _refcount = _ptr.refcount; if( _refcount ) CV_XADD(_refcount, 1); release(); - obj = ptr.obj; + obj = _ptr.obj; refcount = _refcount; return *this; } @@ -2598,6 +2639,57 @@ template inline Ptr<_Tp>::operator const _Tp*() const { return obj template inline bool Ptr<_Tp>::empty() const { return obj == 0; } +template template Ptr<_Tp>::Ptr(const Ptr<_Tp2>& p) + : obj(0), refcount(0) +{ + if (p.empty()) + return; + + _Tp* p_casted = dynamic_cast<_Tp*>(p.obj); + if (!p_casted) + return; + + obj = p_casted; + refcount = p.refcount; + addref(); +} + +template template inline Ptr<_Tp2> Ptr<_Tp>::ptr() +{ + Ptr<_Tp2> p; + if( !obj ) + return p; + + _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); + if (!obj_casted) + return p; + + if( refcount ) + CV_XADD(refcount, 1); + + p.obj = obj_casted; + p.refcount = refcount; + return p; +} + +template template inline const Ptr<_Tp2> Ptr<_Tp>::ptr() const +{ + Ptr<_Tp2> p; + if( !obj ) + return p; + + _Tp2* obj_casted = dynamic_cast<_Tp2*>(obj); + if (!obj_casted) + return p; + + if( refcount ) + CV_XADD(refcount, 1); + + p.obj = obj_casted; + p.refcount = refcount; + return p; +} + //// specializied implementations of Ptr::delete_obj() for classic OpenCV types template<> CV_EXPORTS void Ptr::delete_obj(); @@ -2606,7 +2698,7 @@ template<> CV_EXPORTS void Ptr::delete_obj(); template<> CV_EXPORTS void Ptr::delete_obj(); template<> CV_EXPORTS void Ptr::delete_obj(); template<> CV_EXPORTS void Ptr::delete_obj(); - + //////////////////////////////////////// XML & YAML I/O //////////////////////////////////// CV_EXPORTS_W void write( FileStorage& fs, const string& name, int value ); @@ -2786,24 +2878,22 @@ template class CV_EXPORTS VecWriterProxy<_Tp,1> { int _fmt = DataType<_Tp>::fmt; char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' }; - fs->writeRaw( string(fmt), (uchar*)&vec[0], vec.size()*sizeof(_Tp) ); + fs->writeRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, vec.size()*sizeof(_Tp) ); } FileStorage* fs; }; - template static inline void write( FileStorage& fs, const vector<_Tp>& vec ) { VecWriterProxy<_Tp, DataType<_Tp>::fmt != 0> w(&fs); w(vec); } -template static inline FileStorage& -operator << ( FileStorage& fs, const vector<_Tp>& vec ) +template static inline void write( FileStorage& fs, const string& name, + const vector<_Tp>& vec ) { - VecWriterProxy<_Tp, DataType<_Tp>::generic_type == 0> w(&fs); - w(vec); - return fs; + WriteStructContext ws(fs, name, CV_NODE_SEQ+(DataType<_Tp>::fmt != 0 ? CV_NODE_FLOW : 0)); + write(fs, vec); } CV_EXPORTS_W void write( FileStorage& fs, const string& name, const Mat& value ); @@ -2844,8 +2934,8 @@ inline bool FileNode::isNamed() const { return !node ? false : (node->tag & NAME inline size_t FileNode::size() const { int t = type(); - return t == MAP ? ((CvSet*)node->data.map)->active_count : - t == SEQ ? node->data.seq->total : node != 0; + return t == MAP ? (size_t)((CvSet*)node->data.map)->active_count : + t == SEQ ? (size_t)node->data.seq->total : (size_t)!isNone(); } inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; } @@ -2857,7 +2947,7 @@ static inline void read(const FileNode& node, int& value, int default_value) CV_NODE_IS_INT(node.node->tag) ? node.node->data.i : CV_NODE_IS_REAL(node.node->tag) ? cvRound(node.node->data.f) : 0x7fffffff; } - + static inline void read(const FileNode& node, bool& value, bool default_value) { int temp; read(node, temp, (int)default_value); @@ -2887,7 +2977,7 @@ static inline void read(const FileNode& node, short& value, short default_value) int temp; read(node, temp, (int)default_value); value = saturate_cast(temp); } - + static inline void read(const FileNode& node, float& value, float default_value) { value = !node.node ? default_value : @@ -2908,8 +2998,8 @@ static inline void read(const FileNode& node, string& value, const string& defau } CV_EXPORTS_W void read(const FileNode& node, Mat& mat, const Mat& default_mat=Mat() ); -CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat=SparseMat() ); - +CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat=SparseMat() ); + inline FileNode::operator int() const { int value; @@ -2953,7 +3043,7 @@ template class CV_EXPORTS VecReaderProxy } FileNodeIterator* it; }; - + template class CV_EXPORTS VecReaderProxy<_Tp,1> { public: @@ -2963,10 +3053,10 @@ template class CV_EXPORTS VecReaderProxy<_Tp,1> size_t remaining = it->remaining, cn = DataType<_Tp>::channels; int _fmt = DataType<_Tp>::fmt; char fmt[] = { (char)((_fmt>>8)+'1'), (char)_fmt, '\0' }; - size_t remaining1 = remaining/cn; - count = count < remaining1 ? count : remaining1; + size_t remaining1 = remaining/cn; + count = count < remaining1 ? count : remaining1; vec.resize(count); - it->readRaw( string(fmt), (uchar*)&vec[0], count*sizeof(_Tp) ); + it->readRaw( string(fmt), !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp) ); } FileNodeIterator* it; }; @@ -2979,11 +3069,17 @@ read( FileNodeIterator& it, vector<_Tp>& vec, size_t maxCount=(size_t)INT_MAX ) } template static inline void -read( FileNode& node, vector<_Tp>& vec, const vector<_Tp>& default_value=vector<_Tp>() ) +read( const FileNode& node, vector<_Tp>& vec, const vector<_Tp>& default_value=vector<_Tp>() ) { - read( node.begin(), vec ); + if(!node.node) + vec = default_value; + else + { + FileNodeIterator it = node.begin(); + read( it, vec ); + } } - + inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); @@ -3387,7 +3483,7 @@ partition( const vector<_Tp>& _vec, vector& labels, return nclasses; } - + ////////////////////////////////////////////////////////////////////////////// // bridge C++ => C Seq API @@ -3401,7 +3497,7 @@ CV_EXPORTS void seqRemove( CvSeq* seq, int index ); CV_EXPORTS void clearSeq( CvSeq* seq ); CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); -CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); +CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); template inline Seq<_Tp>::Seq() : seq(0) {} template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) @@ -3456,8 +3552,8 @@ template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t c { cvSeqPushMulti(seq, elem, (int)count, 0); } template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 1); } - +{ cvSeqPushMulti(seq, elem, (int)count, 1); } + template inline _Tp& Seq<_Tp>::back() { return *(_Tp*)getSeqElem(seq, -1); } @@ -3486,23 +3582,23 @@ template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) { seqPopMulti(seq, elem, (int)count, 0); } template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 1); } +{ seqPopMulti(seq, elem, (int)count, 1); } template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) { seqInsert(seq, idx, &elem); } - + template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) { CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); seqInsertSlice(seq, idx, &m); } - + template inline void Seq<_Tp>::remove(int idx) { seqRemove(seq, idx); } - + template inline void Seq<_Tp>::remove(const Range& r) { seqRemoveSlice(seq, r); } - + template inline void Seq<_Tp>::copyTo(vector<_Tp>& vec, const Range& range) const { size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; @@ -3521,10 +3617,10 @@ template inline Seq<_Tp>::operator vector<_Tp>() const template inline SeqIterator<_Tp>::SeqIterator() { memset(this, 0, sizeof(*this)); } -template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& seq, bool seekEnd) +template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) { - cvStartReadSeq(seq.seq, this); - index = seekEnd ? seq.seq->total : 0; + cvStartReadSeq(_seq.seq, this); + index = seekEnd ? _seq.seq->total : 0; } template inline void SeqIterator<_Tp>::seek(size_t pos) @@ -3617,12 +3713,13 @@ template struct CV_EXPORTS RTTIImpl static int isInstance(const void* ptr) { static _ClsName dummy; + static void* dummyp = &dummy; union { const void* p; const void** pp; } a, b; - a.p = &dummy; + a.p = dummyp; b.p = ptr; return *a.pp == *b.pp; } @@ -3643,7 +3740,7 @@ template struct CV_EXPORTS RTTIImpl delete obj; return 0; } - + static void write(CvFileStorage* _fs, const char* name, const void* ptr, CvAttrList) { if(ptr && _fs) @@ -3653,7 +3750,7 @@ template struct CV_EXPORTS RTTIImpl ((const _ClsName*)ptr)->write(fs, string(name)); } } - + static void* clone(const void* ptr) { if(!ptr) @@ -3662,7 +3759,7 @@ template struct CV_EXPORTS RTTIImpl } }; - + class CV_EXPORTS Formatter { public: @@ -3686,23 +3783,6 @@ struct CV_EXPORTS Formatted vector params; }; - -/** Writes a point to an output stream in Matlab notation - */ -template inline std::ostream& operator<<(std::ostream& out, const Point_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << "]"; - return out; -} - -/** Writes a point to an output stream in Matlab notation - */ -template inline std::ostream& operator<<(std::ostream& out, const Point3_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; - return out; -} - static inline Formatted format(const Mat& mtx, const char* fmt, const vector& params=vector()) { @@ -3727,7 +3807,7 @@ template static inline Formatted format(const vector Mat my_mat = Mat::eye(3,3,CV_32F); std::cout << my_mat; @endverbatim - */ + */ static inline std::ostream& operator << (std::ostream& out, const Mat& mtx) { Formatter::get()->write(out, mtx); @@ -3740,7 +3820,7 @@ static inline std::ostream& operator << (std::ostream& out, const Mat& mtx) Mat my_mat = Mat::eye(3,3,CV_32F); std::cout << my_mat; @endverbatim - */ + */ static inline std::ostream& operator << (std::ostream& out, const Formatted& fmtd) { fmtd.fmt->write(out, fmtd.mtx); @@ -3762,52 +3842,136 @@ template static inline std::ostream& operator << (std::ostream& ou Formatter::get()->write(out, Mat(vec)); return out; } - -/*template struct AlgorithmParamType {}; -template<> struct AlgorithmParamType { enum { type = CV_PARAM_TYPE_INT }; }; -template<> struct AlgorithmParamType { enum { type = CV_PARAM_TYPE_REAL }; }; -template<> struct AlgorithmParamType { enum { type = CV_PARAM_TYPE_STRING }; }; -template<> struct AlgorithmParamType { enum { type = CV_PARAM_TYPE_MAT }; }; - -template _Tp Algorithm::get(int paramId) const -{ - _Tp value = _Tp(); - get_(paramId, AlgorithmParamType<_Tp>::type, &value); - return value; + + +/** Writes a Matx to an output stream. + */ +template inline std::ostream& operator<<(std::ostream& out, const Matx<_Tp, m, n>& matx) +{ + out << cv::Mat(matx); + return out; } - -template bool Algorithm::set(int paramId, const _Tp& value) + +/** Writes a point to an output stream in Matlab notation + */ +template inline std::ostream& operator<<(std::ostream& out, const Point_<_Tp>& p) { - set_(paramId, AlgorithmParamType<_Tp>::type, &value); - return value; + out << "[" << p.x << ", " << p.y << "]"; + return out; +} + +/** Writes a point to an output stream in Matlab notation + */ +template inline std::ostream& operator<<(std::ostream& out, const Point3_<_Tp>& p) +{ + out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; + return out; +} + +/** Writes a Vec to an output stream. Format example : [10, 20, 30] + */ +template inline std::ostream& operator<<(std::ostream& out, const Vec<_Tp, n>& vec) +{ + out << "["; + for (int i = 0; i < n - 1; ++i) { + out << vec[i] << ", "; + } + out << vec[n-1] << "]"; + + return out; } - -template _Tp Algorithm::paramDefaultValue(int paramId) const + +/** Writes a Size_ to an output stream. Format example : [640 x 480] + */ +template inline std::ostream& operator<<(std::ostream& out, const Size_<_Tp>& size) { - _Tp value = _Tp(); - paramDefaultValue_(paramId, AlgorithmParamType<_Tp>::type, &value); + out << "[" << size.width << " x " << size.height << "]"; + return out; +} + +/** Writes a Rect_ to an output stream. Format example : [640 x 480 from (10, 20)] + */ +template inline std::ostream& operator<<(std::ostream& out, const Rect_<_Tp>& rect) +{ + out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; + return out; +} + + +template inline Ptr<_Tp> Algorithm::create(const string& name) +{ + return _create(name).ptr<_Tp>(); +} + +template +inline void Algorithm::set(const char* _name, const Ptr<_Tp>& value) +{ + Ptr algo_ptr = value. template ptr(); + if (algo_ptr.empty()) { + CV_Error( CV_StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); + } + info()->set(this, _name, ParamType::type, &algo_ptr); +} + +template +inline void Algorithm::set(const string& _name, const Ptr<_Tp>& value) +{ + this->set<_Tp>(_name.c_str(), value); +} + +template +inline void Algorithm::setAlgorithm(const char* _name, const Ptr<_Tp>& value) +{ + Ptr algo_ptr = value. template ptr(); + if (algo_ptr.empty()) { + CV_Error( CV_StsUnsupportedFormat, "unknown/unsupported Ptr type of the second parameter of the method Algorithm::set"); + } + info()->set(this, _name, ParamType::type, &algo_ptr); +} + +template +inline void Algorithm::setAlgorithm(const string& _name, const Ptr<_Tp>& value) +{ + this->set<_Tp>(_name.c_str(), value); +} + +template inline typename ParamType<_Tp>::member_type Algorithm::get(const string& _name) const +{ + typename ParamType<_Tp>::member_type value; + info()->get(this, _name.c_str(), ParamType<_Tp>::type, &value); return value; } - -template bool Algorithm::paramRange(int paramId, _Tp& minVal, _Tp& maxVal) const + +template inline typename ParamType<_Tp>::member_type Algorithm::get(const char* _name) const { - return paramRange_(paramId, AlgorithmParamType<_Tp>::type, &minVal, &maxVal); + typename ParamType<_Tp>::member_type value; + info()->get(this, _name, ParamType<_Tp>::type, &value); + return value; } -template void Algorithm::addParam(int propId, _Tp& value, bool readOnly, const string& name, - const string& help, const _Tp& defaultValue, - _Tp (Algorithm::*getter)(), bool (Algorithm::*setter)(const _Tp&)) +template inline void AlgorithmInfo::addParam(Algorithm& algo, const char* parameter, + Ptr<_Tp>& value, bool readOnly, Ptr<_Tp> (Algorithm::*getter)(), void (Algorithm::*setter)(const Ptr<_Tp>&), + const string& help) { - addParam_(propId, AlgorithmParamType<_Tp>::type, &value, readOnly, name, help, &defaultValue, - (void*)getter, (void*)setter); + //TODO: static assert: _Tp inherits from _Base + addParam_(algo, parameter, ParamType<_Base>::type, &value, readOnly, + (Algorithm::Getter)getter, (Algorithm::Setter)setter, help); } - -template void Algorithm::setParamRange(int propId, const _Tp& minVal, const _Tp& maxVal) + +template inline void AlgorithmInfo::addParam(Algorithm& algo, const char* parameter, + Ptr<_Tp>& value, bool readOnly, Ptr<_Tp> (Algorithm::*getter)(), void (Algorithm::*setter)(const Ptr<_Tp>&), + const string& help) { - setParamRange_(propId, AlgorithmParamType<_Tp>::type, &minVal, &maxVal); -}*/ - + //TODO: static assert: _Tp inherits from Algorithm + addParam_(algo, parameter, ParamType::type, &value, readOnly, + (Algorithm::Getter)getter, (Algorithm::Setter)setter, help); +} + } +#ifdef _MSC_VER +# pragma warning(pop) +#endif + #endif // __cplusplus #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/types_c.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/types_c.h old mode 100755 new mode 100644 similarity index 94% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/types_c.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/types_c.h index e2284a8..cbc7872 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/types_c.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/types_c.h @@ -43,120 +43,132 @@ #ifndef __OPENCV_CORE_TYPES_H__ #define __OPENCV_CORE_TYPES_H__ -#if !defined _CRT_SECURE_NO_DEPRECATE && _MSC_VER > 1300 -#define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio 2005 warnings */ +#if !defined _CRT_SECURE_NO_DEPRECATE && defined _MSC_VER +# if _MSC_VER > 1300 +# define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio 2005 warnings */ +# endif #endif #ifndef SKIP_INCLUDES - #include - #include - #include - #include + +#include +#include +#include +#include #if !defined _MSC_VER && !defined __BORLANDC__ - #include +# include +#endif + +#if defined __ICL +# define CV_ICC __ICL +#elif defined __ICC +# define CV_ICC __ICC +#elif defined __ECL +# define CV_ICC __ECL +#elif defined __ECC +# define CV_ICC __ECC +#elif defined __INTEL_COMPILER +# define CV_ICC __INTEL_COMPILER +#endif + +#if defined CV_ICC && !defined CV_ENABLE_UNROLLED +# define CV_ENABLE_UNROLLED 0 +#else +# define CV_ENABLE_UNROLLED 1 +#endif + +#if (defined _M_X64 && defined _MSC_VER && _MSC_VER >= 1400) || (__GNUC__ >= 4 && defined __x86_64__) +# if defined WIN32 +# include +# endif +# if defined __SSE2__ || !defined __GNUC__ +# include +# endif +#endif + +#if defined __BORLANDC__ +# include +#else +# include +#endif + +#ifdef HAVE_IPL +# ifndef __IPL_H__ +# if defined WIN32 || defined _WIN32 +# include +# else +# include +# endif +# endif +#elif defined __IPL_H__ +# define HAVE_IPL #endif - #if defined __ICL - #define CV_ICC __ICL - #elif defined __ICC - #define CV_ICC __ICC - #elif defined __ECL - #define CV_ICC __ECL - #elif defined __ECC - #define CV_ICC __ECC - #elif defined __INTEL_COMPILER - #define CV_ICC __INTEL_COMPILER - #endif - - #if (_MSC_VER >= 1400 && defined _M_X64) || (__GNUC__ >= 4 && defined __x86_64__) - #if defined WIN32 - #include - #endif - #include - #endif - - #if defined __BORLANDC__ - #include - #else - #include - #endif - - #ifdef HAVE_IPL - #ifndef __IPL_H__ - #if defined WIN32 || defined _WIN32 - #include - #else - #include - #endif - #endif - #elif defined __IPL_H__ - #define HAVE_IPL - #endif #endif // SKIP_INCLUDES #if defined WIN32 || defined _WIN32 - #define CV_CDECL __cdecl - #define CV_STDCALL __stdcall +# define CV_CDECL __cdecl +# define CV_STDCALL __stdcall #else - #define CV_CDECL - #define CV_STDCALL +# define CV_CDECL +# define CV_STDCALL #endif #ifndef CV_EXTERN_C - #ifdef __cplusplus - #define CV_EXTERN_C extern "C" - #define CV_DEFAULT(val) = val - #else - #define CV_EXTERN_C - #define CV_DEFAULT(val) - #endif +# ifdef __cplusplus +# define CV_EXTERN_C extern "C" +# define CV_DEFAULT(val) = val +# else +# define CV_EXTERN_C +# define CV_DEFAULT(val) +# endif #endif #ifndef CV_EXTERN_C_FUNCPTR - #ifdef __cplusplus - #define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } - #else - #define CV_EXTERN_C_FUNCPTR(x) typedef x - #endif +# ifdef __cplusplus +# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } +# else +# define CV_EXTERN_C_FUNCPTR(x) typedef x +# endif #endif #ifndef CV_INLINE -#if defined __cplusplus - #define CV_INLINE inline -#elif (defined WIN32 || defined _WIN32 || defined WINCE) && !defined __GNUC__ - #define CV_INLINE __inline -#else - #define CV_INLINE static -#endif +# if defined __cplusplus +# define CV_INLINE inline +# elif (defined WIN32 || defined _WIN32 || defined WINCE) && !defined __GNUC__ +# define CV_INLINE __inline +# else +# define CV_INLINE static +# endif #endif /* CV_INLINE */ #if (defined WIN32 || defined _WIN32 || defined WINCE) && defined CVAPI_EXPORTS - #define CV_EXPORTS __declspec(dllexport) +# define CV_EXPORTS __declspec(dllexport) #else - #define CV_EXPORTS +# define CV_EXPORTS #endif #ifndef CVAPI - #define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL +# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL #endif #if defined _MSC_VER || defined __BORLANDC__ -typedef __int64 int64; -typedef unsigned __int64 uint64; -#define CV_BIG_INT(n) n##I64 -#define CV_BIG_UINT(n) n##UI64 + typedef __int64 int64; + typedef unsigned __int64 uint64; +# define CV_BIG_INT(n) n##I64 +# define CV_BIG_UINT(n) n##UI64 #else -typedef int64_t int64; -typedef uint64_t uint64; -#define CV_BIG_INT(n) n##LL -#define CV_BIG_UINT(n) n##ULL + typedef int64_t int64; + typedef uint64_t uint64; +# define CV_BIG_INT(n) n##LL +# define CV_BIG_UINT(n) n##ULL #endif #ifndef HAVE_IPL -typedef unsigned char uchar; -typedef unsigned short ushort; + typedef unsigned char uchar; + typedef unsigned short ushort; #endif typedef signed char schar; @@ -201,7 +213,7 @@ Cv64suf; typedef int CVStatus; -enum { +enum { CV_StsOk= 0, /* everithing is ok */ CV_StsBackTrace= -1, /* pseudo error for back trace */ CV_StsError= -2, /* unknown /unspecified error */ @@ -239,8 +251,8 @@ enum { CV_StsInplaceNotSupported= -203, /* in-place operation is not supported */ CV_StsObjectNotFound= -204, /* request can't be completed */ CV_StsUnmatchedFormats= -205, /* formats of input/output arrays differ */ - CV_StsBadFlag= -206, /* flag is wrong or not supported */ - CV_StsBadPoint= -207, /* bad CvPoint */ + CV_StsBadFlag= -206, /* flag is wrong or not supported */ + CV_StsBadPoint= -207, /* bad CvPoint */ CV_StsBadMask= -208, /* bad format of mask (neither 8uC1 nor 8sC1)*/ CV_StsUnmatchedSizes= -209, /* sizes of input/output structures do not match */ CV_StsUnsupportedFormat= -210, /* the data format/type is not supported by the function*/ @@ -248,9 +260,11 @@ enum { CV_StsParseError= -212, /* invalid syntax/structure of the parsed file */ CV_StsNotImplemented= -213, /* the requested function/feature is not implemented */ CV_StsBadMemBlock= -214, /* an allocated block has been corrupted */ - CV_StsAssert= -215, /* assertion failed */ - CV_GpuNotSupported= -216, - CV_GpuApiCallError= -217 + CV_StsAssert= -215, /* assertion failed */ + CV_GpuNotSupported= -216, + CV_GpuApiCallError= -217, + CV_OpenGlNotSupported= -218, + CV_OpenGlApiCallError= -219 }; /****************************************************************************************\ @@ -258,7 +272,7 @@ enum { \****************************************************************************************/ #ifdef HAVE_TEGRA_OPTIMIZATION -# include "tegra_round.hpp" +# include "tegra_round.hpp" #endif #define CV_PI 3.1415926535897932384626433832795 @@ -267,11 +281,11 @@ enum { #define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) #ifndef MIN -#define MIN(a,b) ((a) > (b) ? (b) : (a)) +# define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #ifndef MAX -#define MAX(a,b) ((a) < (b) ? (b) : (a)) +# define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif /* min & max without jumps */ @@ -281,16 +295,16 @@ enum { /* absolute value without jumps */ #ifndef __cplusplus -#define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) +# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) #else -#define CV_IABS(a) abs(a) +# define CV_IABS(a) abs(a) #endif #define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) #define CV_SIGN(a) CV_CMP((a),0) CV_INLINE int cvRound( double value ) { -#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && !defined __APPLE__) +#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && defined __SSE2__ && !defined __APPLE__) __m128d t = _mm_set_sd( value ); return _mm_cvtsd_si32(t); #elif defined _MSC_VER && defined _M_IX86 @@ -302,27 +316,30 @@ CV_INLINE int cvRound( double value ) } return t; #elif defined HAVE_LRINT || defined CV_ICC || defined __GNUC__ -# ifdef HAVE_TEGRA_OPTIMIZATION +# ifdef HAVE_TEGRA_OPTIMIZATION TEGRA_ROUND(value); -# else +# else return (int)lrint(value); -# endif +# endif #else // while this is not IEEE754-compliant rounding, it's usually a good enough approximation return (int)(value + (value >= 0 ? 0.5 : -0.5)); #endif } +#if defined __SSE2__ || (defined _M_IX86_FP && 2 == _M_IX86_FP) +# include "emmintrin.h" +#endif CV_INLINE int cvFloor( double value ) { -#ifdef __GNUC__ - int i = (int)value; - return i - (i > value); -#elif defined _MSC_VER && defined _M_X64 +#if defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__ && !defined __APPLE__) __m128d t = _mm_set_sd( value ); int i = _mm_cvtsd_si32(t); return i - _mm_movemask_pd(_mm_cmplt_sd(t, _mm_cvtsi32_sd(t,i))); +#elif defined __GNUC__ + int i = (int)value; + return i - (i > value); #else int i = cvRound(value); Cv32suf diff; @@ -334,13 +351,13 @@ CV_INLINE int cvFloor( double value ) CV_INLINE int cvCeil( double value ) { -#ifdef __GNUC__ - int i = (int)value; - return i + (i < value); -#elif defined _MSC_VER && defined _M_X64 +#if defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__) __m128d t = _mm_set_sd( value ); int i = _mm_cvtsd_si32(t); return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i), t)); +#elif defined __GNUC__ + int i = (int)value; + return i + (i < value); #else int i = cvRound(value); Cv32suf diff; @@ -1123,7 +1140,7 @@ CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) /******************************** CvSize's & CvBox **************************************/ -typedef struct +typedef struct CvSize { int width; int height; @@ -1733,6 +1750,11 @@ typedef struct CvFileStorage CvFileStorage; #define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE #define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE #define CV_STORAGE_APPEND 2 +#define CV_STORAGE_MEMORY 4 +#define CV_STORAGE_FORMAT_MASK (7<<3) +#define CV_STORAGE_FORMAT_AUTO 0 +#define CV_STORAGE_FORMAT_XML 8 +#define CV_STORAGE_FORMAT_YAML 16 /* List of attributes: */ typedef struct CvAttrList @@ -1874,8 +1896,6 @@ typedef struct CvModuleInfo } CvModuleInfo; -enum { CV_PARAM_TYPE_INT=0, CV_PARAM_TYPE_REAL=1, CV_PARAM_TYPE_STRING=2, CV_PARAM_TYPE_MAT=3 }; - -#endif /*_CXCORE_TYPES_H_*/ +#endif /*__OPENCV_CORE_TYPES_H__*/ /* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/version.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/version.hpp old mode 100755 new mode 100644 similarity index 97% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/version.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/version.hpp index 897d2dc..4e68c52 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/version.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/version.hpp @@ -48,8 +48,8 @@ #define __OPENCV_VERSION_HPP__ #define CV_MAJOR_VERSION 2 -#define CV_MINOR_VERSION 3 -#define CV_SUBMINOR_VERSION 2 +#define CV_MINOR_VERSION 4 +#define CV_SUBMINOR_VERSION 3 #define CVAUX_STR_EXP(__A) #__A #define CVAUX_STR(__A) CVAUX_STR_EXP(__A) diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/wimage.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/wimage.hpp old mode 100755 new mode 100644 similarity index 99% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/wimage.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/wimage.hpp index 579c009..c7afa8c --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/core/wimage.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/core/wimage.hpp @@ -1,8 +1,8 @@ /////////////////////////////////////////////////////////////////////////////// // 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, +// 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. // // License Agreement @@ -11,7 +11,7 @@ // Copyright (C) 2008, Google, all rights reserved. // Third party copyrights are property of their respective owners. // -// Redistribution and use in source and binary forms, with or without +// 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, @@ -25,11 +25,11 @@ // 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 +// 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 diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/features2d/features2d.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/features2d/features2d.hpp new file mode 100644 index 0000000..a205322 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/features2d/features2d.hpp @@ -0,0 +1,1606 @@ +/*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. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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 __OPENCV_FEATURES_2D_HPP__ +#define __OPENCV_FEATURES_2D_HPP__ + +#include "opencv2/core/core.hpp" +#include "opencv2/flann/miniflann.hpp" + +#ifdef __cplusplus +#include + +namespace cv +{ + +CV_EXPORTS bool initModule_features2d(); + +/*! + The Keypoint Class + + The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint detectors, such as + Harris corner detector, cv::FAST, cv::StarDetector, cv::SURF, cv::SIFT, cv::LDetector etc. + + The keypoint is characterized by the 2D position, scale + (proportional to the diameter of the neighborhood that needs to be taken into account), + orientation and some other parameters. The keypoint neighborhood is then analyzed by another algorithm that builds a descriptor + (usually represented as a feature vector). The keypoints representing the same object in different images can then be matched using + cv::KDTree or another method. +*/ +class CV_EXPORTS_W_SIMPLE KeyPoint +{ +public: + //! the default constructor + CV_WRAP KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} + //! the full constructor + KeyPoint(Point2f _pt, float _size, float _angle=-1, + float _response=0, int _octave=0, int _class_id=-1) + : pt(_pt), size(_size), angle(_angle), + response(_response), octave(_octave), class_id(_class_id) {} + //! another form of the full constructor + CV_WRAP KeyPoint(float x, float y, float _size, float _angle=-1, + float _response=0, int _octave=0, int _class_id=-1) + : pt(x, y), size(_size), angle(_angle), + response(_response), octave(_octave), class_id(_class_id) {} + + size_t hash() const; + + //! converts vector of keypoints to vector of points + static void convert(const vector& keypoints, + CV_OUT vector& points2f, + const vector& keypointIndexes=vector()); + //! converts vector of points to the vector of keypoints, where each keypoint is assigned the same size and the same orientation + static void convert(const vector& points2f, + CV_OUT vector& keypoints, + float size=1, float response=1, int octave=0, int class_id=-1); + + //! computes overlap for pair of keypoints; + //! overlap is a ratio between area of keypoint regions intersection and + //! area of keypoint regions union (now keypoint region is circle) + static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); + + CV_PROP_RW Point2f pt; //!< coordinates of the keypoints + CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood + CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); + //!< it's in [0,360) degrees and measured relative to + //!< image coordinate system, ie in clockwise. + CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling + CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted + CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) +}; + +//! writes vector of keypoints to the file storage +CV_EXPORTS void write(FileStorage& fs, const string& name, const vector& keypoints); +//! reads vector of keypoints from the specified file storage node +CV_EXPORTS void read(const FileNode& node, CV_OUT vector& keypoints); + +/* + * A class filters a vector of keypoints. + * Because now it is difficult to provide a convenient interface for all usage scenarios of the keypoints filter class, + * it has only several needed by now static methods. + */ +class CV_EXPORTS KeyPointsFilter +{ +public: + KeyPointsFilter(){} + + /* + * Remove keypoints within borderPixels of an image edge. + */ + static void runByImageBorder( vector& keypoints, Size imageSize, int borderSize ); + /* + * Remove keypoints of sizes out of range. + */ + static void runByKeypointSize( vector& keypoints, float minSize, + float maxSize=FLT_MAX ); + /* + * Remove keypoints from some image by mask for pixels of this image. + */ + static void runByPixelsMask( vector& keypoints, const Mat& mask ); + /* + * Remove duplicated keypoints. + */ + static void removeDuplicated( vector& keypoints ); + + /* + * Retain the specified number of the best keypoints (according to the response) + */ + static void retainBest( vector& keypoints, int npoints ); +}; + + +/************************************ Base Classes ************************************/ + +/* + * Abstract base class for 2D image feature detectors. + */ +class CV_EXPORTS_W FeatureDetector : public virtual Algorithm +{ +public: + virtual ~FeatureDetector(); + + /* + * Detect keypoints in an image. + * image The image. + * keypoints The detected keypoints. + * mask Mask specifying where to look for keypoints (optional). Must be a char + * matrix with non-zero values in the region of interest. + */ + CV_WRAP void detect( const Mat& image, CV_OUT vector& keypoints, const Mat& mask=Mat() ) const; + + /* + * Detect keypoints in an image set. + * images Image collection. + * keypoints Collection of keypoints detected in an input images. keypoints[i] is a set of keypoints detected in an images[i]. + * masks Masks for image set. masks[i] is a mask for images[i]. + */ + void detect( const vector& images, vector >& keypoints, const vector& masks=vector() ) const; + + // Return true if detector object is empty + CV_WRAP virtual bool empty() const; + + // Create feature detector by detector name. + CV_WRAP static Ptr create( const string& detectorType ); + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const = 0; + + /* + * Remove keypoints that are not in the mask. + * Helper function, useful when wrapping a library call for keypoint detection that + * does not support a mask argument. + */ + static void removeInvalidPoints( const Mat& mask, vector& keypoints ); +}; + + +/* + * Abstract base class for computing descriptors for image keypoints. + * + * In this interface we assume a keypoint descriptor can be represented as a + * dense, fixed-dimensional vector of some basic type. Most descriptors used + * in practice follow this pattern, as it makes it very easy to compute + * distances between descriptors. Therefore we represent a collection of + * descriptors as a Mat, where each row is one keypoint descriptor. + */ +class CV_EXPORTS_W DescriptorExtractor : public virtual Algorithm +{ +public: + virtual ~DescriptorExtractor(); + + /* + * Compute the descriptors for a set of keypoints in an image. + * image The image. + * keypoints The input keypoints. Keypoints for which a descriptor cannot be computed are removed. + * descriptors Copmputed descriptors. Row i is the descriptor for keypoint i. + */ + CV_WRAP void compute( const Mat& image, CV_OUT CV_IN_OUT vector& keypoints, CV_OUT Mat& descriptors ) const; + + /* + * Compute the descriptors for a keypoints collection detected in image collection. + * images Image collection. + * keypoints Input keypoints collection. keypoints[i] is keypoints detected in images[i]. + * Keypoints for which a descriptor cannot be computed are removed. + * descriptors Descriptor collection. descriptors[i] are descriptors computed for set keypoints[i]. + */ + void compute( const vector& images, vector >& keypoints, vector& descriptors ) const; + + CV_WRAP virtual int descriptorSize() const = 0; + CV_WRAP virtual int descriptorType() const = 0; + + CV_WRAP virtual bool empty() const; + + CV_WRAP static Ptr create( const string& descriptorExtractorType ); + +protected: + virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const = 0; + + /* + * Remove keypoints within borderPixels of an image edge. + */ + static void removeBorderKeypoints( vector& keypoints, + Size imageSize, int borderSize ); +}; + + + +/* + * Abstract base class for simultaneous 2D feature detection descriptor extraction. + */ +class CV_EXPORTS_W Feature2D : public FeatureDetector, public DescriptorExtractor +{ +public: + /* + * Detect keypoints in an image. + * image The image. + * keypoints The detected keypoints. + * mask Mask specifying where to look for keypoints (optional). Must be a char + * matrix with non-zero values in the region of interest. + * useProvidedKeypoints If true, the method will skip the detection phase and will compute + * descriptors for the provided keypoints + */ + CV_WRAP_AS(detectAndCompute) virtual void operator()( InputArray image, InputArray mask, + CV_OUT vector& keypoints, + OutputArray descriptors, + bool useProvidedKeypoints=false ) const = 0; + + // Create feature detector and descriptor extractor by name. + CV_WRAP static Ptr create( const string& name ); +}; + +/*! + BRISK implementation +*/ +class CV_EXPORTS_W BRISK : public Feature2D +{ +public: + CV_WRAP explicit BRISK(int thresh=30, int octaves=3, float patternScale=1.0f); + + virtual ~BRISK(); + + // returns the descriptor size in bytes + int descriptorSize() const; + // returns the descriptor type + int descriptorType() const; + + // Compute the BRISK features on an image + void operator()(InputArray image, InputArray mask, vector& keypoints) const; + + // Compute the BRISK features and descriptors on an image + void operator()( InputArray image, InputArray mask, vector& keypoints, + OutputArray descriptors, bool useProvidedKeypoints=false ) const; + + AlgorithmInfo* info() const; + + // custom setup + CV_WRAP explicit BRISK(std::vector &radiusList, std::vector &numberList, + float dMax=5.85f, float dMin=8.2f, std::vector indexChange=std::vector()); + + // call this to generate the kernel: + // circle of radius r (pixels), with n points; + // short pairings with dMax, long pairings with dMin + CV_WRAP void generateKernel(std::vector &radiusList, + std::vector &numberList, float dMax=5.85f, float dMin=8.2f, + std::vector indexChange=std::vector()); + +protected: + + void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + void computeKeypointsNoOrientation(InputArray image, InputArray mask, vector& keypoints) const; + void computeDescriptorsAndOrOrientation(InputArray image, InputArray mask, vector& keypoints, + OutputArray descriptors, bool doDescriptors, bool doOrientation, + bool useProvidedKeypoints) const; + + // Feature parameters + CV_PROP_RW int threshold; + CV_PROP_RW int octaves; + + // some helper structures for the Brisk pattern representation + struct BriskPatternPoint{ + float x; // x coordinate relative to center + float y; // x coordinate relative to center + float sigma; // Gaussian smoothing sigma + }; + struct BriskShortPair{ + unsigned int i; // index of the first pattern point + unsigned int j; // index of other pattern point + }; + struct BriskLongPair{ + unsigned int i; // index of the first pattern point + unsigned int j; // index of other pattern point + int weighted_dx; // 1024.0/dx + int weighted_dy; // 1024.0/dy + }; + inline int smoothedIntensity(const cv::Mat& image, + const cv::Mat& integral,const float key_x, + const float key_y, const unsigned int scale, + const unsigned int rot, const unsigned int point) const; + // pattern properties + BriskPatternPoint* patternPoints_; //[i][rotation][scale] + unsigned int points_; // total number of collocation points + float* scaleList_; // lists the scaling per scale index [scale] + unsigned int* sizeList_; // lists the total pattern size per scale index [scale] + static const unsigned int scales_; // scales discretization + static const float scalerange_; // span of sizes 40->4 Octaves - else, this needs to be adjusted... + static const unsigned int n_rot_; // discretization of the rotation look-up + + // pairs + int strings_; // number of uchars the descriptor consists of + float dMax_; // short pair maximum distance + float dMin_; // long pair maximum distance + BriskShortPair* shortPairs_; // d<_dMax + BriskLongPair* longPairs_; // d>_dMin + unsigned int noShortPairs_; // number of shortParis + unsigned int noLongPairs_; // number of longParis + + // general + static const float basicSize_; +}; + + +/*! + ORB implementation. +*/ +class CV_EXPORTS_W ORB : public Feature2D +{ +public: + // the size of the signature in bytes + enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 }; + + CV_WRAP explicit ORB(int nfeatures = 500, float scaleFactor = 1.2f, int nlevels = 8, int edgeThreshold = 31, + int firstLevel = 0, int WTA_K=2, int scoreType=ORB::HARRIS_SCORE, int patchSize=31 ); + + // returns the descriptor size in bytes + int descriptorSize() const; + // returns the descriptor type + int descriptorType() const; + + // Compute the ORB features and descriptors on an image + void operator()(InputArray image, InputArray mask, vector& keypoints) const; + + // Compute the ORB features and descriptors on an image + void operator()( InputArray image, InputArray mask, vector& keypoints, + OutputArray descriptors, bool useProvidedKeypoints=false ) const; + + AlgorithmInfo* info() const; + +protected: + + void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + CV_PROP_RW int nfeatures; + CV_PROP_RW double scaleFactor; + CV_PROP_RW int nlevels; + CV_PROP_RW int edgeThreshold; + CV_PROP_RW int firstLevel; + CV_PROP_RW int WTA_K; + CV_PROP_RW int scoreType; + CV_PROP_RW int patchSize; +}; + +typedef ORB OrbFeatureDetector; +typedef ORB OrbDescriptorExtractor; + +/*! + FREAK implementation +*/ +class CV_EXPORTS FREAK : public DescriptorExtractor +{ +public: + /** Constructor + * @param orientationNormalized enable orientation normalization + * @param scaleNormalized enable scale normalization + * @param patternScale scaling of the description pattern + * @param nbOctave number of octaves covered by the detected keypoints + * @param selectedPairs (optional) user defined selected pairs + */ + explicit FREAK( bool orientationNormalized = true, + bool scaleNormalized = true, + float patternScale = 22.0f, + int nOctaves = 4, + const vector& selectedPairs = vector()); + FREAK( const FREAK& rhs ); + FREAK& operator=( const FREAK& ); + + virtual ~FREAK(); + + /** returns the descriptor length in bytes */ + virtual int descriptorSize() const; + + /** returns the descriptor type */ + virtual int descriptorType() const; + + /** select the 512 "best description pairs" + * @param images grayscale images set + * @param keypoints set of detected keypoints + * @param corrThresh correlation threshold + * @param verbose print construction information + * @return list of best pair indexes + */ + vector selectPairs( const vector& images, vector >& keypoints, + const double corrThresh = 0.7, bool verbose = true ); + + AlgorithmInfo* info() const; + + enum + { + NB_SCALES = 64, NB_PAIRS = 512, NB_ORIENPAIRS = 45 + }; + +protected: + virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + void buildPattern(); + uchar meanIntensity( const Mat& image, const Mat& integral, const float kp_x, const float kp_y, + const unsigned int scale, const unsigned int rot, const unsigned int point ) const; + + bool orientationNormalized; //true if the orientation is normalized, false otherwise + bool scaleNormalized; //true if the scale is normalized, false otherwise + double patternScale; //scaling of the pattern + int nOctaves; //number of octaves + bool extAll; // true if all pairs need to be extracted for pairs selection + + double patternScale0; + int nOctaves0; + vector selectedPairs0; + + struct PatternPoint + { + float x; // x coordinate relative to center + float y; // x coordinate relative to center + float sigma; // Gaussian smoothing sigma + }; + + struct DescriptionPair + { + uchar i; // index of the first point + uchar j; // index of the second point + }; + + struct OrientationPair + { + uchar i; // index of the first point + uchar j; // index of the second point + int weight_dx; // dx/(norm_sq))*4096 + int weight_dy; // dy/(norm_sq))*4096 + }; + + vector patternLookup; // look-up table for the pattern points (position+sigma of all points at all scales and orientation) + int patternSizes[NB_SCALES]; // size of the pattern at a specific scale (used to check if a point is within image boundaries) + DescriptionPair descriptionPairs[NB_PAIRS]; + OrientationPair orientationPairs[NB_ORIENPAIRS]; +}; + + +/*! + Maximal Stable Extremal Regions class. + + The class implements MSER algorithm introduced by J. Matas. + Unlike SIFT, SURF and many other detectors in OpenCV, this is salient region detector, + not the salient point detector. + + It returns the regions, each of those is encoded as a contour. +*/ +class CV_EXPORTS_W MSER : public FeatureDetector +{ +public: + //! the full constructor + CV_WRAP explicit MSER( int _delta=5, int _min_area=60, int _max_area=14400, + double _max_variation=0.25, double _min_diversity=.2, + int _max_evolution=200, double _area_threshold=1.01, + double _min_margin=0.003, int _edge_blur_size=5 ); + + //! the operator that extracts the MSERs from the image or the specific part of it + CV_WRAP_AS(detect) void operator()( const Mat& image, CV_OUT vector >& msers, + const Mat& mask=Mat() ) const; + AlgorithmInfo* info() const; + +protected: + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + int delta; + int minArea; + int maxArea; + double maxVariation; + double minDiversity; + int maxEvolution; + double areaThreshold; + double minMargin; + int edgeBlurSize; +}; + +typedef MSER MserFeatureDetector; + +/*! + The "Star" Detector. + + The class implements the keypoint detector introduced by K. Konolige. +*/ +class CV_EXPORTS_W StarDetector : public FeatureDetector +{ +public: + //! the full constructor + CV_WRAP StarDetector(int _maxSize=45, int _responseThreshold=30, + int _lineThresholdProjected=10, + int _lineThresholdBinarized=8, + int _suppressNonmaxSize=5); + + //! finds the keypoints in the image + CV_WRAP_AS(detect) void operator()(const Mat& image, + CV_OUT vector& keypoints) const; + + AlgorithmInfo* info() const; + +protected: + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + int maxSize; + int responseThreshold; + int lineThresholdProjected; + int lineThresholdBinarized; + int suppressNonmaxSize; +}; + +//! detects corners using FAST algorithm by E. Rosten +CV_EXPORTS void FAST( InputArray image, CV_OUT vector& keypoints, + int threshold, bool nonmaxSupression=true ); + +CV_EXPORTS void FASTX( InputArray image, CV_OUT vector& keypoints, + int threshold, bool nonmaxSupression, int type ); + +class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector +{ +public: + + enum + { // Define it in old class to simplify migration to 2.5 + TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 + }; + + CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true ); + AlgorithmInfo* info() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + int threshold; + bool nonmaxSuppression; +}; + + +class CV_EXPORTS GFTTDetector : public FeatureDetector +{ +public: + GFTTDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, + int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); + AlgorithmInfo* info() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + int nfeatures; + double qualityLevel; + double minDistance; + int blockSize; + bool useHarrisDetector; + double k; +}; + +typedef GFTTDetector GoodFeaturesToTrackDetector; +typedef StarDetector StarFeatureDetector; + +class CV_EXPORTS_W SimpleBlobDetector : public FeatureDetector +{ +public: + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW float thresholdStep; + CV_PROP_RW float minThreshold; + CV_PROP_RW float maxThreshold; + CV_PROP_RW size_t minRepeatability; + CV_PROP_RW float minDistBetweenBlobs; + + CV_PROP_RW bool filterByColor; + CV_PROP_RW uchar blobColor; + + CV_PROP_RW bool filterByArea; + CV_PROP_RW float minArea, maxArea; + + CV_PROP_RW bool filterByCircularity; + CV_PROP_RW float minCircularity, maxCircularity; + + CV_PROP_RW bool filterByInertia; + CV_PROP_RW float minInertiaRatio, maxInertiaRatio; + + CV_PROP_RW bool filterByConvexity; + CV_PROP_RW float minConvexity, maxConvexity; + + void read( const FileNode& fn ); + void write( FileStorage& fs ) const; + }; + + CV_WRAP SimpleBlobDetector(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); + + virtual void read( const FileNode& fn ); + virtual void write( FileStorage& fs ) const; + +protected: + struct CV_EXPORTS Center + { + Point2d location; + double radius; + double confidence; + }; + + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + virtual void findBlobs(const Mat &image, const Mat &binaryImage, vector
        ¢ers) const; + + Params params; +}; + + +class CV_EXPORTS DenseFeatureDetector : public FeatureDetector +{ +public: + explicit DenseFeatureDetector( float initFeatureScale=1.f, int featureScaleLevels=1, + float featureScaleMul=0.1f, + int initXyStep=6, int initImgBound=0, + bool varyXyStepWithScale=true, + bool varyImgBoundWithScale=false ); + AlgorithmInfo* info() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + double initFeatureScale; + int featureScaleLevels; + double featureScaleMul; + + int initXyStep; + int initImgBound; + + bool varyXyStepWithScale; + bool varyImgBoundWithScale; +}; + +/* + * Adapts a detector to partition the source image into a grid and detect + * points in each cell. + */ +class CV_EXPORTS_W GridAdaptedFeatureDetector : public FeatureDetector +{ +public: + /* + * detector Detector that will be adapted. + * maxTotalKeypoints Maximum count of keypoints detected on the image. Only the strongest keypoints + * will be keeped. + * gridRows Grid rows count. + * gridCols Grid column count. + */ + CV_WRAP GridAdaptedFeatureDetector( const Ptr& detector=0, + int maxTotalKeypoints=1000, + int gridRows=4, int gridCols=4 ); + + // TODO implement read/write + virtual bool empty() const; + + AlgorithmInfo* info() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + Ptr detector; + int maxTotalKeypoints; + int gridRows; + int gridCols; +}; + +/* + * Adapts a detector to detect points over multiple levels of a Gaussian + * pyramid. Useful for detectors that are not inherently scaled. + */ +class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector +{ +public: + // maxLevel - The 0-based index of the last pyramid layer + CV_WRAP PyramidAdaptedFeatureDetector( const Ptr& detector, int maxLevel=2 ); + + // TODO implement read/write + virtual bool empty() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + Ptr detector; + int maxLevel; +}; + +/** \brief A feature detector parameter adjuster, this is used by the DynamicAdaptedFeatureDetector + * and is a wrapper for FeatureDetector that allow them to be adjusted after a detection + */ +class CV_EXPORTS AdjusterAdapter: public FeatureDetector +{ +public: + /** pure virtual interface + */ + virtual ~AdjusterAdapter() {} + /** too few features were detected so, adjust the detector params accordingly + * \param min the minimum number of desired features + * \param n_detected the number previously detected + */ + virtual void tooFew(int min, int n_detected) = 0; + /** too many features were detected so, adjust the detector params accordingly + * \param max the maximum number of desired features + * \param n_detected the number previously detected + */ + virtual void tooMany(int max, int n_detected) = 0; + /** are params maxed out or still valid? + * \return false if the parameters can't be adjusted any more + */ + virtual bool good() const = 0; + + virtual Ptr clone() const = 0; + + static Ptr create( const string& detectorType ); +}; +/** \brief an adaptively adjusting detector that iteratively detects until the desired number + * of features are detected. + * Beware that this is not thread safe - as the adjustment of parameters breaks the const + * of the detection routine... + * /TODO Make this const correct and thread safe + * + * sample usage: + //will create a detector that attempts to find 100 - 110 FAST Keypoints, and will at most run + //FAST feature detection 10 times until that number of keypoints are found + Ptr detector(new DynamicAdaptedFeatureDetector(new FastAdjuster(20,true),100, 110, 10)); + + */ +class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector +{ +public: + + /** \param adjuster an AdjusterAdapter that will do the detection and parameter adjustment + * \param max_features the maximum desired number of features + * \param max_iters the maximum number of times to try to adjust the feature detector params + * for the FastAdjuster this can be high, but with Star or Surf this can get time consuming + * \param min_features the minimum desired features + */ + DynamicAdaptedFeatureDetector( const Ptr& adjuster, int min_features=400, int max_features=500, int max_iters=5 ); + + virtual bool empty() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + +private: + DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&); + DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&); + + int escape_iters_; + int min_features_, max_features_; + const Ptr adjuster_; +}; + +/**\brief an adjust for the FAST detector. This will basically decrement or increment the + * threshold by 1 + */ +class CV_EXPORTS FastAdjuster: public AdjusterAdapter +{ +public: + /**\param init_thresh the initial threshold to start with, default = 20 + * \param nonmax whether to use non max or not for fast feature detection + */ + FastAdjuster(int init_thresh=20, bool nonmax=true, int min_thresh=1, int max_thresh=200); + + virtual void tooFew(int minv, int n_detected); + virtual void tooMany(int maxv, int n_detected); + virtual bool good() const; + + virtual Ptr clone() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + int thresh_; + bool nonmax_; + int init_thresh_, min_thresh_, max_thresh_; +}; + + +/** An adjuster for StarFeatureDetector, this one adjusts the responseThreshold for now + * TODO find a faster way to converge the parameters for Star - use CvStarDetectorParams + */ +class CV_EXPORTS StarAdjuster: public AdjusterAdapter +{ +public: + StarAdjuster(double initial_thresh=30.0, double min_thresh=2., double max_thresh=200.); + + virtual void tooFew(int minv, int n_detected); + virtual void tooMany(int maxv, int n_detected); + virtual bool good() const; + + virtual Ptr clone() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + double thresh_, init_thresh_, min_thresh_, max_thresh_; +}; + +class CV_EXPORTS SurfAdjuster: public AdjusterAdapter +{ +public: + SurfAdjuster( double initial_thresh=400.f, double min_thresh=2, double max_thresh=1000 ); + + virtual void tooFew(int minv, int n_detected); + virtual void tooMany(int maxv, int n_detected); + virtual bool good() const; + + virtual Ptr clone() const; + +protected: + virtual void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + + double thresh_, init_thresh_, min_thresh_, max_thresh_; +}; + +CV_EXPORTS Mat windowedMatchingMask( const vector& keypoints1, const vector& keypoints2, + float maxDeltaX, float maxDeltaY ); + + + +/* + * OpponentColorDescriptorExtractor + * + * Adapts a descriptor extractor to compute descripors in Opponent Color Space + * (refer to van de Sande et al., CGIV 2008 "Color Descriptors for Object Category Recognition"). + * Input RGB image is transformed in Opponent Color Space. Then unadapted descriptor extractor + * (set in constructor) computes descriptors on each of the three channel and concatenate + * them into a single color descriptor. + */ +class CV_EXPORTS OpponentColorDescriptorExtractor : public DescriptorExtractor +{ +public: + OpponentColorDescriptorExtractor( const Ptr& descriptorExtractor ); + + virtual void read( const FileNode& ); + virtual void write( FileStorage& ) const; + + virtual int descriptorSize() const; + virtual int descriptorType() const; + + virtual bool empty() const; + +protected: + virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + + Ptr descriptorExtractor; +}; + +/* + * BRIEF Descriptor + */ +class CV_EXPORTS BriefDescriptorExtractor : public DescriptorExtractor +{ +public: + static const int PATCH_SIZE = 48; + static const int KERNEL_SIZE = 9; + + // bytes is a length of descriptor in bytes. It can be equal 16, 32 or 64 bytes. + BriefDescriptorExtractor( int bytes = 32 ); + + virtual void read( const FileNode& ); + virtual void write( FileStorage& ) const; + + virtual int descriptorSize() const; + virtual int descriptorType() const; + + /// @todo read and write for brief + + AlgorithmInfo* info() const; + +protected: + virtual void computeImpl(const Mat& image, vector& keypoints, Mat& descriptors) const; + + typedef void(*PixelTestFn)(const Mat&, const vector&, Mat&); + + int bytes_; + PixelTestFn test_fn_; +}; + + +/****************************************************************************************\ +* Distance * +\****************************************************************************************/ + +template +struct CV_EXPORTS Accumulator +{ + typedef T Type; +}; + +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; + +/* + * Squared Euclidean distance functor + */ +template +struct CV_EXPORTS SL2 +{ + enum { normType = NORM_L2SQR }; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL2Sqr(a, b, size); + } +}; + +/* + * Euclidean distance functor + */ +template +struct CV_EXPORTS L2 +{ + enum { normType = NORM_L2 }; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return (ResultType)sqrt((double)normL2Sqr(a, b, size)); + } +}; + +/* + * Manhattan distance (city block distance) functor + */ +template +struct CV_EXPORTS L1 +{ + enum { normType = NORM_L1 }; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL1(a, b, size); + } +}; + +/* + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct CV_EXPORTS Hamming +{ + enum { normType = NORM_HAMMING }; + typedef unsigned char ValueType; + typedef int ResultType; + + /** this will count the bits in a ^ b + */ + ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const + { + return normHamming(a, b, size); + } +}; + +typedef Hamming HammingLUT; + +template struct CV_EXPORTS HammingMultilevel +{ + enum { normType = NORM_HAMMING + (cellsize>1) }; + typedef unsigned char ValueType; + typedef int ResultType; + + ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const + { + return normHamming(a, b, size, cellsize); + } +}; + +/****************************************************************************************\ +* DMatch * +\****************************************************************************************/ +/* + * Struct for matching: query descriptor index, train descriptor index, train image index and distance between descriptors. + */ +struct CV_EXPORTS_W_SIMPLE DMatch +{ + CV_WRAP DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} + CV_WRAP DMatch( int _queryIdx, int _trainIdx, float _distance ) : + queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} + CV_WRAP DMatch( int _queryIdx, int _trainIdx, int _imgIdx, float _distance ) : + queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} + + CV_PROP_RW int queryIdx; // query descriptor index + CV_PROP_RW int trainIdx; // train descriptor index + CV_PROP_RW int imgIdx; // train image index + + CV_PROP_RW float distance; + + // less is better + bool operator<( const DMatch &m ) const + { + return distance < m.distance; + } +}; + +/****************************************************************************************\ +* DescriptorMatcher * +\****************************************************************************************/ +/* + * Abstract base class for matching two sets of descriptors. + */ +class CV_EXPORTS_W DescriptorMatcher : public Algorithm +{ +public: + virtual ~DescriptorMatcher(); + + /* + * Add descriptors to train descriptor collection. + * descriptors Descriptors to add. Each descriptors[i] is a descriptors set from one image. + */ + CV_WRAP virtual void add( const vector& descriptors ); + /* + * Get train descriptors collection. + */ + CV_WRAP const vector& getTrainDescriptors() const; + /* + * Clear train descriptors collection. + */ + CV_WRAP virtual void clear(); + + /* + * Return true if there are not train descriptors in collection. + */ + CV_WRAP virtual bool empty() const; + /* + * Return true if the matcher supports mask in match methods. + */ + CV_WRAP virtual bool isMaskSupported() const = 0; + + /* + * Train matcher (e.g. train flann index). + * In all methods to match the method train() is run every time before matching. + * Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation + * of this method, other matchers really train their inner structures + * (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation + * of train() should check the class object state and do traing/retraining + * only if the state requires that (e.g. FlannBasedMatcher trains flann::Index + * if it has not trained yet or if new descriptors have been added to the train + * collection). + */ + CV_WRAP virtual void train(); + /* + * Group of methods to match descriptors from image pair. + * Method train() is run in this methods. + */ + // Find one best match for each query descriptor (if mask is empty). + CV_WRAP void match( const Mat& queryDescriptors, const Mat& trainDescriptors, + CV_OUT vector& matches, const Mat& mask=Mat() ) const; + // Find k best matches for each query descriptor (in increasing order of distances). + // compactResult is used when mask is not empty. If compactResult is false matches + // vector will have the same size as queryDescriptors rows. If compactResult is true + // matches vector will not contain matches for fully masked out query descriptors. + CV_WRAP void knnMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, + CV_OUT vector >& matches, int k, + const Mat& mask=Mat(), bool compactResult=false ) const; + // Find best matches for each query descriptor which have distance less than + // maxDistance (in increasing order of distances). + void radiusMatch( const Mat& queryDescriptors, const Mat& trainDescriptors, + vector >& matches, float maxDistance, + const Mat& mask=Mat(), bool compactResult=false ) const; + /* + * Group of methods to match descriptors from one image to image set. + * See description of similar methods for matching image pair above. + */ + CV_WRAP void match( const Mat& queryDescriptors, CV_OUT vector& matches, + const vector& masks=vector() ); + CV_WRAP void knnMatch( const Mat& queryDescriptors, CV_OUT vector >& matches, int k, + const vector& masks=vector(), bool compactResult=false ); + void radiusMatch( const Mat& queryDescriptors, vector >& matches, float maxDistance, + const vector& masks=vector(), bool compactResult=false ); + + // Reads matcher object from a file node + virtual void read( const FileNode& ); + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const; + + // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies + // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters + // but with empty train data. + virtual Ptr clone( bool emptyTrainData=false ) const = 0; + + CV_WRAP static Ptr create( const string& descriptorMatcherType ); +protected: + /* + * Class to work with descriptors from several images as with one merged matrix. + * It is used e.g. in FlannBasedMatcher. + */ + class CV_EXPORTS DescriptorCollection + { + public: + DescriptorCollection(); + DescriptorCollection( const DescriptorCollection& collection ); + virtual ~DescriptorCollection(); + + // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. + void set( const vector& descriptors ); + virtual void clear(); + + const Mat& getDescriptors() const; + const Mat getDescriptor( int imgIdx, int localDescIdx ) const; + const Mat getDescriptor( int globalDescIdx ) const; + void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; + + int size() const; + + protected: + Mat mergedDescriptors; + vector startIdxs; + }; + + // In fact the matching is implemented only by the following two methods. These methods suppose + // that the class object has been trained already. Public match methods call these methods + // after calling train(). + virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, + const vector& masks=vector(), bool compactResult=false ) = 0; + virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, + const vector& masks=vector(), bool compactResult=false ) = 0; + + static bool isPossibleMatch( const Mat& mask, int queryIdx, int trainIdx ); + static bool isMaskedOut( const vector& masks, int queryIdx ); + + static Mat clone_op( Mat m ) { return m.clone(); } + void checkMasks( const vector& masks, int queryDescriptorsCount ) const; + + // Collection of descriptors from train images. + vector trainDescCollection; +}; + +/* + * Brute-force descriptor matcher. + * + * For each descriptor in the first set, this matcher finds the closest + * descriptor in the second set by trying each one. + * + * For efficiency, BruteForceMatcher is templated on the distance metric. + * For float descriptors, a common choice would be cv::L2. + */ +class CV_EXPORTS_W BFMatcher : public DescriptorMatcher +{ +public: + CV_WRAP BFMatcher( int normType, bool crossCheck=false ); + virtual ~BFMatcher() {} + + virtual bool isMaskSupported() const { return true; } + + virtual Ptr clone( bool emptyTrainData=false ) const; + +protected: + virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, + const vector& masks=vector(), bool compactResult=false ); + virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, + const vector& masks=vector(), bool compactResult=false ); + + int normType; + bool crossCheck; +}; + + +/* + * Flann based matcher + */ +class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher +{ +public: + CV_WRAP FlannBasedMatcher( const Ptr& indexParams=new flann::KDTreeIndexParams(), + const Ptr& searchParams=new flann::SearchParams() ); + + virtual void add( const vector& descriptors ); + virtual void clear(); + + // Reads matcher object from a file node + virtual void read( const FileNode& ); + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const; + + virtual void train(); + virtual bool isMaskSupported() const; + + virtual Ptr clone( bool emptyTrainData=false ) const; + +protected: + static void convertToDMatches( const DescriptorCollection& descriptors, + const Mat& indices, const Mat& distances, + vector >& matches ); + + virtual void knnMatchImpl( const Mat& queryDescriptors, vector >& matches, int k, + const vector& masks=vector(), bool compactResult=false ); + virtual void radiusMatchImpl( const Mat& queryDescriptors, vector >& matches, float maxDistance, + const vector& masks=vector(), bool compactResult=false ); + + Ptr indexParams; + Ptr searchParams; + Ptr flannIndex; + + DescriptorCollection mergedDescriptors; + int addedDescCount; +}; + +/****************************************************************************************\ +* GenericDescriptorMatcher * +\****************************************************************************************/ +/* + * Abstract interface for a keypoint descriptor and matcher + */ +class GenericDescriptorMatcher; +typedef GenericDescriptorMatcher GenericDescriptorMatch; + +class CV_EXPORTS GenericDescriptorMatcher +{ +public: + GenericDescriptorMatcher(); + virtual ~GenericDescriptorMatcher(); + + /* + * Add train collection: images and keypoints from them. + * images A set of train images. + * ketpoints Keypoint collection that have been detected on train images. + * + * Keypoints for which a descriptor cannot be computed are removed. Such keypoints + * must be filtered in this method befor adding keypoints to train collection "trainPointCollection". + * If inheritor class need perform such prefiltering the method add() must be overloaded. + * In the other class methods programmer has access to the train keypoints by a constant link. + */ + virtual void add( const vector& images, + vector >& keypoints ); + + const vector& getTrainImages() const; + const vector >& getTrainKeypoints() const; + + /* + * Clear images and keypoints storing in train collection. + */ + virtual void clear(); + /* + * Returns true if matcher supports mask to match descriptors. + */ + virtual bool isMaskSupported() = 0; + /* + * Train some inner structures (e.g. flann index or decision trees). + * train() methods is run every time in matching methods. So the method implementation + * should has a check whether these inner structures need be trained/retrained or not. + */ + virtual void train(); + + /* + * Classifies query keypoints. + * queryImage The query image + * queryKeypoints Keypoints from the query image + * trainImage The train image + * trainKeypoints Keypoints from the train image + */ + // Classify keypoints from query image under one train image. + void classify( const Mat& queryImage, vector& queryKeypoints, + const Mat& trainImage, vector& trainKeypoints ) const; + // Classify keypoints from query image under train image collection. + void classify( const Mat& queryImage, vector& queryKeypoints ); + + /* + * Group of methods to match keypoints from image pair. + * Keypoints for which a descriptor cannot be computed are removed. + * train() method is called here. + */ + // Find one best match for each query descriptor (if mask is empty). + void match( const Mat& queryImage, vector& queryKeypoints, + const Mat& trainImage, vector& trainKeypoints, + vector& matches, const Mat& mask=Mat() ) const; + // Find k best matches for each query keypoint (in increasing order of distances). + // compactResult is used when mask is not empty. If compactResult is false matches + // vector will have the same size as queryDescriptors rows. + // If compactResult is true matches vector will not contain matches for fully masked out query descriptors. + void knnMatch( const Mat& queryImage, vector& queryKeypoints, + const Mat& trainImage, vector& trainKeypoints, + vector >& matches, int k, + const Mat& mask=Mat(), bool compactResult=false ) const; + // Find best matches for each query descriptor which have distance less than maxDistance (in increasing order of distances). + void radiusMatch( const Mat& queryImage, vector& queryKeypoints, + const Mat& trainImage, vector& trainKeypoints, + vector >& matches, float maxDistance, + const Mat& mask=Mat(), bool compactResult=false ) const; + /* + * Group of methods to match keypoints from one image to image set. + * See description of similar methods for matching image pair above. + */ + void match( const Mat& queryImage, vector& queryKeypoints, + vector& matches, const vector& masks=vector() ); + void knnMatch( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, int k, + const vector& masks=vector(), bool compactResult=false ); + void radiusMatch( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, float maxDistance, + const vector& masks=vector(), bool compactResult=false ); + + // Reads matcher object from a file node + virtual void read( const FileNode& fn ); + // Writes matcher object to a file storage + virtual void write( FileStorage& fs ) const; + + // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty) + virtual bool empty() const; + + // Clone the matcher. If emptyTrainData is false the method create deep copy of the object, i.e. copies + // both parameters and train data. If emptyTrainData is true the method create object copy with current parameters + // but with empty train data. + virtual Ptr clone( bool emptyTrainData=false ) const = 0; + + static Ptr create( const string& genericDescritptorMatcherType, + const string ¶msFilename=string() ); + +protected: + // In fact the matching is implemented only by the following two methods. These methods suppose + // that the class object has been trained already. Public match methods call these methods + // after calling train(). + virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, int k, + const vector& masks, bool compactResult ) = 0; + virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, float maxDistance, + const vector& masks, bool compactResult ) = 0; + /* + * A storage for sets of keypoints together with corresponding images and class IDs + */ + class CV_EXPORTS KeyPointCollection + { + public: + KeyPointCollection(); + KeyPointCollection( const KeyPointCollection& collection ); + void add( const vector& images, const vector >& keypoints ); + void clear(); + + // Returns the total number of keypoints in the collection + size_t keypointCount() const; + size_t imageCount() const; + + const vector >& getKeypoints() const; + const vector& getKeypoints( int imgIdx ) const; + const KeyPoint& getKeyPoint( int imgIdx, int localPointIdx ) const; + const KeyPoint& getKeyPoint( int globalPointIdx ) const; + void getLocalIdx( int globalPointIdx, int& imgIdx, int& localPointIdx ) const; + + const vector& getImages() const; + const Mat& getImage( int imgIdx ) const; + + protected: + int pointCount; + + vector images; + vector > keypoints; + // global indices of the first points in each image, startIndices.size() = keypoints.size() + vector startIndices; + + private: + static Mat clone_op( Mat m ) { return m.clone(); } + }; + + KeyPointCollection trainPointCollection; +}; + + +/****************************************************************************************\ +* VectorDescriptorMatcher * +\****************************************************************************************/ + +/* + * A class used for matching descriptors that can be described as vectors in a finite-dimensional space + */ +class VectorDescriptorMatcher; +typedef VectorDescriptorMatcher VectorDescriptorMatch; + +class CV_EXPORTS VectorDescriptorMatcher : public GenericDescriptorMatcher +{ +public: + VectorDescriptorMatcher( const Ptr& extractor, const Ptr& matcher ); + virtual ~VectorDescriptorMatcher(); + + virtual void add( const vector& imgCollection, + vector >& pointCollection ); + + virtual void clear(); + + virtual void train(); + + virtual bool isMaskSupported(); + + virtual void read( const FileNode& fn ); + virtual void write( FileStorage& fs ) const; + virtual bool empty() const; + + virtual Ptr clone( bool emptyTrainData=false ) const; + +protected: + virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, int k, + const vector& masks, bool compactResult ); + virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, float maxDistance, + const vector& masks, bool compactResult ); + + Ptr extractor; + Ptr matcher; +}; + +/****************************************************************************************\ +* Drawing functions * +\****************************************************************************************/ +struct CV_EXPORTS DrawMatchesFlags +{ + enum{ DEFAULT = 0, // Output image matrix will be created (Mat::create), + // i.e. existing memory of output image may be reused. + // Two source image, matches and single keypoints will be drawn. + // For each keypoint only the center point will be drawn (without + // the circle around keypoint with keypoint size and orientation). + DRAW_OVER_OUTIMG = 1, // Output image matrix will not be created (Mat::create). + // Matches will be drawn on existing content of output image. + NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn. + DRAW_RICH_KEYPOINTS = 4 // For each keypoint the circle around keypoint with keypoint size and + // orientation will be drawn. + }; +}; + +// Draw keypoints. +CV_EXPORTS_W void drawKeypoints( const Mat& image, const vector& keypoints, CV_OUT Mat& outImage, + const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT ); + +// Draws matches of keypints from two images on output image. +CV_EXPORTS void drawMatches( const Mat& img1, const vector& keypoints1, + const Mat& img2, const vector& keypoints2, + const vector& matches1to2, Mat& outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const vector& matchesMask=vector(), int flags=DrawMatchesFlags::DEFAULT ); + +CV_EXPORTS void drawMatches( const Mat& img1, const vector& keypoints1, + const Mat& img2, const vector& keypoints2, + const vector >& matches1to2, Mat& outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const vector >& matchesMask=vector >(), int flags=DrawMatchesFlags::DEFAULT ); + +/****************************************************************************************\ +* Functions to evaluate the feature detectors and [generic] descriptor extractors * +\****************************************************************************************/ + +CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, + vector* keypoints1, vector* keypoints2, + float& repeatability, int& correspCount, + const Ptr& fdetector=Ptr() ); + +CV_EXPORTS void computeRecallPrecisionCurve( const vector >& matches1to2, + const vector >& correctMatches1to2Mask, + vector& recallPrecisionCurve ); + +CV_EXPORTS float getRecall( const vector& recallPrecisionCurve, float l_precision ); +CV_EXPORTS int getNearestPoint( const vector& recallPrecisionCurve, float l_precision ); + +CV_EXPORTS void evaluateGenericDescriptorMatcher( const Mat& img1, const Mat& img2, const Mat& H1to2, + vector& keypoints1, vector& keypoints2, + vector >* matches1to2, vector >* correctMatches1to2Mask, + vector& recallPrecisionCurve, + const Ptr& dmatch=Ptr() ); + + +/****************************************************************************************\ +* Bag of visual words * +\****************************************************************************************/ +/* + * Abstract base class for training of a 'bag of visual words' vocabulary from a set of descriptors + */ +class CV_EXPORTS BOWTrainer +{ +public: + BOWTrainer(); + virtual ~BOWTrainer(); + + void add( const Mat& descriptors ); + const vector& getDescriptors() const; + int descripotorsCount() const; + + virtual void clear(); + + /* + * Train visual words vocabulary, that is cluster training descriptors and + * compute cluster centers. + * Returns cluster centers. + * + * descriptors Training descriptors computed on images keypoints. + */ + virtual Mat cluster() const = 0; + virtual Mat cluster( const Mat& descriptors ) const = 0; + +protected: + vector descriptors; + int size; +}; + +/* + * This is BOWTrainer using cv::kmeans to get vocabulary. + */ +class CV_EXPORTS BOWKMeansTrainer : public BOWTrainer +{ +public: + BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), + int attempts=3, int flags=KMEANS_PP_CENTERS ); + virtual ~BOWKMeansTrainer(); + + // Returns trained vocabulary (i.e. cluster centers). + virtual Mat cluster() const; + virtual Mat cluster( const Mat& descriptors ) const; + +protected: + + int clusterCount; + TermCriteria termcrit; + int attempts; + int flags; +}; + +/* + * Class to compute image descriptor using bag of visual words. + */ +class CV_EXPORTS BOWImgDescriptorExtractor +{ +public: + BOWImgDescriptorExtractor( const Ptr& dextractor, + const Ptr& dmatcher ); + virtual ~BOWImgDescriptorExtractor(); + + void setVocabulary( const Mat& vocabulary ); + const Mat& getVocabulary() const; + void compute( const Mat& image, vector& keypoints, Mat& imgDescriptor, + vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); + // compute() is not constant because DescriptorMatcher::match is not constant + + int descriptorSize() const; + int descriptorType() const; + +protected: + Mat vocabulary; + Ptr dextractor; + Ptr dmatcher; +}; + +} /* namespace cv */ + +#endif /* __cplusplus */ + +#endif + +/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/all_indices.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/all_indices.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/all_indices.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/all_indices.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/allocator.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/allocator.h old mode 100755 new mode 100644 similarity index 95% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/allocator.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/allocator.h index 6ca44fc..26091d0 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/allocator.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/allocator.h @@ -92,9 +92,9 @@ class PooledAllocator /** Default constructor. Initializes a new pool. */ - PooledAllocator(int blocksize = BLOCKSIZE) + PooledAllocator(int blockSize = BLOCKSIZE) { - this->blocksize = blocksize; + blocksize = blockSize; remaining = 0; base = NULL; @@ -122,7 +122,7 @@ class PooledAllocator */ void* allocateMemory(int size) { - int blocksize; + int blockSize; /* Round size up to a multiple of wordsize. The following expression only works for WORDSIZE that is a power of 2, by masking last bits of @@ -138,11 +138,11 @@ class PooledAllocator wastedMemory += remaining; /* Allocate new storage. */ - blocksize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? + blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; // use the standard C malloc to allocate memory - void* m = ::malloc(blocksize); + void* m = ::malloc(blockSize); if (!m) { fprintf(stderr,"Failed to allocate memory.\n"); return NULL; @@ -155,7 +155,7 @@ class PooledAllocator int shift = 0; //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); - remaining = blocksize - sizeof(void*) - shift; + remaining = blockSize - sizeof(void*) - shift; loc = ((char*)m + sizeof(void*) + shift); } void* rloc = loc; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/any.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/any.h old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/any.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/any.h index ca37487..89189c6 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/any.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/any.h @@ -12,11 +12,12 @@ * Adapted for FLANN by Marius Muja */ +#include "defines.h" #include #include #include -namespace cdiggins +namespace cvflann { namespace anyimpl @@ -43,15 +44,19 @@ struct base_any_policy virtual void clone(void* const* src, void** dest) = 0; virtual void move(void* const* src, void** dest) = 0; virtual void* get_value(void** src) = 0; - virtual size_t get_size() = 0; + virtual ::size_t get_size() = 0; virtual const std::type_info& type() = 0; virtual void print(std::ostream& out, void* const* src) = 0; + +#ifdef OPENCV_CAN_BREAK_BINARY_COMPATIBILITY + virtual ~base_any_policy() {} +#endif }; template struct typed_base_any_policy : base_any_policy { - virtual size_t get_size() { return sizeof(T); } + virtual ::size_t get_size() { return sizeof(T); } virtual const std::type_info& type() { return typeid(T); } }; @@ -94,6 +99,16 @@ struct big_any_policy : typed_base_any_policy virtual void print(std::ostream& out, void* const* src) { out << *reinterpret_cast(*src); } }; +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + template struct choose_policy { diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/autotuned_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/autotuned_index.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/autotuned_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/autotuned_index.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/composite_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/composite_index.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/composite_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/composite_index.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/config.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/config.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/config.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/config.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/defines.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/defines.h old mode 100755 new mode 100644 similarity index 97% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/defines.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/defines.h index 7bd8964..13833b3 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/defines.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/defines.h @@ -65,7 +65,7 @@ #undef FLANN_PLATFORM_32_BIT #undef FLANN_PLATFORM_64_BIT -#if __amd64__ || __x86_64__ || _WIN64 || _M_X64 +#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 #define FLANN_PLATFORM_64_BIT #else #define FLANN_PLATFORM_32_BIT @@ -137,6 +137,7 @@ enum flann_distance_t FLANN_DIST_CS = 7, FLANN_DIST_KULLBACK_LEIBLER = 8, FLANN_DIST_KL = 8, + FLANN_DIST_HAMMING = 9, // deprecated constants, should use the FLANN_DIST_* ones instead EUCLIDEAN = 1, diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dist.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dist.h old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dist.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dist.h index b16ca39..d267430 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dist.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dist.h @@ -35,7 +35,7 @@ #include #include #ifdef _MSC_VER -typedef unsigned uint32_t; +typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #else #include @@ -43,6 +43,9 @@ typedef unsigned __int64 uint64_t; #include "defines.h" +#ifdef __ARM_NEON__ +#include "arm_neon.h" +#endif namespace cvflann { @@ -59,10 +62,6 @@ inline float abs(float x) { return fabsf(x); } template<> inline double abs(double x) { return fabs(x); } -template<> -inline long double abs(long double x) { return fabsl(x); } - - template struct Accumulator { typedef T Type; }; template<> @@ -78,6 +77,8 @@ struct Accumulator { typedef float Type; }; template<> struct Accumulator { typedef float Type; }; +#undef True +#undef False class True { @@ -383,7 +384,7 @@ struct HammingLUT */ ResultType operator()(const unsigned char* a, const unsigned char* b, int size) const { - static const uchar popCountTable[] = + static const uchar popCountTable[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, @@ -402,6 +403,41 @@ struct HammingLUT } }; +/** + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct HammingLUT2 +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef unsigned char ElementType; + typedef int ResultType; + + /** this will count the bits in a ^ b + */ + ResultType operator()(const unsigned char* a, const unsigned char* b, size_t size) const + { + static const uchar popCountTable[] = + { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + ResultType result = 0; + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i] ^ b[i]]; + } + return result; + } +}; + /** * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) * That code was taken from brief.cpp in OpenCV @@ -420,9 +456,9 @@ struct Hamming ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const { ResultType result = 0; -#if __GNUC__ -#if CV_NEON - if (CPU_HAS_NEON_FEATURE) { +#ifdef __GNUC__ +#ifdef __ARM_NEON__ + { uint32x4_t bits = vmovq_n_u32(0); for (size_t i = 0; i < size; i += 16) { uint8x16_t A_vec = vld1q_u8 (a + i); @@ -437,8 +473,7 @@ struct Hamming result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); } - else -#endif +#else { //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) typedef unsigned long long pop_t; @@ -458,6 +493,7 @@ struct Hamming result += __builtin_popcountll(a_final ^ b_final); } } +#endif //NEON #else HammingLUT lut; result = lut(reinterpret_cast (a), @@ -513,9 +549,9 @@ struct Hamming2 ResultType result = 0; size /= (sizeof(uint32_t)/sizeof(unsigned char)); for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa ^ *pb); - ++pa; - ++pb; + result += popcnt32(*pa ^ *pb); + ++pa; + ++pb; } #endif return result; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dummy.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dummy.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dummy.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dummy.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dynamic_bitset.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dynamic_bitset.h old mode 100755 new mode 100644 similarity index 94% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dynamic_bitset.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dynamic_bitset.h index e88cfaa..bfd39ce --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/dynamic_bitset.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/dynamic_bitset.h @@ -35,6 +35,9 @@ #ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ #define OPENCV_FLANN_DYNAMIC_BITSET_H_ +#ifndef FLANN_USE_BOOST +# define FLANN_USE_BOOST 0 +#endif //#define FLANN_USE_BOOST 1 #if FLANN_USE_BOOST #include @@ -45,6 +48,8 @@ typedef boost::dynamic_bitset<> DynamicBitset; #include "dist.h" +namespace cvflann { + /** Class re-implementing the boost version of it * This helps not depending on boost, it also does not do the bound checks * and has a way to reset a block for speed @@ -61,9 +66,9 @@ class DynamicBitset /** @param only constructor we use in our code * @param the size of the bitset (in bits) */ - DynamicBitset(size_t size) + DynamicBitset(size_t sz) { - resize(size); + resize(sz); reset(); } @@ -111,10 +116,10 @@ class DynamicBitset /** @param resize the bitset so that it contains at least size bits * @param size */ - void resize(size_t size) + void resize(size_t sz) { - size_ = size; - bitset_.resize(size / cell_bit_size_ + 1); + size_ = sz; + bitset_.resize(sz / cell_bit_size_ + 1); } /** @param set a bit to true @@ -147,6 +152,8 @@ class DynamicBitset static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); }; +} // namespace cvflann + #endif #endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/flann.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/flann.hpp old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/flann.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/flann.hpp index 988988f..d053488 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/flann.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/flann.hpp @@ -93,7 +93,7 @@ using ::cvflann::KL_Divergence; template -class GenericIndex +class GenericIndex { public: typedef typename Distance::ElementType ElementType; @@ -103,13 +103,13 @@ class GenericIndex ~GenericIndex(); - void knnSearch(const vector& query, vector& indices, + void knnSearch(const vector& query, vector& indices, vector& dists, int knn, const ::cvflann::SearchParams& params); void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); - int radiusSearch(const vector& query, vector& indices, + int radiusSearch(const vector& query, vector& indices, vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); - int radiusSearch(const Mat& query, Mat& indices, Mat& dists, + int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params); void save(std::string filename) { nnIndex->save(filename); } @@ -134,7 +134,7 @@ class GenericIndex "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ "for example for L1 distance use: GenericIndex< L1 > \n"); \ } - + template GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) @@ -142,11 +142,11 @@ GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexP CV_Assert(dataset.type() == CvType::type()); CV_Assert(dataset.isContinuous()); ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); - + nnIndex = new ::cvflann::Index(m_dataset, params, distance); - + FLANN_DISTANCE_CHECK - + nnIndex->buildIndex(); } @@ -175,17 +175,17 @@ void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& di CV_Assert(queries.type() == CvType::type()); CV_Assert(queries.isContinuous()); ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - + CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - + CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); FLANN_DISTANCE_CHECK - + nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); } @@ -197,7 +197,7 @@ int GenericIndex::radiusSearch(const vector& query, vecto ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); FLANN_DISTANCE_CHECK - + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } @@ -207,17 +207,17 @@ int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& di CV_Assert(query.type() == CvType::type()); CV_Assert(query.isContinuous()); ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - + CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - + CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - + FLANN_DISTANCE_CHECK - + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } @@ -225,50 +225,54 @@ int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& di * @deprecated Use GenericIndex class instead */ template -class FLANN_DEPRECATED Index_ { +class +#ifndef _MSC_VER + FLANN_DEPRECATED +#endif + Index_ { public: typedef typename L2::ElementType ElementType; typedef typename L2::ResultType DistanceType; - Index_(const Mat& features, const ::cvflann::IndexParams& params); + Index_(const Mat& features, const ::cvflann::IndexParams& params); - ~Index_(); + ~Index_(); - void knnSearch(const vector& query, vector& indices, vector& dists, int knn, const ::cvflann::SearchParams& params); - void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); + void knnSearch(const vector& query, vector& indices, vector& dists, int knn, const ::cvflann::SearchParams& params); + void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); - int radiusSearch(const vector& query, vector& indices, vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); - int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params); + int radiusSearch(const vector& query, vector& indices, vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); + int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params); - void save(std::string filename) - { + void save(std::string filename) + { if (nnIndex_L1) nnIndex_L1->save(filename); if (nnIndex_L2) nnIndex_L2->save(filename); } - int veclen() const - { + int veclen() const + { if (nnIndex_L1) return nnIndex_L1->veclen(); - if (nnIndex_L2) return nnIndex_L2->veclen(); + if (nnIndex_L2) return nnIndex_L2->veclen(); } - int size() const - { + int size() const + { if (nnIndex_L1) return nnIndex_L1->size(); - if (nnIndex_L2) return nnIndex_L2->size(); + if (nnIndex_L2) return nnIndex_L2->size(); } - ::cvflann::IndexParams getParameters() - { + ::cvflann::IndexParams getParameters() + { if (nnIndex_L1) return nnIndex_L1->getParameters(); if (nnIndex_L2) return nnIndex_L2->getParameters(); - + } - FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() - { + FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() + { if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); - if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); + if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); } private: @@ -277,23 +281,27 @@ class FLANN_DEPRECATED Index_ { ::cvflann::Index< L1 >* nnIndex_L1; }; +#ifdef _MSC_VER +template +class FLANN_DEPRECATED Index_; +#endif template Index_::Index_(const Mat& dataset, const ::cvflann::IndexParams& params) { printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); - + CV_Assert(dataset.type() == CvType::type()); CV_Assert(dataset.isContinuous()); ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); - + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { nnIndex_L1 = NULL; nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); } else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); - nnIndex_L2 = NULL; + nnIndex_L2 = NULL; } else { printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " @@ -317,7 +325,7 @@ void Index_::knnSearch(const vector& query, vector& indices ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - + if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); } @@ -329,11 +337,11 @@ void Index_::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, CV_Assert(queries.type() == CvType::type()); CV_Assert(queries.isContinuous()); ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - + CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - + CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); @@ -348,7 +356,7 @@ int Index_::radiusSearch(const vector& query, vector& indic ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } @@ -359,31 +367,31 @@ int Index_::radiusSearch(const Mat& query, Mat& indices, Mat& dists, Distance CV_Assert(query.type() == CvType::type()); CV_Assert(query.isContinuous()); ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - + CV_Assert(indices.type() == CV_32S); CV_Assert(indices.isContinuous()); ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - + CV_Assert(dists.type() == CvType::type()); CV_Assert(dists.isContinuous()); ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); } template -int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::IndexParams& params, +int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, Distance d = Distance()) { typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; - + CV_Assert(features.type() == CvType::type()); CV_Assert(features.isContinuous()); ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); - + CV_Assert(centers.type() == CvType::type()); CV_Assert(centers.isContinuous()); ::cvflann::Matrix m_centers((DistanceType*)centers.ptr(0), centers.rows, centers.cols); @@ -393,11 +401,11 @@ int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::I template -FLANN_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::IndexParams& params) +FLANN_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) { printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " "cv::flann::hierarchicalClustering instead\n"); - + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { return hierarchicalClustering< L2 >(features, centers, params); } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/flann_base.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/flann_base.hpp old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/flann_base.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/flann_base.hpp diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/general.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/general.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/general.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/general.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/ground_truth.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/ground_truth.h old mode 100755 new mode 100644 similarity index 94% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/ground_truth.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/ground_truth.h index 8f1c698..69d978b --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/ground_truth.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/ground_truth.h @@ -46,8 +46,8 @@ void find_nearest(const Matrix& dataset, typenam typedef typename Distance::ResultType DistanceType; int n = nn + skip; - int* match = new int[n]; - DistanceType* dists = new DistanceType[n]; + std::vector match(n); + std::vector dists(n); dists[0] = distance(dataset[0], query, dataset.cols); match[0] = 0; @@ -57,12 +57,12 @@ void find_nearest(const Matrix& dataset, typenam DistanceType tmp = distance(dataset[i], query, dataset.cols); if (dcnt& dataset, typenam for (int i=0; i hid_t get_hdf5_type() { return H5T_NATIVE_FLOAT; } template<> hid_t get_hdf5_type() { return H5T_NATIVE_DOUBLE; } -template<> -hid_t get_hdf5_type() { return H5T_NATIVE_LDOUBLE; } } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/heap.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/heap.h old mode 100755 new mode 100644 similarity index 98% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/heap.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/heap.h index dc0a6f7..92a6ea6 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/heap.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/heap.h @@ -67,12 +67,12 @@ class Heap * Constructor. * * Params: - * size = heap size + * sz = heap size */ - Heap(int size) + Heap(int sz) { - length = size; + length = sz; heap.reserve(length); count = 0; } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/hierarchical_clustering_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/hierarchical_clustering_index.h old mode 100755 new mode 100644 similarity index 90% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/hierarchical_clustering_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/hierarchical_clustering_index.h index 1ca1c10..ce2d622 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/hierarchical_clustering_index.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/hierarchical_clustering_index.h @@ -106,7 +106,7 @@ class HierarchicalClusteringIndex : public NNIndex * indices_length = length of indices vector * */ - void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) + void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { UniqueRandom r(indices_length); @@ -122,7 +122,7 @@ class HierarchicalClusteringIndex : public NNIndex return; } - centers[index] = indices[rnd]; + centers[index] = dsindices[rnd]; for (int j=0; j * indices = indices in the dataset * Returns: */ - void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length) + void chooseCentersGonzales(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { int n = indices_length; int rnd = rand_int(n); assert(rnd >=0 && rnd < n); - centers[0] = indices[rnd]; + centers[0] = dsindices[rnd]; int index; for (index=1; index int best_index = -1; DistanceType best_val = 0; for (int j=0; j } } if (best_index!=-1) { - centers[index] = indices[best_index]; + centers[index] = dsindices[best_index]; } else { break; @@ -198,7 +198,7 @@ class HierarchicalClusteringIndex : public NNIndex * indices = indices in the dataset * Returns: */ - void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) + void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) { int n = indices_length; @@ -208,10 +208,10 @@ class HierarchicalClusteringIndex : public NNIndex // Choose one random center and set the closestDistSq values int index = rand_int(n); assert(index >=0 && index < n); - centers[0] = indices[index]; + centers[0] = dsindices[index]; for (int i = 0; i < n; i++) { - closestDistSq[i] = distance(dataset[indices[i]], dataset[indices[index]], dataset.cols); + closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); currentPot += closestDistSq[i]; } @@ -237,7 +237,7 @@ class HierarchicalClusteringIndex : public NNIndex // Compute the new potential double newPot = 0; - for (int i = 0; i < n; i++) newPot += std::min( distance(dataset[indices[i]], dataset[indices[index]], dataset.cols), closestDistSq[i] ); + for (int i = 0; i < n; i++) newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols), closestDistSq[i] ); // Store the best result if ((bestNewPot < 0)||(newPot < bestNewPot)) { @@ -247,9 +247,9 @@ class HierarchicalClusteringIndex : public NNIndex } // Add the appropriate center - centers[centerCount] = indices[bestNewIndex]; + centers[centerCount] = dsindices[bestNewIndex]; currentPot = bestNewPot; - for (int i = 0; i < n; i++) closestDistSq[i] = std::min( distance(dataset[indices[i]], dataset[indices[bestNewIndex]], dataset.cols), closestDistSq[i] ); + for (int i = 0; i < n; i++) closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols), closestDistSq[i] ); } centers_length = centerCount; @@ -352,10 +352,10 @@ class HierarchicalClusteringIndex : public NNIndex for (int i=0; i(); - computeClustering(root[i], indices[i], size_, branching_,0); + computeClustering(root[i], indices[i], (int)size_, branching_,0); } } @@ -419,7 +419,7 @@ class HierarchicalClusteringIndex : public NNIndex int maxChecks = get_param(searchParams,"checks",32); // Priority queue storing intermediate branches in the best-bin-first search - Heap* heap = new Heap(size_); + Heap* heap = new Heap((int)size_); std::vector checked(size_,false); int checks = 0; @@ -487,7 +487,7 @@ class HierarchicalClusteringIndex : public NNIndex { save_value(stream, *node); if (node->childs==NULL) { - int indices_offset = node->indices - indices[num]; + int indices_offset = (int)(node->indices - indices[num]); save_value(stream, indices_offset); } else { @@ -518,11 +518,11 @@ class HierarchicalClusteringIndex : public NNIndex - void computeLabels(int* indices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost) + void computeLabels(int* dsindices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost) { cost = 0; for (int i=0; i * * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) */ - void computeClustering(NodePtr node, int* indices, int indices_length, int branching, int level) + void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) { node->size = indices_length; node->level = level; if (indices_length < leaf_size_) { // leaf node - node->indices = indices; + node->indices = dsindices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; @@ -563,10 +563,10 @@ class HierarchicalClusteringIndex : public NNIndex std::vector labels(indices_length); int centers_length; - (this->*chooseCenters)(branching, indices, indices_length, ¢ers[0], centers_length); + (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); if (centers_lengthindices = indices; + node->indices = dsindices; std::sort(node->indices,node->indices+indices_length); node->childs = NULL; return; @@ -575,7 +575,7 @@ class HierarchicalClusteringIndex : public NNIndex // assign points to clusters DistanceType cost; - computeLabels(indices, indices_length, ¢ers[0], centers_length, &labels[0], cost); + computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); node->childs = pool.allocate(branching); int start = 0; @@ -583,7 +583,7 @@ class HierarchicalClusteringIndex : public NNIndex for (int i=0; i node->childs[i] = pool.allocate(); node->childs[i]->pivot = centers[i]; node->childs[i]->indices = NULL; - computeClustering(node->childs[i],indices+start, end-start, branching, level+1); + computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); start=end; } } @@ -619,13 +619,13 @@ class HierarchicalClusteringIndex : public NNIndex if (checks>=maxChecks) { if (result.full()) return; } - checks += node->size; for (int i=0; isize; ++i) { int index = node->indices[i]; if (!checked[index]) { DistanceType dist = distance(dataset[index], vec, veclen_); result.addPoint(dist, index); checked[index] = true; + ++checks; } } } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/index_testing.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/index_testing.h old mode 100755 new mode 100644 similarity index 96% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/index_testing.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/index_testing.h index c98a14b..d764004 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/index_testing.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/index_testing.h @@ -98,9 +98,9 @@ float search_with_ground_truth(NNIndex& index, const Matrix resultSet(nn+skipMatches); SearchParams searchParams(checks); - int* indices = new int[nn+skipMatches]; - DistanceType* dists = new DistanceType[nn+skipMatches]; - int* neighbors = indices + skipMatches; + std::vector indices(nn+skipMatches); + std::vector dists(nn+skipMatches); + int* neighbors = &indices[skipMatches]; int correct = 0; DistanceType distR = 0; @@ -112,19 +112,16 @@ float search_with_ground_truth(NNIndex& index, const Matrix(inputData, testData[i], neighbors, matches[i], testData.cols, nn, distance); + distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); } t.stop(); } time = float(t.value/repeats); - delete[] indices; - delete[] dists; - float precicion = (float)correct/(nn*testData.rows); dist = distR/(testData.rows*nn); @@ -167,7 +164,7 @@ float test_index_precision(NNIndex& index, const Matrix& index, const Matrix // Create a permutable array of indices to the input vectors. vind_.resize(size_); for (size_t i = 0; i < size_; i++) { - vind_[i] = i; + vind_[i] = (int)i; } } @@ -116,7 +116,7 @@ class KDTreeSingleIndex : public NNIndex void buildIndex() { computeBoundingBox(root_bbox_); - root_node_ = divideTree(0, size_, root_bbox_ ); // construct the tree + root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree if (reorder_) { delete[] data_.data; @@ -197,7 +197,7 @@ class KDTreeSingleIndex : public NNIndex */ int usedMemory() const { - return pool_.usedMemory+pool_.wastedMemory+dataset_.rows*sizeof(int); // pool memory and vind array memory + return (int)(pool_.usedMemory+pool_.wastedMemory+dataset_.rows*sizeof(int)); // pool memory and vind array memory } @@ -253,18 +253,18 @@ class KDTreeSingleIndex : public NNIndex /*--------------------- Internal Data Structures --------------------------*/ struct Node { - /** - * Indices of points in leaf node - */ - int left, right; - /** - * Dimension used for subdivision. - */ - int divfeat; - /** - * The values used for subdivision. - */ - DistanceType divlow, divhigh; + /** + * Indices of points in leaf node + */ + int left, right; + /** + * Dimension used for subdivision. + */ + int divfeat; + /** + * The values used for subdivision. + */ + DistanceType divlow, divhigh; /** * The child nodes. */ @@ -404,7 +404,7 @@ class KDTreeSingleIndex : public NNIndex cutfeat = 0; cutval = (bbox[0].high+bbox[0].low)/2; for (size_t i=1; imax_span) { max_span = span; cutfeat = i; @@ -461,7 +461,7 @@ class KDTreeSingleIndex : public NNIndex computeMinMax(ind, count, cutfeat, min_elem, max_elem); DistanceType spread = (DistanceType)(max_elem-min_elem); if (spread>max_spread) { - cutfeat = i; + cutfeat = (int)i; max_spread = spread; } } @@ -524,11 +524,11 @@ class KDTreeSingleIndex : public NNIndex for (size_t i = 0; i < dim_; ++i) { if (vec[i] < root_bbox_[i].low) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, i); + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); distsq += dists[i]; } if (vec[i] > root_bbox_[i].high) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, i); + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); distsq += dists[i]; } } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/kmeans_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/kmeans_index.h old mode 100755 new mode 100644 similarity index 99% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/kmeans_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/kmeans_index.h index 624c27a..3fea956 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/kmeans_index.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/kmeans_index.h @@ -674,7 +674,7 @@ class KMeansIndex : public NNIndex } delete[] centers_idx; - DistanceType* radiuses = new DistanceType[branching]; + std::vector radiuses(branching); int* count = new int[branching]; for (int i=0; i for (int i=0; i delete[] dcenters.data; delete[] centers; - delete[] radiuses; delete[] count; delete[] belongs_to; } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/linear_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/linear_index.h old mode 100755 new mode 100644 similarity index 98% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/linear_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/linear_index.h index ecb99f2..5aa7a5c --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/linear_index.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/linear_index.h @@ -108,7 +108,7 @@ class LinearIndex : public NNIndex ElementType* data = dataset_.data; for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { DistanceType dist = distance_(data, vec, dataset_.cols); - resultSet.addPoint(dist, i); + resultSet.addPoint(dist, (int)i); } } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/logger.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/logger.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/logger.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/logger.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_index.h old mode 100755 new mode 100644 similarity index 95% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_index.h index 4680653..4d4670e --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_index.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_index.h @@ -90,11 +90,13 @@ class LshIndex : public NNIndex Distance d = Distance()) : dataset_(input_data), index_params_(params), distance_(d) { - table_number_ = get_param(index_params_,"table_number",12); - key_size_ = get_param(index_params_,"key_size",20); - multi_probe_level_ = get_param(index_params_,"multi_probe_level",2); + // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param + // in place of 'unsigned int' + table_number_ = (unsigned int)get_param(index_params_,"table_number",12); + key_size_ = (unsigned int)get_param(index_params_,"key_size",20); + multi_probe_level_ = (unsigned int)get_param(index_params_,"multi_probe_level",2); - feature_size_ = dataset_.cols; + feature_size_ = (unsigned)dataset_.cols; fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); } @@ -168,7 +170,7 @@ class LshIndex : public NNIndex */ int usedMemory() const { - return dataset_.rows * sizeof(int); + return (int)(dataset_.rows * sizeof(int)); } @@ -258,8 +260,8 @@ class LshIndex : public NNIndex * @param k_nn the number of nearest neighbors * @param checked_average used for debugging */ - void getNeighbors(const ElementType* vec, bool do_radius, float radius, bool do_k, unsigned int k_nn, - float& checked_average) + void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, + float& /*checked_average*/) { static std::vector score_index_heap; @@ -344,7 +346,7 @@ class LshIndex : public NNIndex std::vector::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); + const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); if (bucket == 0) continue; // Go over each descriptor index @@ -355,7 +357,7 @@ class LshIndex : public NNIndex // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { // Compute the Hamming distance - hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); + hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); result.addPoint(hamming_distance, *training_index); } } diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_table.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_table.h old mode 100755 new mode 100644 similarity index 97% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_table.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_table.h index a245160..126fb2a --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/lsh_table.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/lsh_table.h @@ -40,6 +40,11 @@ #include #include // TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +# define USE_UNORDERED_MAP 1 +#else +# define USE_UNORDERED_MAP 0 +#endif #if USE_UNORDERED_MAP #include #else @@ -151,7 +156,7 @@ class LshTable LshTable(unsigned int /*feature_size*/, unsigned int /*key_size*/) { std::cerr << "LSH is not implemented for that type" << std::endl; - throw; + assert(0); } /** Add a feature to the table @@ -161,7 +166,7 @@ class LshTable void add(unsigned int value, const ElementType* feature) { // Add the value to the corresponding bucket - BucketKey key = getKey(feature); + BucketKey key = (lsh::BucketKey)getKey(feature); switch (speed_level_) { case kArray: @@ -188,7 +193,7 @@ class LshTable void add(Matrix dataset) { #if USE_UNORDERED_MAP - if (!use_speed_) buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); + buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); #endif // Add the features to the table for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); @@ -232,7 +237,7 @@ class LshTable size_t getKey(const ElementType* /*feature*/) const { std::cerr << "LSH is not implemented for that type" << std::endl; - throw; + assert(0); return 1; } @@ -414,7 +419,7 @@ inline LshStats LshTable::getStats() const if (!buckets_speed_.empty()) { for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { - stats.bucket_sizes_.push_back(pbucket->size()); + stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); stats.bucket_size_mean_ += pbucket->size(); } stats.bucket_size_mean_ /= buckets_speed_.size(); @@ -422,7 +427,7 @@ inline LshStats LshTable::getStats() const } else { for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { - stats.bucket_sizes_.push_back(x->second.size()); + stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); stats.bucket_size_mean_ += x->second.size(); } stats.bucket_size_mean_ /= buckets_space_.size(); diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/matrix.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/matrix.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/matrix.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/matrix.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/miniflann.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/miniflann.hpp old mode 100755 new mode 100644 similarity index 94% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/miniflann.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/miniflann.hpp index d7fd90f..18c9081 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/miniflann.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/miniflann.hpp @@ -50,7 +50,7 @@ namespace cv { - + namespace flann { @@ -58,31 +58,31 @@ struct CV_EXPORTS IndexParams { IndexParams(); ~IndexParams(); - + std::string getString(const std::string& key, const std::string& defaultVal=std::string()) const; int getInt(const std::string& key, int defaultVal=-1) const; double getDouble(const std::string& key, double defaultVal=-1) const; - + void setString(const std::string& key, const std::string& value); void setInt(const std::string& key, int value); void setDouble(const std::string& key, double value); void setFloat(const std::string& key, float value); void setBool(const std::string& key, bool value); void setAlgorithm(int value); - + void getAll(std::vector& names, std::vector& types, std::vector& strValues, std::vector& numValues) const; - + void* params; -}; +}; struct CV_EXPORTS KDTreeIndexParams : public IndexParams { KDTreeIndexParams(int trees=4); }; - + struct CV_EXPORTS LinearIndexParams : public IndexParams { LinearIndexParams(); @@ -99,7 +99,13 @@ struct CV_EXPORTS AutotunedIndexParams : public IndexParams AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1); }; - + +struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams +{ + HierarchicalClusteringIndexParams(int branching = 32, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); +}; + struct CV_EXPORTS KMeansIndexParams : public IndexParams { KMeansIndexParams(int branching = 32, int iterations = 11, @@ -110,45 +116,45 @@ struct CV_EXPORTS LshIndexParams : public IndexParams { LshIndexParams(int table_number, int key_size, int multi_probe_level); }; - + struct CV_EXPORTS SavedIndexParams : public IndexParams { SavedIndexParams(const std::string& filename); -}; - +}; + struct CV_EXPORTS SearchParams : public IndexParams { SearchParams( int checks = 32, float eps = 0, bool sorted = true ); -}; - +}; + class CV_EXPORTS_W Index { public: CV_WRAP Index(); CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); virtual ~Index(); - + CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); - CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, + CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, OutputArray dists, int knn, const SearchParams& params=SearchParams()); - + CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, OutputArray dists, double radius, int maxResults, const SearchParams& params=SearchParams()); - + CV_WRAP virtual void save(const std::string& filename) const; CV_WRAP virtual bool load(InputArray features, const std::string& filename); CV_WRAP virtual void release(); CV_WRAP cvflann::flann_distance_t getDistance() const; CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; - + protected: cvflann::flann_distance_t distType; cvflann::flann_algorithm_t algo; int featureType; void* index; }; - + } } // namespace cv::flann #endif // __cplusplus diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/nn_index.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/nn_index.h old mode 100755 new mode 100644 similarity index 97% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/nn_index.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/nn_index.h index 518babf..d14e83a --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/nn_index.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/nn_index.h @@ -114,12 +114,12 @@ class NNIndex int* indices_ptr = NULL; DistanceType* dists_ptr = NULL; if (indices.cols > 0) { - n = indices.cols; + n = (int)indices.cols; indices_ptr = indices[0]; dists_ptr = dists[0]; } - RadiusUniqueResultSet resultSet(radius); + RadiusUniqueResultSet resultSet((DistanceType)radius); resultSet.clear(); findNeighbors(resultSet, query[0], params); if (n>0) { @@ -127,7 +127,7 @@ class NNIndex else resultSet.copy(indices_ptr, dists_ptr, n); } - return resultSet.size(); + return (int)resultSet.size(); } /** diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/object_factory.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/object_factory.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/object_factory.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/object_factory.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/params.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/params.h old mode 100755 new mode 100644 similarity index 99% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/params.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/params.h index 9f3a468..fc2a906 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/params.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/params.h @@ -39,7 +39,6 @@ namespace cvflann { -typedef cdiggins::any any; typedef std::map IndexParams; struct SearchParams : public IndexParams diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/random.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/random.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/random.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/random.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/result_set.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/result_set.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/result_set.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/result_set.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/sampling.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/sampling.h old mode 100755 new mode 100644 similarity index 96% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/sampling.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/sampling.h index fd65150..396f177 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/sampling.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/sampling.h @@ -43,7 +43,7 @@ Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) T* src,* dest; for (long i=0; i random_sample(Matrix& srcMatrix, long size, bool remove = false) template Matrix random_sample(const Matrix& srcMatrix, size_t size) { - UniqueRandom rand(srcMatrix.rows); + UniqueRandom rand((int)srcMatrix.rows); Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); T* src,* dest; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/saving.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/saving.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/saving.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/saving.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/simplex_downhill.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/simplex_downhill.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/simplex_downhill.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/simplex_downhill.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/timer.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/timer.h old mode 100755 new mode 100644 similarity index 100% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/flann/timer.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/flann/timer.h diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/cap_ios.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/cap_ios.h new file mode 100644 index 0000000..5bd5fe3 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/cap_ios.h @@ -0,0 +1,163 @@ +/* + * cap_ios.h + * For iOS video I/O + * by Eduard Feicho on 29/07/12 + * Copyright 2012. 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. The name of the author may not 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. + * + */ + +#import +#import +#import +#import +#include "opencv2/core/core.hpp" + +/////////////////////////////////////// CvAbstractCamera ///////////////////////////////////// + +@class CvAbstractCamera; + +@interface CvAbstractCamera : NSObject +{ + AVCaptureSession* captureSession; + AVCaptureConnection* videoCaptureConnection; + AVCaptureVideoPreviewLayer *captureVideoPreviewLayer; + + UIDeviceOrientation currentDeviceOrientation; + + BOOL cameraAvailable; + BOOL captureSessionLoaded; + BOOL running; + BOOL useAVCaptureVideoPreviewLayer; + + AVCaptureDevicePosition defaultAVCaptureDevicePosition; + AVCaptureVideoOrientation defaultAVCaptureVideoOrientation; + NSString *const defaultAVCaptureSessionPreset; + + int defaultFPS; + + UIView* parentView; + + int imageWidth; + int imageHeight; +} + +@property (nonatomic, retain) AVCaptureSession* captureSession; +@property (nonatomic, retain) AVCaptureConnection* videoCaptureConnection; + +@property (nonatomic, readonly) BOOL running; +@property (nonatomic, readonly) BOOL captureSessionLoaded; + +@property (nonatomic, assign) int defaultFPS; +@property (nonatomic, assign) AVCaptureDevicePosition defaultAVCaptureDevicePosition; +@property (nonatomic, assign) AVCaptureVideoOrientation defaultAVCaptureVideoOrientation; +@property (nonatomic, assign) BOOL useAVCaptureVideoPreviewLayer; +@property (nonatomic, strong) NSString *const defaultAVCaptureSessionPreset; + +@property (nonatomic, assign) int imageWidth; +@property (nonatomic, assign) int imageHeight; + +@property (nonatomic, retain) UIView* parentView; + +- (void)start; +- (void)stop; +- (void)switchCameras; + +- (id)initWithParentView:(UIView*)parent; + +- (void)createCaptureOutput; +- (void)createVideoPreviewLayer; +- (void)updateOrientation; + + +@end + +///////////////////////////////// CvVideoCamera /////////////////////////////////////////// + +@class CvVideoCamera; + +@protocol CvVideoCameraDelegate + +#ifdef __cplusplus +// delegate method for processing image frames +- (void)processImage:(cv::Mat&)image; +#endif + +@end + +@interface CvVideoCamera : CvAbstractCamera +{ + AVCaptureVideoDataOutput *videoDataOutput; + + dispatch_queue_t videoDataOutputQueue; + CALayer *customPreviewLayer; + + BOOL grayscaleMode; + + BOOL recordVideo; + AVAssetWriterInput* recordAssetWriterInput; + AVAssetWriterInputPixelBufferAdaptor* recordPixelBufferAdaptor; + AVAssetWriter* recordAssetWriter; + + CMTime lastSampleTime; + +} + +@property (nonatomic, assign) id delegate; +@property (nonatomic, assign) BOOL grayscaleMode; + +@property (nonatomic, assign) BOOL recordVideo; +@property (nonatomic, retain) AVAssetWriterInput* recordAssetWriterInput; +@property (nonatomic, retain) AVAssetWriterInputPixelBufferAdaptor* recordPixelBufferAdaptor; +@property (nonatomic, retain) AVAssetWriter* recordAssetWriter; + +- (void)adjustLayoutToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; +- (void)layoutPreviewLayer; +- (void)saveVideo; +- (NSURL *)videoFileURL; + + +@end + +///////////////////////////////// CvPhotoCamera /////////////////////////////////////////// + +@class CvPhotoCamera; + +@protocol CvPhotoCameraDelegate + +- (void)photoCamera:(CvPhotoCamera*)photoCamera capturedImage:(UIImage *)image; +- (void)photoCameraCancel:(CvPhotoCamera*)photoCamera; + +@end + +@interface CvPhotoCamera : CvAbstractCamera +{ + AVCaptureStillImageOutput *stillImageOutput; +} + +@property (nonatomic, assign) id delegate; + +- (void)takePicture; + +@end diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui.hpp old mode 100755 new mode 100644 similarity index 72% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui.hpp index 969e905..57aef63 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui.hpp @@ -54,54 +54,34 @@ struct CvVideoWriter; namespace cv { -enum { WINDOW_AUTOSIZE=1 }; +enum { + // Flags for namedWindow + WINDOW_NORMAL = CV_WINDOW_NORMAL, // the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size + WINDOW_AUTOSIZE = CV_WINDOW_AUTOSIZE, // the user cannot resize the window, the size is constrainted by the image displayed + WINDOW_OPENGL = CV_WINDOW_OPENGL, // window with opengl support + + // Flags for set / getWindowProperty + WND_PROP_FULLSCREEN = CV_WND_PROP_FULLSCREEN, // fullscreen property + WND_PROP_AUTOSIZE = CV_WND_PROP_AUTOSIZE, // autosize property + WND_PROP_ASPECT_RATIO = CV_WND_PROP_ASPECTRATIO, // window's aspect ration + WND_PROP_OPENGL = CV_WND_PROP_OPENGL // opengl support +}; -CV_EXPORTS_W void namedWindow( const string& winname, int flags=WINDOW_AUTOSIZE ); -CV_EXPORTS_W void destroyWindow( const string& winname ); +CV_EXPORTS_W void namedWindow(const string& winname, int flags = WINDOW_AUTOSIZE); +CV_EXPORTS_W void destroyWindow(const string& winname); CV_EXPORTS_W void destroyAllWindows(); -CV_EXPORTS_W int startWindowThread(); -CV_EXPORTS_W void resizeWindow( const string& name, int width, int height ); -CV_EXPORTS_W void moveWindow( const string& name, int x, int y ); - -CV_EXPORTS_W void setWindowProperty(const string& winname, int prop_id, double prop_value);//YV -CV_EXPORTS_W double getWindowProperty(const string& winname, int prop_id);//YV - - -//Only for Qt -//------------------------ -CV_EXPORTS CvFont fontQt(const string& nameFont, int pointSize=-1, - Scalar color=Scalar::all(0), int weight=CV_FONT_NORMAL, - int style=CV_STYLE_NORMAL, int spacing=0); -CV_EXPORTS void addText( const Mat& img, const string& text, Point org, CvFont font); - -CV_EXPORTS void displayOverlay(const string& winname, const string& text, int delayms); -CV_EXPORTS void displayStatusBar(const string& winname, const string& text, int delayms); - -typedef void (CV_CDECL *OpenGLCallback)(void* userdata); -CV_EXPORTS void createOpenGLCallback(const string& winname, CvOpenGLCallback callbackOpenGL, void* userdata=0); - -CV_EXPORTS void saveWindowParameters(const string& windowName); -CV_EXPORTS void loadWindowParameters(const string& windowName); -CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); -CV_EXPORTS void stopLoop(); -typedef void (CV_CDECL *ButtonCallback)(int state, void* userdata); -CV_EXPORTS int createButton( const string& bar_name, ButtonCallback on_change, - void* userdata=NULL, int type=CV_PUSH_BUTTON, - bool initial_button_state=0); -//------------------------- +CV_EXPORTS_W int startWindowThread(); -CV_EXPORTS_W void imshow( const string& winname, InputArray mat ); +CV_EXPORTS_W int waitKey(int delay = 0); -typedef void (CV_CDECL *TrackbarCallback)(int pos, void* userdata); +CV_EXPORTS_W void imshow(const string& winname, InputArray mat); -CV_EXPORTS int createTrackbar( const string& trackbarname, const string& winname, - int* value, int count, - TrackbarCallback onChange=0, - void* userdata=0); +CV_EXPORTS_W void resizeWindow(const string& winname, int width, int height); +CV_EXPORTS_W void moveWindow(const string& winname, int x, int y); -CV_EXPORTS_W int getTrackbarPos( const string& trackbarname, const string& winname ); -CV_EXPORTS_W void setTrackbarPos( const string& trackbarname, const string& winname, int pos ); +CV_EXPORTS_W void setWindowProperty(const string& winname, int prop_id, double prop_value);//YV +CV_EXPORTS_W double getWindowProperty(const string& winname, int prop_id);//YV enum { @@ -126,11 +106,56 @@ enum EVENT_FLAG_SHIFTKEY =16, EVENT_FLAG_ALTKEY =32 }; - -typedef void (*MouseCallback )(int event, int x, int y, int flags, void* param); + +typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); //! assigns callback for mouse events -CV_EXPORTS void setMouseCallback( const string& windowName, MouseCallback onMouse, void* param=0); +CV_EXPORTS void setMouseCallback(const string& winname, MouseCallback onMouse, void* userdata = 0); + + +typedef void (CV_CDECL *TrackbarCallback)(int pos, void* userdata); + +CV_EXPORTS int createTrackbar(const string& trackbarname, const string& winname, + int* value, int count, + TrackbarCallback onChange = 0, + void* userdata = 0); + +CV_EXPORTS_W int getTrackbarPos(const string& trackbarname, const string& winname); +CV_EXPORTS_W void setTrackbarPos(const string& trackbarname, const string& winname, int pos); + +// OpenGL support + +typedef void (*OpenGlDrawCallback)(void* userdata); +CV_EXPORTS void setOpenGlDrawCallback(const string& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); + +CV_EXPORTS void setOpenGlContext(const string& winname); + +CV_EXPORTS void updateWindow(const string& winname); + +CV_EXPORTS void pointCloudShow(const string& winname, const GlCamera& camera, const GlArrays& arr); +CV_EXPORTS void pointCloudShow(const string& winname, const GlCamera& camera, InputArray points, InputArray colors = noArray()); + +//Only for Qt + +CV_EXPORTS CvFont fontQt(const string& nameFont, int pointSize=-1, + Scalar color=Scalar::all(0), int weight=CV_FONT_NORMAL, + int style=CV_STYLE_NORMAL, int spacing=0); +CV_EXPORTS void addText( const Mat& img, const string& text, Point org, CvFont font); + +CV_EXPORTS void displayOverlay(const string& winname, const string& text, int delayms CV_DEFAULT(0)); +CV_EXPORTS void displayStatusBar(const string& winname, const string& text, int delayms CV_DEFAULT(0)); + +CV_EXPORTS void saveWindowParameters(const string& windowName); +CV_EXPORTS void loadWindowParameters(const string& windowName); +CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); +CV_EXPORTS void stopLoop(); + +typedef void (CV_CDECL *ButtonCallback)(int state, void* userdata); +CV_EXPORTS int createButton( const string& bar_name, ButtonCallback on_change, + void* userdata=NULL, int type=CV_PUSH_BUTTON, + bool initial_button_state=0); + +//------------------------- enum { @@ -145,12 +170,13 @@ enum // ?, any color IMREAD_ANYCOLOR =4 }; - + enum { IMWRITE_JPEG_QUALITY =1, IMWRITE_PNG_COMPRESSION =16, IMWRITE_PNG_STRATEGY =17, + IMWRITE_PNG_BILEVEL =18, IMWRITE_PNG_STRATEGY_DEFAULT =0, IMWRITE_PNG_STRATEGY_FILTERED =1, IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, @@ -158,17 +184,16 @@ enum IMWRITE_PNG_STRATEGY_FIXED =4, IMWRITE_PXM_BINARY =32 }; - + CV_EXPORTS_W Mat imread( const string& filename, int flags=1 ); CV_EXPORTS_W bool imwrite( const string& filename, InputArray img, const vector& params=vector()); CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); +CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst ); CV_EXPORTS_W bool imencode( const string& ext, InputArray img, CV_OUT vector& buf, const vector& params=vector()); -CV_EXPORTS_W int waitKey(int delay=0); - #ifndef CV_NO_VIDEO_CAPTURE_CPP_API template<> void CV_EXPORTS Ptr::delete_obj(); @@ -180,40 +205,41 @@ class CV_EXPORTS_W VideoCapture CV_WRAP VideoCapture(); CV_WRAP VideoCapture(const string& filename); CV_WRAP VideoCapture(int device); - + virtual ~VideoCapture(); CV_WRAP virtual bool open(const string& filename); CV_WRAP virtual bool open(int device); CV_WRAP virtual bool isOpened() const; CV_WRAP virtual void release(); - + CV_WRAP virtual bool grab(); CV_WRAP virtual bool retrieve(CV_OUT Mat& image, int channel=0); virtual VideoCapture& operator >> (CV_OUT Mat& image); CV_WRAP virtual bool read(CV_OUT Mat& image); - + CV_WRAP virtual bool set(int propId, double value); CV_WRAP virtual double get(int propId); - + protected: Ptr cap; }; - + class CV_EXPORTS_W VideoWriter { -public: +public: CV_WRAP VideoWriter(); CV_WRAP VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true); - + virtual ~VideoWriter(); CV_WRAP virtual bool open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true); CV_WRAP virtual bool isOpened() const; + CV_WRAP virtual void release(); virtual VideoWriter& operator << (const Mat& image); CV_WRAP virtual void write(const Mat& image); - + protected: Ptr writer; }; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui_c.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui_c.h old mode 100755 new mode 100644 similarity index 76% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui_c.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui_c.h index 093578f..9c7166f --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/highgui/highgui_c.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/highgui/highgui_c.h @@ -73,16 +73,13 @@ CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvSca CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); -CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms); -CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms); - -typedef void (CV_CDECL *CvOpenGLCallback)(void* userdata); -CVAPI(void) cvCreateOpenGLCallback( const char* window_name, CvOpenGLCallback callbackOpenGL, void* userdata CV_DEFAULT(NULL), double angle CV_DEFAULT(-1), double zmin CV_DEFAULT(-1), double zmax CV_DEFAULT(-1)); +CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); +CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); CVAPI(void) cvSaveWindowParameters(const char* name); CVAPI(void) cvLoadWindowParameters(const char* name); CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); -CVAPI(void) cvStopLoop(); +CVAPI(void) cvStopLoop( void ); typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; @@ -93,24 +90,26 @@ CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCall /* this function is used to set some external parameters in case of X Window */ CVAPI(int) cvInitSystem( int argc, char** argv ); -CVAPI(int) cvStartWindowThread(); +CVAPI(int) cvStartWindowThread( void ); // --------- YV --------- enum { //These 3 flags are used by cvSet/GetWindowProperty - CV_WND_PROP_FULLSCREEN = 0,//to change/get window's fullscreen property - CV_WND_PROP_AUTOSIZE = 1,//to change/get window's autosize property - CV_WND_PROP_ASPECTRATIO= 2,//to change/get window's aspectratio property - // + CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property + CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property + CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property + CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support + //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_NORMAL = 0x00000000,//the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size - CV_WINDOW_AUTOSIZE = 0x00000001,//the user cannot resize the window, the size is constrainted by the image displayed - // + CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size + CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed + CV_WINDOW_OPENGL = 0x00001000, //window with opengl support + //Those flags are only for Qt - CV_GUI_EXPANDED = 0x00000000,//status bar and tool bar - CV_GUI_NORMAL = 0x00000010,//old fashious way - // + CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar + CV_GUI_NORMAL = 0x00000010, //old fashious way + //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) @@ -218,6 +217,7 @@ enum CV_IMWRITE_JPEG_QUALITY =1, CV_IMWRITE_PNG_COMPRESSION =16, CV_IMWRITE_PNG_STRATEGY =17, + CV_IMWRITE_PNG_BILEVEL =18, CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, CV_IMWRITE_PNG_STRATEGY_FILTERED =1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, @@ -250,6 +250,15 @@ CVAPI(void) cvConvertImage( const CvArr* src, CvArr* dst, int flags CV_DEFAULT(0 /* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); +// OpenGL support + +typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); +CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); + +CVAPI(void) cvSetOpenGlContext(const char* window_name); +CVAPI(void) cvUpdateWindow(const char* window_name); + + /****************************************************************************************\ * Working with Video Files and Cameras * \****************************************************************************************/ @@ -292,12 +301,15 @@ enum CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK CV_CAP_OPENNI =900, // OpenNI (for Kinect) + CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion) CV_CAP_ANDROID =1000, // Android - + CV_CAP_XIAPI =1100, // XIMEA Camera API - - CV_CAP_AVFOUNDATION = 1200 // AVFoundation framework for iOS (OS X Lion will have the same API) + + CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) + + CV_CAP_GIGANETIX = 1300 // Smartek Giganetix GigEVisionSDK }; /* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */ @@ -357,46 +369,67 @@ enum CV_CAP_PROP_TRIGGER =24, CV_CAP_PROP_TRIGGER_DELAY =25, CV_CAP_PROP_WHITE_BALANCE_RED_V =26, - CV_CAP_PROP_MAX_DC1394 =27, + CV_CAP_PROP_ZOOM =27, + CV_CAP_PROP_FOCUS =28, + CV_CAP_PROP_GUID =29, + CV_CAP_PROP_ISO_SPEED =30, + CV_CAP_PROP_MAX_DC1394 =31, + CV_CAP_PROP_BACKLIGHT =32, + CV_CAP_PROP_PAN =33, + CV_CAP_PROP_TILT =34, + CV_CAP_PROP_ROLL =35, + CV_CAP_PROP_IRIS =36, + CV_CAP_PROP_SETTINGS =37, + CV_CAP_PROP_AUTOGRAB =1024, // property for highgui class CvCapture_Android only CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed + // OpenNI map generators - CV_CAP_OPENNI_DEPTH_GENERATOR = 0, - CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 31, - CV_CAP_OPENNI_GENERATORS_MASK = 1 << 31, + CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, + CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, + CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR, // Properties of cameras available through OpenNI interfaces - CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, - CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm - CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm - CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels - CV_CAP_PROP_OPENNI_REGISTRATION_ON = 104, // flag - CV_CAP_PROP_OPENNI_REGISTRATION = CV_CAP_PROP_OPENNI_REGISTRATION_ON, // flag that synchronizes the remapping depth map to image map - // by changing depth generator's view point (if the flag is "on") or - // sets this view point to its normal one (if the flag is "off"). - CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, - CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, - CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, - CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION_ON, - + CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, + CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm + CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm + CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels + CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag + CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map + // by changing depth generator's view point (if the flag is "on") or + // sets this view point to its normal one (if the flag is "off"). + CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, + CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, + CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, + CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, + + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, + + CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, + CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, + CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, + // Properties of cameras available through GStreamer interface CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast - + // Properties of cameras available through XIMEA SDK interface - CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. + CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. - CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input + CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level - CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output + CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode - CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED + CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance @@ -406,13 +439,32 @@ enum CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds - + + // Properties for Android cameras + CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, + CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, + CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, + CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, + CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, + // Properties of cameras available through AVFOUNDATION interface CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CV_CAP_PROP_IOS_DEVICE_TORCH = 9005 + + // Properties of cameras available through Smartek Giganetix Ethernet Vision interface + /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ + ,CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, + CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, + CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, + CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, + CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, + CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006 }; enum @@ -433,18 +485,64 @@ enum enum { CV_CAP_OPENNI_VGA_30HZ = 0, - CV_CAP_OPENNI_SXGA_15HZ = 1 + CV_CAP_OPENNI_SXGA_15HZ = 1, + CV_CAP_OPENNI_SXGA_30HZ = 2, + CV_CAP_OPENNI_QVGA_30HZ = 3, + CV_CAP_OPENNI_QVGA_60HZ = 4 }; //supported by Android camera output formats enum { - CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR - CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR, - CV_CAP_ANDROID_GREY_FRAME = 1, //Y - CV_CAP_ANDROID_COLOR_FRAME_RGB = 2, - CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3, - CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4 + CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR + CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR, + CV_CAP_ANDROID_GREY_FRAME = 1, //Y + CV_CAP_ANDROID_COLOR_FRAME_RGB = 2, + CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3, + CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4 +}; + +// supported Android camera flash modes +enum +{ + CV_CAP_ANDROID_FLASH_MODE_AUTO = 0, + CV_CAP_ANDROID_FLASH_MODE_OFF, + CV_CAP_ANDROID_FLASH_MODE_ON, + CV_CAP_ANDROID_FLASH_MODE_RED_EYE, + CV_CAP_ANDROID_FLASH_MODE_TORCH +}; + +// supported Android camera focus modes +enum +{ + CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0, + CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO, + CV_CAP_ANDROID_FOCUS_MODE_EDOF, + CV_CAP_ANDROID_FOCUS_MODE_FIXED, + CV_CAP_ANDROID_FOCUS_MODE_INFINITY, + CV_CAP_ANDROID_FOCUS_MODE_MACRO +}; + +// supported Android camera white balance modes +enum +{ + CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0, + CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT, + CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT, + CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT, + CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT, + CV_CAP_ANDROID_WHITE_BALANCE_SHADE, + CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT, + CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT +}; + +// supported Android camera antibanding modes +enum +{ + CV_CAP_ANDROID_ANTIBANDING_50HZ = 0, + CV_CAP_ANDROID_ANTIBANDING_60HZ, + CV_CAP_ANDROID_ANTIBANDING_AUTO, + CV_CAP_ANDROID_ANTIBANDING_OFF }; /* retrieve or set capture properties */ @@ -452,14 +550,14 @@ CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id ); CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value ); // Return the type of the capturer (eg, CV_CAP_V4W, CV_CAP_UNICAP), which is unknown if created with CV_CAP_ANY -CVAPI(int) cvGetCaptureDomain( CvCapture* capture); +CVAPI(int) cvGetCaptureDomain( CvCapture* capture); /* "black box" video file writer structure */ typedef struct CvVideoWriter CvVideoWriter; CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) { - return (c1 & 255) + ((c2 & 255) << 8) + ((c3 &255) << 16) + ((c4 & 255) << 24); + return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24); } #define CV_FOURCC_PROMPT -1 /* Open Codec Selection Dialog (Windows only) */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc.hpp old mode 100755 new mode 100644 similarity index 85% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc.hpp index e0d77d3..caa2d55 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc.hpp @@ -60,20 +60,20 @@ namespace cv //! various border interpolation methods enum { BORDER_REPLICATE=IPL_BORDER_REPLICATE, BORDER_CONSTANT=IPL_BORDER_CONSTANT, - BORDER_REFLECT=IPL_BORDER_REFLECT, BORDER_WRAP=IPL_BORDER_WRAP, + BORDER_REFLECT=IPL_BORDER_REFLECT, BORDER_WRAP=IPL_BORDER_WRAP, BORDER_REFLECT_101=IPL_BORDER_REFLECT_101, BORDER_REFLECT101=BORDER_REFLECT_101, BORDER_TRANSPARENT=IPL_BORDER_TRANSPARENT, BORDER_DEFAULT=BORDER_REFLECT_101, BORDER_ISOLATED=16 }; -//! 1D interpolation function: returns coordinate of the "donor" pixel for the specified location p. +//! 1D interpolation function: returns coordinate of the "donor" pixel for the specified location p. CV_EXPORTS_W int borderInterpolate( int p, int len, int borderType ); /*! The Base Class for 1D or Row-wise Filters - + This is the base class for linear or non-linear filters that process 1D data. In particular, such filters are used for the "horizontal" filtering parts in separable filters. - + Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. */ @@ -93,17 +93,17 @@ class CV_EXPORTS BaseRowFilter /*! The Base Class for Column-wise Filters - + This is the base class for linear or non-linear filters that process columns of 2D arrays. Such filters are used for the "vertical" filtering parts in separable filters. - + Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. - + Unlike cv::BaseRowFilter, cv::BaseColumnFilter may have some context information, i.e. box filter keeps the sliding sum of elements. To reset the state BaseColumnFilter::reset() must be called (e.g. the method is called by cv::FilterEngine) - */ + */ class CV_EXPORTS BaseColumnFilter { public: @@ -121,15 +121,15 @@ class CV_EXPORTS BaseColumnFilter /*! The Base Class for Non-Separable 2D Filters. - + This is the base class for linear or non-linear 2D filters. - + Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. - + Similar to cv::BaseColumnFilter, the class may have some context information, that should be reset using BaseFilter::reset() method before processing the new array. -*/ +*/ class CV_EXPORTS BaseFilter { public: @@ -148,7 +148,7 @@ class CV_EXPORTS BaseFilter /*! The Main Class for Image Filtering. - + The class can be used to apply an arbitrary filtering operation to an image. It contains all the necessary intermediate buffers, it computes extrapolated values of the "virtual" pixels outside of the image etc. @@ -156,45 +156,45 @@ class CV_EXPORTS BaseFilter are returned by various OpenCV functions, such as cv::createSeparableLinearFilter(), cv::createLinearFilter(), cv::createGaussianFilter(), cv::createDerivFilter(), cv::createBoxFilter() and cv::createMorphologyFilter(). - + Using the class you can process large images by parts and build complex pipelines that include filtering as some of the stages. If all you need is to apply some pre-defined filtering operation, you may use cv::filter2D(), cv::erode(), cv::dilate() etc. functions that create FilterEngine internally. - + Here is the example on how to use the class to implement Laplacian operator, which is the sum of second-order derivatives. More complex variant for different types is implemented in cv::Laplacian(). - + \code void laplace_f(const Mat& src, Mat& dst) { CV_Assert( src.type() == CV_32F ); // make sure the destination array has the proper size and type dst.create(src.size(), src.type()); - + // get the derivative and smooth kernels for d2I/dx2. // for d2I/dy2 we could use the same kernels, just swapped Mat kd, ks; getSobelKernels( kd, ks, 2, 0, ksize, false, ktype ); - + // let's process 10 source rows at once int DELTA = std::min(10, src.rows); Ptr Fxx = createSeparableLinearFilter(src.type(), - dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() ); + dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() ); Ptr Fyy = createSeparableLinearFilter(src.type(), dst.type(), ks, kd, Point(-1,-1), 0, borderType, borderType, Scalar() ); - + int y = Fxx->start(src), dsty = 0, dy = 0; Fyy->start(src); const uchar* sptr = src.data + y*src.step; - + // allocate the buffers for the spatial image derivatives; // the buffers need to have more than DELTA rows, because at the // last iteration the output may take max(kd.rows-1,ks.rows-1) // rows more than the input. Mat Ixx( DELTA + kd.rows - 1, src.cols, dst.type() ); Mat Iyy( DELTA + kd.rows - 1, src.cols, dst.type() ); - + // inside the loop we always pass DELTA rows to the filter // (note that the "proceed" method takes care of possibe overflow, since // it was given the actual image height in the "start" method) @@ -241,7 +241,7 @@ class CV_EXPORTS FilterEngine int srcType, int dstType, int bufType, int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1, const Scalar& _borderValue=Scalar()); - //! starts filtering of the specified ROI of an image of size wholeSize. + //! starts filtering of the specified ROI of an image of size wholeSize. virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1); //! starts filtering of the specified ROI of the specified image. virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1), @@ -256,10 +256,10 @@ class CV_EXPORTS FilterEngine bool isolated=false); //! returns true if the filter is separable bool isSeparable() const { return (const BaseFilter*)filter2D == 0; } - //! returns the number + //! returns the number int remainingInputRows() const; int remainingOutputRows() const; - + int srcType, dstType, bufType; Size ksize; Point anchor; @@ -276,7 +276,7 @@ class CV_EXPORTS FilterEngine vector constBorderRow; int bufStep, startY, startY0, endY, rowCount, dstY; vector rows; - + Ptr filter2D; Ptr rowFilter; Ptr columnFilter; @@ -309,16 +309,16 @@ CV_EXPORTS Ptr getLinearFilter(int srcType, int dstType, //! returns the separable linear filter engine CV_EXPORTS Ptr createSeparableLinearFilter(int srcType, int dstType, InputArray rowKernel, InputArray columnKernel, - Point _anchor=Point(-1,-1), double delta=0, - int _rowBorderType=BORDER_DEFAULT, - int _columnBorderType=-1, - const Scalar& _borderValue=Scalar()); + Point anchor=Point(-1,-1), double delta=0, + int rowBorderType=BORDER_DEFAULT, + int columnBorderType=-1, + const Scalar& borderValue=Scalar()); //! returns the non-separable linear filter engine CV_EXPORTS Ptr createLinearFilter(int srcType, int dstType, InputArray kernel, Point _anchor=Point(-1,-1), - double delta=0, int _rowBorderType=BORDER_DEFAULT, - int _columnBorderType=-1, const Scalar& _borderValue=Scalar()); + double delta=0, int rowBorderType=BORDER_DEFAULT, + int columnBorderType=-1, const Scalar& borderValue=Scalar()); //! returns the Gaussian kernel with the specified parameters CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype=CV_64F ); @@ -335,7 +335,7 @@ CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, CV_EXPORTS Ptr createDerivFilter( int srcType, int dstType, int dx, int dy, int ksize, int borderType=BORDER_DEFAULT ); -//! returns horizontal 1D box filter +//! returns horizontal 1D box filter CV_EXPORTS Ptr getRowSumFilter(int srcType, int sumType, int ksize, int anchor=-1); //! returns vertical 1D box filter @@ -347,6 +347,11 @@ CV_EXPORTS Ptr createBoxFilter( int srcType, int dstType, Size ksi Point anchor=Point(-1,-1), bool normalize=true, int borderType=BORDER_DEFAULT); + +//! returns the Gabor kernel with the specified parameters +CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, + double gamma, double psi=CV_PI*0.5, int ktype=CV_64F ); + //! type of morphological operation enum { MORPH_ERODE=CV_MOP_ERODE, MORPH_DILATE=CV_MOP_DILATE, MORPH_OPEN=CV_MOP_OPEN, MORPH_CLOSE=CV_MOP_CLOSE, @@ -360,15 +365,15 @@ CV_EXPORTS Ptr getMorphologyColumnFilter(int op, int type, int //! returns 2D morphological filter CV_EXPORTS Ptr getMorphologyFilter(int op, int type, InputArray kernel, Point anchor=Point(-1,-1)); - + //! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported. CV_EXPORTS Ptr createMorphologyFilter(int op, int type, InputArray kernel, - Point anchor=Point(-1,-1), int _rowBorderType=BORDER_CONSTANT, - int _columnBorderType=-1, - const Scalar& _borderValue=morphologyDefaultBorderValue()); + Point anchor=Point(-1,-1), int rowBorderType=BORDER_CONSTANT, + int columnBorderType=-1, + const Scalar& borderValue=morphologyDefaultBorderValue()); //! shape of the structuring element enum { MORPH_RECT=0, MORPH_CROSS=1, MORPH_ELLIPSE=2 }; @@ -377,7 +382,7 @@ CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor=Point template<> CV_EXPORTS void Ptr::delete_obj(); -//! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode +//! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode CV_EXPORTS_W void copyMakeBorder( InputArray src, OutputArray dst, int top, int bottom, int left, int right, int borderType, const Scalar& value=Scalar() ); @@ -387,7 +392,7 @@ CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); //! smooths the image using Gaussian filter. CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, - double sigma1, double sigma2=0, + double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT ); //! smooths the image using bilateral filter CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, @@ -413,7 +418,7 @@ CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernelX, InputArray kernelY, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT ); - + //! applies generalized Sobel operator to the image CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize=3, @@ -445,6 +450,9 @@ CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, int ksize, double k, int borderType=BORDER_DEFAULT ); +// low-level function for computing eigenvalues and eigenvectors of 2x2 matrices +CV_EXPORTS void eigen2x2( const float* a, float* e, int n ); + //! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix. CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int ksize, @@ -475,24 +483,60 @@ CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength=0, double maxLineGap=0 ); -//! finds circles in the grayscale image using 2+1 gradient Hough transform +//! finds circles in the grayscale image using 2+1 gradient Hough transform CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0 ); +enum +{ + GHT_POSITION = 0, + GHT_SCALE = 1, + GHT_ROTATION = 2 +}; + +//! finds arbitrary template in the grayscale image using Generalized Hough Transform +//! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. +//! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. +class CV_EXPORTS GeneralizedHough : public Algorithm +{ +public: + static Ptr create(int method); + + virtual ~GeneralizedHough(); + + //! set template to search + void setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1)); + void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)); + + //! find template on image + void detect(InputArray image, OutputArray positions, OutputArray votes = cv::noArray(), int cannyThreshold = 100); + void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = cv::noArray()); + + void release(); + +protected: + virtual void setTemplateImpl(const Mat& edges, const Mat& dx, const Mat& dy, Point templCenter) = 0; + virtual void detectImpl(const Mat& edges, const Mat& dx, const Mat& dy, OutputArray positions, OutputArray votes) = 0; + virtual void releaseImpl() = 0; + +private: + Mat edges_, dx_, dy_; +}; + //! erodes the image (applies the local minimum operator) CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() ); - + //! dilates the image (applies the local maximum operator) CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() ); - + //! applies an advanced morphological operation to the image CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, @@ -523,7 +567,7 @@ CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar()); - + //! warps the image using perspective transformation CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, @@ -548,7 +592,7 @@ CV_EXPORTS_W void remap( InputArray src, OutputArray dst, CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation=false ); - + //! returns 2x3 affine transformation matrix for the planar rotation. CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale ); //! returns 3x3 perspective transformation for the corresponding 4 point pairs. @@ -589,9 +633,15 @@ CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2, CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst, double alpha, InputArray mask=noArray() ); -CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, InputArray window = noArray()); +//! computes PSNR image/video quality metric +CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2); + +CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, + InputArray window = noArray()); +CV_EXPORTS_W Point2d phaseCorrelateRes(InputArray src1, InputArray src2, + InputArray window, CV_OUT double* response = 0); CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); - + //! type of the threshold operation enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV, THRESH_TRUNC=CV_THRESH_TRUNC, THRESH_TOZERO=CV_THRESH_TOZERO, @@ -612,20 +662,21 @@ CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, //! smooths and downsamples the image CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, - const Size& dstsize=Size()); + const Size& dstsize=Size(), int borderType=BORDER_DEFAULT ); //! upsamples and smoothes the image CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, - const Size& dstsize=Size()); + const Size& dstsize=Size(), int borderType=BORDER_DEFAULT ); //! builds the gaussian pyramid using pyrDown() as a basic operation -CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel ); +CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, + int maxlevel, int borderType=BORDER_DEFAULT ); //! corrects lens distortion for the given camera matrix and distortion coefficients CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix=noArray() ); - + //! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, @@ -635,25 +686,25 @@ enum { PROJ_SPHERICAL_ORTHO = 0, PROJ_SPHERICAL_EQRECT = 1 -}; - +}; + //! initializes maps for cv::remap() for wide-angle CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, int destImageWidth, int m1type, OutputArray map1, OutputArray map2, int projType=PROJ_SPHERICAL_EQRECT, double alpha=0); - + //! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true) CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize=Size(), bool centerPrincipalPoint=false ); - + //! returns points' coordinates after lens distortion correction -CV_EXPORTS void undistortPoints( InputArray src, OutputArray dst, - InputArray cameraMatrix, InputArray distCoeffs, - InputArray R=noArray(), InputArray P=noArray()); +CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst, + InputArray cameraMatrix, InputArray distCoeffs, + InputArray R=noArray(), InputArray P=noArray()); template<> CV_EXPORTS void Ptr::delete_obj(); - + //! computes the joint dense histogram for a set of images. CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, @@ -666,7 +717,7 @@ CV_EXPORTS void calcHist( const Mat* images, int nimages, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false ); - + CV_EXPORTS_W void calcHist( InputArrayOfArrays images, const vector& channels, InputArray mask, OutputArray hist, @@ -682,7 +733,7 @@ CV_EXPORTS void calcBackProject( const Mat* images, int nimages, //! computes back projection for the set of images CV_EXPORTS void calcBackProject( const Mat* images, int nimages, - const int* channels, const SparseMat& hist, + const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale=1, bool uniform=true ); @@ -691,6 +742,14 @@ CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const vector& const vector& ranges, double scale ); +/*CV_EXPORTS void calcBackProjectPatch( const Mat* images, int nimages, const int* channels, + InputArray hist, OutputArray dst, Size patchSize, + int method, double factor=1 ); + +CV_EXPORTS_W void calcBackProjectPatch( InputArrayOfArrays images, const vector& channels, + InputArray hist, OutputArray dst, Size patchSize, + int method, double factor=1 );*/ + //! compares two histograms stored in dense arrays CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); @@ -699,7 +758,7 @@ CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int met //! normalizes the grayscale image brightness and contrast by normalizing its histogram CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); - + CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound=0, OutputArray flow=noArray() ); @@ -719,7 +778,7 @@ enum GC_BGD = 0, //!< background GC_FGD = 1, //!< foreground GC_PR_BGD = 2, //!< most probably background - GC_PR_FGD = 3 //!< most probably foreground + GC_PR_FGD = 3 //!< most probably foreground }; //! GrabCut algorithm flags @@ -731,28 +790,24 @@ enum }; //! segments the image using GrabCut algorithm -CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, +CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode = GC_EVAL ); -//! the inpainting algorithm enum { - INPAINT_NS=CV_INPAINT_NS, // Navier-Stokes algorithm - INPAINT_TELEA=CV_INPAINT_TELEA // A. Telea algorithm + DIST_LABEL_CCOMP = 0, + DIST_LABEL_PIXEL = 1 }; -//! restores the damaged image areas using one of the available intpainting algorithms -CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, - OutputArray dst, double inpaintRange, int flags ); - //! builds the discrete Voronoi diagram -CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, - OutputArray labels, int distanceType, int maskSize ); +CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, + OutputArray labels, int distanceType, int maskSize, + int labelType=DIST_LABEL_CCOMP ); //! computes the distance transform map -CV_EXPORTS void distanceTransform( InputArray src, OutputArray dst, - int distanceType, int maskSize ); +CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, + int distanceType, int maskSize ); enum { FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17 }; @@ -768,27 +823,27 @@ CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), int flags=4 ); - + enum { COLOR_BGR2BGRA =0, COLOR_RGB2RGBA =COLOR_BGR2BGRA, - + COLOR_BGRA2BGR =1, COLOR_RGBA2RGB =COLOR_BGRA2BGR, - + COLOR_BGR2RGBA =2, COLOR_RGB2BGRA =COLOR_BGR2RGBA, - + COLOR_RGBA2BGR =3, COLOR_BGRA2RGB =COLOR_RGBA2BGR, - + COLOR_BGR2RGB =4, COLOR_RGB2BGR =COLOR_BGR2RGB, - + COLOR_BGRA2RGBA =5, COLOR_RGBA2BGRA =COLOR_BGRA2RGBA, - + COLOR_BGR2GRAY =6, COLOR_RGB2GRAY =7, COLOR_GRAY2BGR =8, @@ -797,7 +852,7 @@ enum COLOR_GRAY2RGBA =COLOR_GRAY2BGRA, COLOR_BGRA2GRAY =10, COLOR_RGBA2GRAY =11, - + COLOR_BGR2BGR565 =12, COLOR_RGB2BGR565 =13, COLOR_BGR5652BGR =14, @@ -806,10 +861,10 @@ enum COLOR_RGBA2BGR565 =17, COLOR_BGR5652BGRA =18, COLOR_BGR5652RGBA =19, - + COLOR_GRAY2BGR565 =20, COLOR_BGR5652GRAY =21, - + COLOR_BGR2BGR555 =22, COLOR_RGB2BGR555 =23, COLOR_BGR5552BGR =24, @@ -818,105 +873,187 @@ enum COLOR_RGBA2BGR555 =27, COLOR_BGR5552BGRA =28, COLOR_BGR5552RGBA =29, - + COLOR_GRAY2BGR555 =30, COLOR_BGR5552GRAY =31, - + COLOR_BGR2XYZ =32, COLOR_RGB2XYZ =33, COLOR_XYZ2BGR =34, COLOR_XYZ2RGB =35, - + COLOR_BGR2YCrCb =36, COLOR_RGB2YCrCb =37, COLOR_YCrCb2BGR =38, COLOR_YCrCb2RGB =39, - + COLOR_BGR2HSV =40, COLOR_RGB2HSV =41, - + COLOR_BGR2Lab =44, COLOR_RGB2Lab =45, - + COLOR_BayerBG2BGR =46, COLOR_BayerGB2BGR =47, COLOR_BayerRG2BGR =48, COLOR_BayerGR2BGR =49, - + COLOR_BayerBG2RGB =COLOR_BayerRG2BGR, COLOR_BayerGB2RGB =COLOR_BayerGR2BGR, COLOR_BayerRG2RGB =COLOR_BayerBG2BGR, COLOR_BayerGR2RGB =COLOR_BayerGB2BGR, - + COLOR_BGR2Luv =50, COLOR_RGB2Luv =51, COLOR_BGR2HLS =52, COLOR_RGB2HLS =53, - + COLOR_HSV2BGR =54, COLOR_HSV2RGB =55, - + COLOR_Lab2BGR =56, COLOR_Lab2RGB =57, COLOR_Luv2BGR =58, COLOR_Luv2RGB =59, COLOR_HLS2BGR =60, COLOR_HLS2RGB =61, - + COLOR_BayerBG2BGR_VNG =62, COLOR_BayerGB2BGR_VNG =63, COLOR_BayerRG2BGR_VNG =64, COLOR_BayerGR2BGR_VNG =65, - + COLOR_BayerBG2RGB_VNG =COLOR_BayerRG2BGR_VNG, COLOR_BayerGB2RGB_VNG =COLOR_BayerGR2BGR_VNG, COLOR_BayerRG2RGB_VNG =COLOR_BayerBG2BGR_VNG, COLOR_BayerGR2RGB_VNG =COLOR_BayerGB2BGR_VNG, - + COLOR_BGR2HSV_FULL = 66, COLOR_RGB2HSV_FULL = 67, COLOR_BGR2HLS_FULL = 68, COLOR_RGB2HLS_FULL = 69, - + COLOR_HSV2BGR_FULL = 70, COLOR_HSV2RGB_FULL = 71, COLOR_HLS2BGR_FULL = 72, COLOR_HLS2RGB_FULL = 73, - + COLOR_LBGR2Lab = 74, COLOR_LRGB2Lab = 75, COLOR_LBGR2Luv = 76, COLOR_LRGB2Luv = 77, - + COLOR_Lab2LBGR = 78, COLOR_Lab2LRGB = 79, COLOR_Luv2LBGR = 80, COLOR_Luv2LRGB = 81, - + COLOR_BGR2YUV = 82, COLOR_RGB2YUV = 83, COLOR_YUV2BGR = 84, COLOR_YUV2RGB = 85, - + COLOR_BayerBG2GRAY = 86, COLOR_BayerGB2GRAY = 87, COLOR_BayerRG2GRAY = 88, COLOR_BayerGR2GRAY = 89, - - COLOR_YUV420i2RGB = 90, - COLOR_YUV420i2BGR = 91, - COLOR_YUV420sp2RGB = 92, - COLOR_YUV420sp2BGR = 93, - - COLOR_YUV420i2RGBA = 94, - COLOR_YUV420i2BGRA = 95, - COLOR_YUV420sp2RGBA = 96, - COLOR_YUV420sp2BGRA = 97, - - COLOR_COLORCVT_MAX =100 + + //YUV 4:2:0 formats family + COLOR_YUV2RGB_NV12 = 90, + COLOR_YUV2BGR_NV12 = 91, + COLOR_YUV2RGB_NV21 = 92, + COLOR_YUV2BGR_NV21 = 93, + COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, + COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, + + COLOR_YUV2RGBA_NV12 = 94, + COLOR_YUV2BGRA_NV12 = 95, + COLOR_YUV2RGBA_NV21 = 96, + COLOR_YUV2BGRA_NV21 = 97, + COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, + COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, + + COLOR_YUV2RGB_YV12 = 98, + COLOR_YUV2BGR_YV12 = 99, + COLOR_YUV2RGB_IYUV = 100, + COLOR_YUV2BGR_IYUV = 101, + COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, + COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, + COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, + COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, + + COLOR_YUV2RGBA_YV12 = 102, + COLOR_YUV2BGRA_YV12 = 103, + COLOR_YUV2RGBA_IYUV = 104, + COLOR_YUV2BGRA_IYUV = 105, + COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, + COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, + COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, + COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, + + COLOR_YUV2GRAY_420 = 106, + COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, + COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, + COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, + COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, + COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, + COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, + COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, + + //YUV 4:2:2 formats family + COLOR_YUV2RGB_UYVY = 107, + COLOR_YUV2BGR_UYVY = 108, + //COLOR_YUV2RGB_VYUY = 109, + //COLOR_YUV2BGR_VYUY = 110, + COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, + COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, + COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, + COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, + + COLOR_YUV2RGBA_UYVY = 111, + COLOR_YUV2BGRA_UYVY = 112, + //COLOR_YUV2RGBA_VYUY = 113, + //COLOR_YUV2BGRA_VYUY = 114, + COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, + COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, + COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, + COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, + + COLOR_YUV2RGB_YUY2 = 115, + COLOR_YUV2BGR_YUY2 = 116, + COLOR_YUV2RGB_YVYU = 117, + COLOR_YUV2BGR_YVYU = 118, + COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, + COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, + COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, + COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, + + COLOR_YUV2RGBA_YUY2 = 119, + COLOR_YUV2BGRA_YUY2 = 120, + COLOR_YUV2RGBA_YVYU = 121, + COLOR_YUV2BGRA_YVYU = 122, + COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, + COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, + COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, + COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, + + COLOR_YUV2GRAY_UYVY = 123, + COLOR_YUV2GRAY_YUY2 = 124, + //COLOR_YUV2GRAY_VYUY = COLOR_YUV2GRAY_UYVY, + COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, + COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, + COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, + COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, + COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, + + // alpha premultiplication + COLOR_RGBA2mRGBA = 125, + COLOR_mRGBA2RGBA = 126, + + COLOR_COLORCVT_MAX = 127 }; - - + + //! converts image from one color space to another CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 ); @@ -933,7 +1070,7 @@ class CV_EXPORTS_W_MAP Moments Moments( const CvMoments& moments ); //! the conversion to CvMoments operator CvMoments() const; - + //! spatial moments CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; //! central moments @@ -962,7 +1099,8 @@ enum RETR_EXTERNAL=CV_RETR_EXTERNAL, //!< retrieve only the most external (top-level) contours RETR_LIST=CV_RETR_LIST, //!< retrieve all the contours without any hierarchical information RETR_CCOMP=CV_RETR_CCOMP, //!< retrieve the connected components (that can possibly be nested) - RETR_TREE=CV_RETR_TREE //!< retrieve all the contours and the whole hierarchy + RETR_TREE=CV_RETR_TREE, //!< retrieve all the contours and the whole hierarchy + RETR_FLOODFILL=CV_RETR_FLOODFILL }; //! the contour approximation algorithm @@ -1005,17 +1143,23 @@ CV_EXPORTS_W double contourArea( InputArray contour, bool oriented=false ); CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); //! computes the minimal enclosing circle for a set of points CV_EXPORTS_W void minEnclosingCircle( InputArray points, - CV_OUT Point2f& center, CV_OUT float& radius ); + CV_OUT Point2f& center, CV_OUT float& radius ); //! matches two contours using one of the available algorithms CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter ); //! computes convex hull for a set of 2D points. CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true ); +//! computes the contour convexity defects +CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); -//! returns true iff the contour is convex. Does not support contours with self-intersection +//! returns true if the contour is convex. Does not support contours with self-intersection CV_EXPORTS_W bool isContourConvex( InputArray contour ); +//! finds intersection of two convex polygons +CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2, + OutputArray _p12, bool handleNested=true ); + //! fits ellipse to the set of 2D points CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); @@ -1024,7 +1168,7 @@ CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps ); //! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); - + class CV_EXPORTS_W Subdiv2D { @@ -1037,7 +1181,7 @@ class CV_EXPORTS_W Subdiv2D PTLOC_VERTEX = 1, PTLOC_ON_EDGE = 2 }; - + enum { NEXT_AROUND_ORG = 0x00, @@ -1049,30 +1193,30 @@ class CV_EXPORTS_W Subdiv2D PREV_AROUND_LEFT = 0x20, PREV_AROUND_RIGHT = 0x02 }; - + CV_WRAP Subdiv2D(); CV_WRAP Subdiv2D(Rect rect); CV_WRAP void initDelaunay(Rect rect); - + CV_WRAP int insert(Point2f pt); CV_WRAP void insert(const vector& ptvec); CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); - + CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt=0); CV_WRAP void getEdgeList(CV_OUT vector& edgeList) const; CV_WRAP void getTriangleList(CV_OUT vector& triangleList) const; CV_WRAP void getVoronoiFacetList(const vector& idx, CV_OUT vector >& facetList, CV_OUT vector& facetCenters); - + CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge=0) const; - + CV_WRAP int getEdge( int edge, int nextEdgeType ) const; CV_WRAP int nextEdge(int edge) const; CV_WRAP int rotateEdge(int edge, int rotate) const; CV_WRAP int symEdge(int edge) const; CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt=0) const; CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt=0) const; - + protected: int newEdge(); void deleteEdge(int edge); @@ -1086,7 +1230,7 @@ class CV_EXPORTS_W Subdiv2D void calcVoronoi(); void clearVoronoi(); void checkSubdiv() const; - + struct CV_EXPORTS Vertex { Vertex(); @@ -1105,13 +1249,13 @@ class CV_EXPORTS_W Subdiv2D int next[4]; int pt[4]; }; - + vector vtx; vector qedges; int freeQEdge; int freePoint; bool validGeometry; - + int recentEdge; Point2f topLeft; Point2f bottomRight; @@ -1119,27 +1263,6 @@ class CV_EXPORTS_W Subdiv2D } -// 2009-01-12, Xavier Delacour - -struct lsh_hash { - int h1, h2; -}; - -struct CvLSHOperations -{ - virtual ~CvLSHOperations() {} - - virtual int vector_add(const void* data) = 0; - virtual void vector_remove(int i) = 0; - virtual const void* vector_lookup(int i) = 0; - virtual void vector_reserve(int n) = 0; - virtual unsigned int vector_count() = 0; - - virtual void hash_insert(lsh_hash h, int l, int i) = 0; - virtual void hash_remove(lsh_hash h, int l, int i) = 0; - virtual int hash_lookup(lsh_hash h, int l, int* ret_i, int ret_i_max) = 0; -}; - #endif /* __cplusplus */ #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc_c.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc_c.h old mode 100755 new mode 100644 similarity index 81% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc_c.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc_c.h index b845e1c..c7b525c --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/imgproc_c.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/imgproc_c.h @@ -67,7 +67,7 @@ CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc /* Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha */ CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, const CvArr* mask CV_DEFAULT(NULL) ); - + /****************************************************************************************\ * Image Processing * \****************************************************************************************/ @@ -121,15 +121,6 @@ CVAPI(CvMat**) cvCreatePyramid( const CvArr* img, int extra_layers, double rate, CVAPI(void) cvReleasePyramid( CvMat*** pyramid, int extra_layers ); -/* Splits color or grayscale image into multiple connected components - of nearly the same color/brightness using modification of Burt algorithm. - comp with contain a pointer to sequence (CvSeq) - of connected components (CvConnectedComp) */ -CVAPI(void) cvPyrSegmentation( IplImage* src, IplImage* dst, - CvMemStorage* storage, CvSeq** comp, - int level, double threshold1, - double threshold2 ); - /* Filters image using meanshift algorithm */ CVAPI(void) cvPyrMeanShiftFiltering( const CvArr* src, CvArr* dst, double sp, double sr, int max_level CV_DEFAULT(1), @@ -138,10 +129,6 @@ CVAPI(void) cvPyrMeanShiftFiltering( const CvArr* src, CvArr* dst, /* Segments image using seed "markers" */ CVAPI(void) cvWatershed( const CvArr* image, CvArr* markers ); -/* Inpaints the selected region in the image */ -CVAPI(void) cvInpaint( const CvArr* src, const CvArr* inpaint_mask, - CvArr* dst, double inpaintRange, int flags ); - /* Calculates an image derivative using generalized Sobel (aperture_size = 1,3,5,7) or Scharr (aperture_size = -1) operator. Scharr can be used only for the first dx or dy derivative */ @@ -355,99 +342,6 @@ CVAPI(void) cvStartReadChainPoints( CvChain* chain, CvChainPtReader* reader ); /* Retrieves the next chain point */ CVAPI(CvPoint) cvReadChainPoint( CvChainPtReader* reader ); -/****************************************************************************************\ -* Planar subdivisions * -\****************************************************************************************/ - -/* Initializes Delaunay triangulation */ -CVAPI(void) cvInitSubdivDelaunay2D( CvSubdiv2D* subdiv, CvRect rect ); - -/* Creates new subdivision */ -CVAPI(CvSubdiv2D*) cvCreateSubdiv2D( int subdiv_type, int header_size, - int vtx_size, int quadedge_size, - CvMemStorage* storage ); - -/************************* high-level subdivision functions ***************************/ - -/* Simplified Delaunay diagram creation */ -CV_INLINE CvSubdiv2D* cvCreateSubdivDelaunay2D( CvRect rect, CvMemStorage* storage ) -{ - CvSubdiv2D* subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv), - sizeof(CvSubdiv2DPoint), sizeof(CvQuadEdge2D), storage ); - - cvInitSubdivDelaunay2D( subdiv, rect ); - return subdiv; -} - - -/* Inserts new point to the Delaunay triangulation */ -CVAPI(CvSubdiv2DPoint*) cvSubdivDelaunay2DInsert( CvSubdiv2D* subdiv, CvPoint2D32f pt); - -/* Locates a point within the Delaunay triangulation (finds the edge - the point is left to or belongs to, or the triangulation point the given - point coinsides with */ -CVAPI(CvSubdiv2DPointLocation) cvSubdiv2DLocate( - CvSubdiv2D* subdiv, CvPoint2D32f pt, - CvSubdiv2DEdge* edge, - CvSubdiv2DPoint** vertex CV_DEFAULT(NULL) ); - -/* Calculates Voronoi tesselation (i.e. coordinates of Voronoi points) */ -CVAPI(void) cvCalcSubdivVoronoi2D( CvSubdiv2D* subdiv ); - - -/* Removes all Voronoi points from the tesselation */ -CVAPI(void) cvClearSubdivVoronoi2D( CvSubdiv2D* subdiv ); - - -/* Finds the nearest to the given point vertex in subdivision. */ -CVAPI(CvSubdiv2DPoint*) cvFindNearestPoint2D( CvSubdiv2D* subdiv, CvPoint2D32f pt ); - - -/************ Basic quad-edge navigation and operations ************/ - -CV_INLINE CvSubdiv2DEdge cvSubdiv2DNextEdge( CvSubdiv2DEdge edge ) -{ - return CV_SUBDIV2D_NEXT_EDGE(edge); -} - - -CV_INLINE CvSubdiv2DEdge cvSubdiv2DRotateEdge( CvSubdiv2DEdge edge, int rotate ) -{ - return (edge & ~3) + ((edge + rotate) & 3); -} - -CV_INLINE CvSubdiv2DEdge cvSubdiv2DSymEdge( CvSubdiv2DEdge edge ) -{ - return edge ^ 2; -} - -CV_INLINE CvSubdiv2DEdge cvSubdiv2DGetEdge( CvSubdiv2DEdge edge, CvNextEdgeType type ) -{ - CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); - edge = e->next[(edge + (int)type) & 3]; - return (edge & ~3) + ((edge + ((int)type >> 4)) & 3); -} - - -CV_INLINE CvSubdiv2DPoint* cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge ) -{ - CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); - return (CvSubdiv2DPoint*)e->pt[edge & 3]; -} - - -CV_INLINE CvSubdiv2DPoint* cvSubdiv2DEdgeDst( CvSubdiv2DEdge edge ) -{ - CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); - return (CvSubdiv2DPoint*)e->pt[(edge + 2) & 3]; -} - - -CV_INLINE double cvTriangleArea( CvPoint2D32f a, CvPoint2D32f b, CvPoint2D32f c ) -{ - return ((double)b.x - a.x) * ((double)c.y - a.y) - ((double)b.y - a.y) * ((double)c.x - a.x); -} - /****************************************************************************************\ * Contour Processing and Shape Analysis * @@ -457,8 +351,8 @@ CV_INLINE double cvTriangleArea( CvPoint2D32f a, CvPoint2D32f b, CvPoint2D32f a tree of polygonal curves (contours) */ CVAPI(CvSeq*) cvApproxPoly( const void* src_seq, int header_size, CvMemStorage* storage, - int method, double parameter, - int parameter2 CV_DEFAULT(0)); + int method, double eps, + int recursive CV_DEFAULT(0)); /* Calculates perimeter of a contour or length of a part of contour */ CVAPI(double) cvArcLength( const void* curve, @@ -624,7 +518,8 @@ CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, int distance_type CV_DEFAULT(CV_DIST_L2), int mask_size CV_DEFAULT(3), const float* mask CV_DEFAULT(NULL), - CvArr* labels CV_DEFAULT(NULL)); + CvArr* labels CV_DEFAULT(NULL), + int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); /* Applies fixed-level threshold to grayscale image. @@ -721,61 +616,6 @@ CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, double reps, double aeps, float* line ); - -/* Constructs kd-tree from set of feature descriptors */ -CVAPI(struct CvFeatureTree*) cvCreateKDTree(CvMat* desc); - -/* Constructs spill-tree from set of feature descriptors */ -CVAPI(struct CvFeatureTree*) cvCreateSpillTree( const CvMat* raw_data, - const int naive CV_DEFAULT(50), - const double rho CV_DEFAULT(.7), - const double tau CV_DEFAULT(.1) ); - -/* Release feature tree */ -CVAPI(void) cvReleaseFeatureTree(struct CvFeatureTree* tr); - -/* Searches feature tree for k nearest neighbors of given reference points, - searching (in case of kd-tree/bbf) at most emax leaves. */ -CVAPI(void) cvFindFeatures(struct CvFeatureTree* tr, const CvMat* query_points, - CvMat* indices, CvMat* dist, int k, int emax CV_DEFAULT(20)); - -/* Search feature tree for all points that are inlier to given rect region. - Only implemented for kd trees */ -CVAPI(int) cvFindFeaturesBoxed(struct CvFeatureTree* tr, - CvMat* bounds_min, CvMat* bounds_max, - CvMat* out_indices); - - -/* Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of - given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. */ -CVAPI(struct CvLSH*) cvCreateLSH(struct CvLSHOperations* ops, int d, - int L CV_DEFAULT(10), int k CV_DEFAULT(10), - int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4), - int64 seed CV_DEFAULT(-1)); - -/* Construct in-memory LSH table, with n bins. */ -CVAPI(struct CvLSH*) cvCreateMemoryLSH(int d, int n, int L CV_DEFAULT(10), int k CV_DEFAULT(10), - int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4), - int64 seed CV_DEFAULT(-1)); - -/* Free the given LSH structure. */ -CVAPI(void) cvReleaseLSH(struct CvLSH** lsh); - -/* Return the number of vectors in the LSH. */ -CVAPI(unsigned int) LSHSize(struct CvLSH* lsh); - -/* Add vectors to the LSH structure, optionally returning indices. */ -CVAPI(void) cvLSHAdd(struct CvLSH* lsh, const CvMat* data, CvMat* indices CV_DEFAULT(0)); - -/* Remove vectors from LSH, as addressed by given indices. */ -CVAPI(void) cvLSHRemove(struct CvLSH* lsh, const CvMat* indices); - -/* Query the LSH n times for at most k nearest points; data is n x d, - indices and dist are n x k. At most emax stored points will be accessed. */ -CVAPI(void) cvLSHQuery(struct CvLSH* lsh, const CvMat* query_points, - CvMat* indices, CvMat* dist, int k, int emax); - - #ifdef __cplusplus } #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/types_c.h b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/types_c.h old mode 100755 new mode 100644 similarity index 81% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/types_c.h rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/types_c.h index 0b76918..0e4f0a2 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/imgproc/types_c.h +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/imgproc/types_c.h @@ -44,7 +44,6 @@ #define __OPENCV_IMGPROC_TYPES_C_H__ #include "opencv2/core/core_c.h" -#include "opencv2/imgproc/types_c.h" #ifdef __cplusplus extern "C" { @@ -77,13 +76,6 @@ enum CV_GAUSSIAN_5x5 = 7 }; -/* Inpainting algorithms */ -enum -{ - CV_INPAINT_NS =0, - CV_INPAINT_TELEA =1 -}; - /* Special filters */ enum { @@ -190,53 +182,135 @@ enum CV_BayerGB2BGR_VNG =63, CV_BayerRG2BGR_VNG =64, CV_BayerGR2BGR_VNG =65, - + CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG, CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG, CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG, CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG, - + CV_BGR2HSV_FULL = 66, CV_RGB2HSV_FULL = 67, CV_BGR2HLS_FULL = 68, CV_RGB2HLS_FULL = 69, - + CV_HSV2BGR_FULL = 70, CV_HSV2RGB_FULL = 71, CV_HLS2BGR_FULL = 72, CV_HLS2RGB_FULL = 73, - + CV_LBGR2Lab = 74, CV_LRGB2Lab = 75, CV_LBGR2Luv = 76, CV_LRGB2Luv = 77, - + CV_Lab2LBGR = 78, CV_Lab2LRGB = 79, CV_Luv2LBGR = 80, CV_Luv2LRGB = 81, - + CV_BGR2YUV = 82, CV_RGB2YUV = 83, CV_YUV2BGR = 84, CV_YUV2RGB = 85, - + CV_BayerBG2GRAY = 86, CV_BayerGB2GRAY = 87, CV_BayerRG2GRAY = 88, CV_BayerGR2GRAY = 89, - CV_YUV420i2RGB = 90, - CV_YUV420i2BGR = 91, - CV_YUV420sp2RGB = 92, - CV_YUV420sp2BGR = 93, - - CV_YUV420i2RGBA = 94, - CV_YUV420i2BGRA = 95, - CV_YUV420sp2RGBA = 96, - CV_YUV420sp2BGRA = 97, - - CV_COLORCVT_MAX =100 + //YUV 4:2:0 formats family + CV_YUV2RGB_NV12 = 90, + CV_YUV2BGR_NV12 = 91, + CV_YUV2RGB_NV21 = 92, + CV_YUV2BGR_NV21 = 93, + CV_YUV420sp2RGB = CV_YUV2RGB_NV21, + CV_YUV420sp2BGR = CV_YUV2BGR_NV21, + + CV_YUV2RGBA_NV12 = 94, + CV_YUV2BGRA_NV12 = 95, + CV_YUV2RGBA_NV21 = 96, + CV_YUV2BGRA_NV21 = 97, + CV_YUV420sp2RGBA = CV_YUV2RGBA_NV21, + CV_YUV420sp2BGRA = CV_YUV2BGRA_NV21, + + CV_YUV2RGB_YV12 = 98, + CV_YUV2BGR_YV12 = 99, + CV_YUV2RGB_IYUV = 100, + CV_YUV2BGR_IYUV = 101, + CV_YUV2RGB_I420 = CV_YUV2RGB_IYUV, + CV_YUV2BGR_I420 = CV_YUV2BGR_IYUV, + CV_YUV420p2RGB = CV_YUV2RGB_YV12, + CV_YUV420p2BGR = CV_YUV2BGR_YV12, + + CV_YUV2RGBA_YV12 = 102, + CV_YUV2BGRA_YV12 = 103, + CV_YUV2RGBA_IYUV = 104, + CV_YUV2BGRA_IYUV = 105, + CV_YUV2RGBA_I420 = CV_YUV2RGBA_IYUV, + CV_YUV2BGRA_I420 = CV_YUV2BGRA_IYUV, + CV_YUV420p2RGBA = CV_YUV2RGBA_YV12, + CV_YUV420p2BGRA = CV_YUV2BGRA_YV12, + + CV_YUV2GRAY_420 = 106, + CV_YUV2GRAY_NV21 = CV_YUV2GRAY_420, + CV_YUV2GRAY_NV12 = CV_YUV2GRAY_420, + CV_YUV2GRAY_YV12 = CV_YUV2GRAY_420, + CV_YUV2GRAY_IYUV = CV_YUV2GRAY_420, + CV_YUV2GRAY_I420 = CV_YUV2GRAY_420, + CV_YUV420sp2GRAY = CV_YUV2GRAY_420, + CV_YUV420p2GRAY = CV_YUV2GRAY_420, + + //YUV 4:2:2 formats family + CV_YUV2RGB_UYVY = 107, + CV_YUV2BGR_UYVY = 108, + //CV_YUV2RGB_VYUY = 109, + //CV_YUV2BGR_VYUY = 110, + CV_YUV2RGB_Y422 = CV_YUV2RGB_UYVY, + CV_YUV2BGR_Y422 = CV_YUV2BGR_UYVY, + CV_YUV2RGB_UYNV = CV_YUV2RGB_UYVY, + CV_YUV2BGR_UYNV = CV_YUV2BGR_UYVY, + + CV_YUV2RGBA_UYVY = 111, + CV_YUV2BGRA_UYVY = 112, + //CV_YUV2RGBA_VYUY = 113, + //CV_YUV2BGRA_VYUY = 114, + CV_YUV2RGBA_Y422 = CV_YUV2RGBA_UYVY, + CV_YUV2BGRA_Y422 = CV_YUV2BGRA_UYVY, + CV_YUV2RGBA_UYNV = CV_YUV2RGBA_UYVY, + CV_YUV2BGRA_UYNV = CV_YUV2BGRA_UYVY, + + CV_YUV2RGB_YUY2 = 115, + CV_YUV2BGR_YUY2 = 116, + CV_YUV2RGB_YVYU = 117, + CV_YUV2BGR_YVYU = 118, + CV_YUV2RGB_YUYV = CV_YUV2RGB_YUY2, + CV_YUV2BGR_YUYV = CV_YUV2BGR_YUY2, + CV_YUV2RGB_YUNV = CV_YUV2RGB_YUY2, + CV_YUV2BGR_YUNV = CV_YUV2BGR_YUY2, + + CV_YUV2RGBA_YUY2 = 119, + CV_YUV2BGRA_YUY2 = 120, + CV_YUV2RGBA_YVYU = 121, + CV_YUV2BGRA_YVYU = 122, + CV_YUV2RGBA_YUYV = CV_YUV2RGBA_YUY2, + CV_YUV2BGRA_YUYV = CV_YUV2BGRA_YUY2, + CV_YUV2RGBA_YUNV = CV_YUV2RGBA_YUY2, + CV_YUV2BGRA_YUNV = CV_YUV2BGRA_YUY2, + + CV_YUV2GRAY_UYVY = 123, + CV_YUV2GRAY_YUY2 = 124, + //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, + CV_YUV2GRAY_Y422 = CV_YUV2GRAY_UYVY, + CV_YUV2GRAY_UYNV = CV_YUV2GRAY_UYVY, + CV_YUV2GRAY_YVYU = CV_YUV2GRAY_YUY2, + CV_YUV2GRAY_YUYV = CV_YUV2GRAY_YUY2, + CV_YUV2GRAY_YUNV = CV_YUV2GRAY_YUY2, + + // alpha premultiplication + CV_RGBA2mRGBA = 125, + CV_mRGBA2RGBA = 126, + + CV_COLORCVT_MAX = 127 }; @@ -313,7 +387,8 @@ enum CV_RETR_EXTERNAL=0, CV_RETR_LIST=1, CV_RETR_CCOMP=2, - CV_RETR_TREE=3 + CV_RETR_TREE=3, + CV_RETR_FLOODFILL=4 }; /* Contour approximation methods */ @@ -462,7 +537,8 @@ enum CV_COMP_CORREL =0, CV_COMP_CHISQR =1, CV_COMP_INTERSECT =2, - CV_COMP_BHATTACHARYYA =3 + CV_COMP_BHATTACHARYYA =3, + CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA }; /* Mask size for distance transform */ @@ -473,6 +549,13 @@ enum CV_DIST_MASK_PRECISE =0 }; +/* Content of output label array: connected components or pixels */ +enum +{ + CV_DIST_LABEL_CCOMP = 0, + CV_DIST_LABEL_PIXEL = 1 +}; + /* Distance types for Distance Transform and M-estimators */ enum { diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/blobtrack.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/blobtrack.hpp old mode 100755 new mode 100644 similarity index 98% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/blobtrack.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/blobtrack.hpp index 3afce31..496b8be --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/blobtrack.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/blobtrack.hpp @@ -49,7 +49,7 @@ #include "opencv2/core/core_c.h" #include -#if _MSC_VER >= 1200 || defined __BORLANDC__ +#if (defined _MSC_VER && _MSC_VER >= 1200) || defined __BORLANDC__ #define cv_stricmp stricmp #define cv_strnicmp strnicmp #if defined WINCE @@ -294,7 +294,7 @@ class CV_EXPORTS CvBlobTrackSeq class CV_EXPORTS CvBlobDetector: public CvVSModule { public: - CvBlobDetector(){SetTypeName("BlobDetector");}; + CvBlobDetector(){SetTypeName("BlobDetector");}; /* Try to detect new blob entrance based on foreground mask. */ /* pFGMask - image of foreground mask */ /* pNewBlob - pointer to CvBlob structure which will be filled if new blob entrance detected */ @@ -410,7 +410,7 @@ class CV_EXPORTS CvImageDrawer class CV_EXPORTS CvBlobTrackGen: public CvVSModule { public: - CvBlobTrackGen(){SetTypeName("BlobTrackGen");}; + CvBlobTrackGen(){SetTypeName("BlobTrackGen");}; virtual void SetFileName(char* pFileName) = 0; virtual void AddBlob(CvBlob* pBlob) = 0; virtual void Process(IplImage* pImg = NULL, IplImage* pFG = NULL) = 0; @@ -597,7 +597,7 @@ CV_EXPORTS CvBlobTracker* cvCreateBlobTrackerMSPF(); class CV_EXPORTS CvBlobTrackPostProc: public CvVSModule { public: - CvBlobTrackPostProc(){SetTypeName("BlobTrackPostProc");}; + CvBlobTrackPostProc(){SetTypeName("BlobTrackPostProc");}; virtual void AddBlob(CvBlob* pBlob) = 0; virtual void Process() = 0; virtual int GetBlobNum() = 0; @@ -628,7 +628,7 @@ inline void cvReleaseBlobTrackPostProc(CvBlobTrackPostProc** pBTPP) class CV_EXPORTS CvBlobTrackPostProcOne: public CvVSModule { public: - CvBlobTrackPostProcOne(){SetTypeName("BlobTrackPostOne");}; + CvBlobTrackPostProcOne(){SetTypeName("BlobTrackPostOne");}; virtual CvBlob* Process(CvBlob* pBlob) = 0; virtual void Release() = 0; }; @@ -648,7 +648,7 @@ CV_EXPORTS CvBlobTrackPostProc* cvCreateModuleBlobTrackPostProcTimeAverExp(); class CvBlobTrackPredictor: public CvVSModule { public: - CvBlobTrackPredictor(){SetTypeName("BlobTrackPredictor");}; + CvBlobTrackPredictor(){SetTypeName("BlobTrackPredictor");}; virtual CvBlob* Predict() = 0; virtual void Update(CvBlob* pBlob) = 0; virtual void Release() = 0; @@ -661,7 +661,7 @@ CV_EXPORTS CvBlobTrackPredictor* cvCreateModuleBlobTrackPredictKalman(); class CV_EXPORTS CvBlobTrackAnalysis: public CvVSModule { public: - CvBlobTrackAnalysis(){SetTypeName("BlobTrackAnalysis");}; + CvBlobTrackAnalysis(){SetTypeName("BlobTrackAnalysis");}; virtual void AddBlob(CvBlob* pBlob) = 0; virtual void Process(IplImage* pImg, IplImage* pFG) = 0; virtual float GetState(int BlobID) = 0; @@ -684,7 +684,7 @@ inline void cvReleaseBlobTrackAnalysis(CvBlobTrackAnalysis** pBTPP) class CV_EXPORTS CvBlobTrackFVGen : public CvVSModule { public: - CvBlobTrackFVGen(){SetTypeName("BlobTrackFVGen");}; + CvBlobTrackFVGen(){SetTypeName("BlobTrackFVGen");}; virtual void AddBlob(CvBlob* pBlob) = 0; virtual void Process(IplImage* pImg, IplImage* pFG) = 0; virtual void Release() = 0; @@ -762,7 +762,7 @@ class CV_EXPORTS CvBlobTrackAnalysisHeight: public CvBlobTrackAnalysis class CV_EXPORTS CvBlobTrackerAuto: public CvVSModule { public: - CvBlobTrackerAuto(){SetTypeName("BlobTrackerAuto");}; + CvBlobTrackerAuto(){SetTypeName("BlobTrackerAuto");}; virtual void Process(IplImage* pImg, IplImage* pMask = NULL) = 0; virtual CvBlob* GetBlob(int index) = 0; virtual CvBlob* GetBlobByID(int ID) = 0; diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/compat.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/compat.hpp old mode 100755 new mode 100644 similarity index 85% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/compat.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/compat.hpp index 7644cbb..5b5495e --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/compat.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/compat.hpp @@ -525,7 +525,7 @@ CV_EXPORTS void cvUnDistortInit( const CvArr* src, CV_EXPORTS void cvUnDistort( const CvArr* src, CvArr* dst, const CvArr* undistortion_map, int interpolate ); - + /* Find fundamental matrix */ CV_EXPORTS void cvFindFundamentalMatrix( int* points1, int* points2, int numpoints, int method, float* matrix ); @@ -601,6 +601,138 @@ CV_EXPORTS void cvProjectPointsSimple( int point_count, CvPoint3D64f* _object_p #define cvConvertPointsHomogenious cvConvertPointsHomogeneous +//////////////////////////////////// feature extractors: obsolete API ////////////////////////////////// + +typedef struct CvSURFPoint +{ + CvPoint2D32f pt; + + int laplacian; + int size; + float dir; + float hessian; + +} CvSURFPoint; + +CV_INLINE CvSURFPoint cvSURFPoint( CvPoint2D32f pt, int laplacian, + int size, float dir CV_DEFAULT(0), + float hessian CV_DEFAULT(0)) +{ + CvSURFPoint kp; + + kp.pt = pt; + kp.laplacian = laplacian; + kp.size = size; + kp.dir = dir; + kp.hessian = hessian; + + return kp; +} + +typedef struct CvSURFParams +{ + int extended; + int upright; + double hessianThreshold; + + int nOctaves; + int nOctaveLayers; + +} CvSURFParams; + +CVAPI(CvSURFParams) cvSURFParams( double hessianThreshold, int extended CV_DEFAULT(0) ); + +// If useProvidedKeyPts!=0, keypoints are not detected, but descriptors are computed +// at the locations provided in keypoints (a CvSeq of CvSURFPoint). +CVAPI(void) cvExtractSURF( const CvArr* img, const CvArr* mask, + CvSeq** keypoints, CvSeq** descriptors, + CvMemStorage* storage, CvSURFParams params, + int useProvidedKeyPts CV_DEFAULT(0) ); + +/*! + Maximal Stable Regions Parameters + */ +typedef struct CvMSERParams +{ + //! delta, in the code, it compares (size_{i}-size_{i-delta})/size_{i-delta} + int delta; + //! prune the area which bigger than maxArea + int maxArea; + //! prune the area which smaller than minArea + int minArea; + //! prune the area have simliar size to its children + float maxVariation; + //! trace back to cut off mser with diversity < min_diversity + float minDiversity; + + /////// the next few params for MSER of color image + + //! for color image, the evolution steps + int maxEvolution; + //! the area threshold to cause re-initialize + double areaThreshold; + //! ignore too small margin + double minMargin; + //! the aperture size for edge blur + int edgeBlurSize; +} CvMSERParams; + +CVAPI(CvMSERParams) cvMSERParams( int delta CV_DEFAULT(5), int min_area CV_DEFAULT(60), + int max_area CV_DEFAULT(14400), float max_variation CV_DEFAULT(.25f), + float min_diversity CV_DEFAULT(.2f), int max_evolution CV_DEFAULT(200), + double area_threshold CV_DEFAULT(1.01), + double min_margin CV_DEFAULT(.003), + int edge_blur_size CV_DEFAULT(5) ); + +// Extracts the contours of Maximally Stable Extremal Regions +CVAPI(void) cvExtractMSER( CvArr* _img, CvArr* _mask, CvSeq** contours, CvMemStorage* storage, CvMSERParams params ); + + +typedef struct CvStarKeypoint +{ + CvPoint pt; + int size; + float response; +} CvStarKeypoint; + +CV_INLINE CvStarKeypoint cvStarKeypoint(CvPoint pt, int size, float response) +{ + CvStarKeypoint kpt; + kpt.pt = pt; + kpt.size = size; + kpt.response = response; + return kpt; +} + +typedef struct CvStarDetectorParams +{ + int maxSize; + int responseThreshold; + int lineThresholdProjected; + int lineThresholdBinarized; + int suppressNonmaxSize; +} CvStarDetectorParams; + +CV_INLINE CvStarDetectorParams cvStarDetectorParams( + int maxSize CV_DEFAULT(45), + int responseThreshold CV_DEFAULT(30), + int lineThresholdProjected CV_DEFAULT(10), + int lineThresholdBinarized CV_DEFAULT(8), + int suppressNonmaxSize CV_DEFAULT(5)) +{ + CvStarDetectorParams params; + params.maxSize = maxSize; + params.responseThreshold = responseThreshold; + params.lineThresholdProjected = lineThresholdProjected; + params.lineThresholdBinarized = lineThresholdBinarized; + params.suppressNonmaxSize = suppressNonmaxSize; + + return params; +} + +CVAPI(CvSeq*) cvGetStarKeypoints( const CvArr* img, CvMemStorage* storage, + CvStarDetectorParams params CV_DEFAULT(cvStarDetectorParams())); + #ifdef __cplusplus } #endif diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/legacy.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/legacy.hpp new file mode 100644 index 0000000..96da25c --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/legacy.hpp @@ -0,0 +1,3436 @@ +/*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 __OPENCV_LEGACY_HPP__ +#define __OPENCV_LEGACY_HPP__ + +#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc/imgproc_c.h" +#include "opencv2/features2d/features2d.hpp" +#include "opencv2/calib3d/calib3d.hpp" +#include "opencv2/ml/ml.hpp" + +#ifdef __cplusplus +extern "C" { +#endif + +CVAPI(CvSeq*) cvSegmentImage( const CvArr* srcarr, CvArr* dstarr, + double canny_threshold, + double ffill_threshold, + CvMemStorage* storage ); + +/****************************************************************************************\ +* Eigen objects * +\****************************************************************************************/ + +typedef int (CV_CDECL * CvCallback)(int index, void* buffer, void* user_data); +typedef union +{ + CvCallback callback; + void* data; +} +CvInput; + +#define CV_EIGOBJ_NO_CALLBACK 0 +#define CV_EIGOBJ_INPUT_CALLBACK 1 +#define CV_EIGOBJ_OUTPUT_CALLBACK 2 +#define CV_EIGOBJ_BOTH_CALLBACK 3 + +/* Calculates covariation matrix of a set of arrays */ +CVAPI(void) cvCalcCovarMatrixEx( int nObjects, void* input, int ioFlags, + int ioBufSize, uchar* buffer, void* userData, + IplImage* avg, float* covarMatrix ); + +/* Calculates eigen values and vectors of covariation matrix of a set of + arrays */ +CVAPI(void) cvCalcEigenObjects( int nObjects, void* input, void* output, + int ioFlags, int ioBufSize, void* userData, + CvTermCriteria* calcLimit, IplImage* avg, + float* eigVals ); + +/* Calculates dot product (obj - avg) * eigObj (i.e. projects image to eigen vector) */ +CVAPI(double) cvCalcDecompCoeff( IplImage* obj, IplImage* eigObj, IplImage* avg ); + +/* Projects image to eigen space (finds all decomposion coefficients */ +CVAPI(void) cvEigenDecomposite( IplImage* obj, int nEigObjs, void* eigInput, + int ioFlags, void* userData, IplImage* avg, + float* coeffs ); + +/* Projects original objects used to calculate eigen space basis to that space */ +CVAPI(void) cvEigenProjection( void* eigInput, int nEigObjs, int ioFlags, + void* userData, float* coeffs, IplImage* avg, + IplImage* proj ); + +/****************************************************************************************\ +* 1D/2D HMM * +\****************************************************************************************/ + +typedef struct CvImgObsInfo +{ + int obs_x; + int obs_y; + int obs_size; + float* obs;//consequtive observations + + int* state;/* arr of pairs superstate/state to which observation belong */ + int* mix; /* number of mixture to which observation belong */ + +} CvImgObsInfo;/*struct for 1 image*/ + +typedef CvImgObsInfo Cv1DObsInfo; + +typedef struct CvEHMMState +{ + int num_mix; /*number of mixtures in this state*/ + float* mu; /*mean vectors corresponding to each mixture*/ + float* inv_var; /* square root of inversed variances corresp. to each mixture*/ + float* log_var_val; /* sum of 0.5 (LN2PI + ln(variance[i]) ) for i=1,n */ + float* weight; /*array of mixture weights. Summ of all weights in state is 1. */ + +} CvEHMMState; + +typedef struct CvEHMM +{ + int level; /* 0 - lowest(i.e its states are real states), ..... */ + int num_states; /* number of HMM states */ + float* transP;/*transition probab. matrices for states */ + float** obsProb; /* if level == 0 - array of brob matrices corresponding to hmm + if level == 1 - martix of matrices */ + union + { + CvEHMMState* state; /* if level == 0 points to real states array, + if not - points to embedded hmms */ + struct CvEHMM* ehmm; /* pointer to an embedded model or NULL, if it is a leaf */ + } u; + +} CvEHMM; + +/*CVAPI(int) icvCreate1DHMM( CvEHMM** this_hmm, + int state_number, int* num_mix, int obs_size ); + +CVAPI(int) icvRelease1DHMM( CvEHMM** phmm ); + +CVAPI(int) icvUniform1DSegm( Cv1DObsInfo* obs_info, CvEHMM* hmm ); + +CVAPI(int) icvInit1DMixSegm( Cv1DObsInfo** obs_info_array, int num_img, CvEHMM* hmm); + +CVAPI(int) icvEstimate1DHMMStateParams( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm); + +CVAPI(int) icvEstimate1DObsProb( CvImgObsInfo* obs_info, CvEHMM* hmm ); + +CVAPI(int) icvEstimate1DTransProb( Cv1DObsInfo** obs_info_array, + int num_seq, + CvEHMM* hmm ); + +CVAPI(float) icvViterbi( Cv1DObsInfo* obs_info, CvEHMM* hmm); + +CVAPI(int) icv1DMixSegmL2( CvImgObsInfo** obs_info_array, int num_img, CvEHMM* hmm );*/ + +/*********************************** Embedded HMMs *************************************/ + +/* Creates 2D HMM */ +CVAPI(CvEHMM*) cvCreate2DHMM( int* stateNumber, int* numMix, int obsSize ); + +/* Releases HMM */ +CVAPI(void) cvRelease2DHMM( CvEHMM** hmm ); + +#define CV_COUNT_OBS(roi, win, delta, numObs ) \ +{ \ + (numObs)->width =((roi)->width -(win)->width +(delta)->width)/(delta)->width; \ + (numObs)->height =((roi)->height -(win)->height +(delta)->height)/(delta)->height;\ +} + +/* Creates storage for observation vectors */ +CVAPI(CvImgObsInfo*) cvCreateObsInfo( CvSize numObs, int obsSize ); + +/* Releases storage for observation vectors */ +CVAPI(void) cvReleaseObsInfo( CvImgObsInfo** obs_info ); + + +/* The function takes an image on input and and returns the sequnce of observations + to be used with an embedded HMM; Each observation is top-left block of DCT + coefficient matrix */ +CVAPI(void) cvImgToObs_DCT( const CvArr* arr, float* obs, CvSize dctSize, + CvSize obsSize, CvSize delta ); + + +/* Uniformly segments all observation vectors extracted from image */ +CVAPI(void) cvUniformImgSegm( CvImgObsInfo* obs_info, CvEHMM* ehmm ); + +/* Does mixture segmentation of the states of embedded HMM */ +CVAPI(void) cvInitMixSegm( CvImgObsInfo** obs_info_array, + int num_img, CvEHMM* hmm ); + +/* Function calculates means, variances, weights of every Gaussian mixture + of every low-level state of embedded HMM */ +CVAPI(void) cvEstimateHMMStateParams( CvImgObsInfo** obs_info_array, + int num_img, CvEHMM* hmm ); + +/* Function computes transition probability matrices of embedded HMM + given observations segmentation */ +CVAPI(void) cvEstimateTransProb( CvImgObsInfo** obs_info_array, + int num_img, CvEHMM* hmm ); + +/* Function computes probabilities of appearing observations at any state + (i.e. computes P(obs|state) for every pair(obs,state)) */ +CVAPI(void) cvEstimateObsProb( CvImgObsInfo* obs_info, + CvEHMM* hmm ); + +/* Runs Viterbi algorithm for embedded HMM */ +CVAPI(float) cvEViterbi( CvImgObsInfo* obs_info, CvEHMM* hmm ); + + +/* Function clusters observation vectors from several images + given observations segmentation. + Euclidean distance used for clustering vectors. + Centers of clusters are given means of every mixture */ +CVAPI(void) cvMixSegmL2( CvImgObsInfo** obs_info_array, + int num_img, CvEHMM* hmm ); + +/****************************************************************************************\ +* A few functions from old stereo gesture recognition demosions * +\****************************************************************************************/ + +/* Creates hand mask image given several points on the hand */ +CVAPI(void) cvCreateHandMask( CvSeq* hand_points, + IplImage *img_mask, CvRect *roi); + +/* Finds hand region in range image data */ +CVAPI(void) cvFindHandRegion (CvPoint3D32f* points, int count, + CvSeq* indexs, + float* line, CvSize2D32f size, int flag, + CvPoint3D32f* center, + CvMemStorage* storage, CvSeq **numbers); + +/* Finds hand region in range image data (advanced version) */ +CVAPI(void) cvFindHandRegionA( CvPoint3D32f* points, int count, + CvSeq* indexs, + float* line, CvSize2D32f size, int jc, + CvPoint3D32f* center, + CvMemStorage* storage, CvSeq **numbers); + +/* Calculates the cooficients of the homography matrix */ +CVAPI(void) cvCalcImageHomography( float* line, CvPoint3D32f* center, + float* intrinsic, float* homography ); + +/****************************************************************************************\ +* More operations on sequences * +\****************************************************************************************/ + +/*****************************************************************************************/ + +#define CV_CURRENT_INT( reader ) (*((int *)(reader).ptr)) +#define CV_PREV_INT( reader ) (*((int *)(reader).prev_elem)) + +#define CV_GRAPH_WEIGHTED_VERTEX_FIELDS() CV_GRAPH_VERTEX_FIELDS()\ + float weight; + +#define CV_GRAPH_WEIGHTED_EDGE_FIELDS() CV_GRAPH_EDGE_FIELDS() + +typedef struct CvGraphWeightedVtx +{ + CV_GRAPH_WEIGHTED_VERTEX_FIELDS() +} CvGraphWeightedVtx; + +typedef struct CvGraphWeightedEdge +{ + CV_GRAPH_WEIGHTED_EDGE_FIELDS() +} CvGraphWeightedEdge; + +typedef enum CvGraphWeightType +{ + CV_NOT_WEIGHTED, + CV_WEIGHTED_VTX, + CV_WEIGHTED_EDGE, + CV_WEIGHTED_ALL +} CvGraphWeightType; + + +/* Calculates histogram of a contour */ +CVAPI(void) cvCalcPGH( const CvSeq* contour, CvHistogram* hist ); + +#define CV_DOMINANT_IPAN 1 + +/* Finds high-curvature points of the contour */ +CVAPI(CvSeq*) cvFindDominantPoints( CvSeq* contour, CvMemStorage* storage, + int method CV_DEFAULT(CV_DOMINANT_IPAN), + double parameter1 CV_DEFAULT(0), + double parameter2 CV_DEFAULT(0), + double parameter3 CV_DEFAULT(0), + double parameter4 CV_DEFAULT(0)); + +/*****************************************************************************************/ + + +/*******************************Stereo correspondence*************************************/ + +typedef struct CvCliqueFinder +{ + CvGraph* graph; + int** adj_matr; + int N; //graph size + + // stacks, counters etc/ + int k; //stack size + int* current_comp; + int** All; + + int* ne; + int* ce; + int* fixp; //node with minimal disconnections + int* nod; + int* s; //for selected candidate + int status; + int best_score; + int weighted; + int weighted_edges; + float best_weight; + float* edge_weights; + float* vertex_weights; + float* cur_weight; + float* cand_weight; + +} CvCliqueFinder; + +#define CLIQUE_TIME_OFF 2 +#define CLIQUE_FOUND 1 +#define CLIQUE_END 0 + +/*CVAPI(void) cvStartFindCliques( CvGraph* graph, CvCliqueFinder* finder, int reverse, + int weighted CV_DEFAULT(0), int weighted_edges CV_DEFAULT(0)); +CVAPI(int) cvFindNextMaximalClique( CvCliqueFinder* finder, int* clock_rest CV_DEFAULT(0) ); +CVAPI(void) cvEndFindCliques( CvCliqueFinder* finder ); + +CVAPI(void) cvBronKerbosch( CvGraph* graph );*/ + + +/*F/////////////////////////////////////////////////////////////////////////////////////// +// +// Name: cvSubgraphWeight +// Purpose: finds weight of subgraph in a graph +// Context: +// Parameters: +// graph - input graph. +// subgraph - sequence of pairwise different ints. These are indices of vertices of subgraph. +// weight_type - describes the way we measure weight. +// one of the following: +// CV_NOT_WEIGHTED - weight of a clique is simply its size +// CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices +// CV_WEIGHTED_EDGE - the same but edges +// CV_WEIGHTED_ALL - the same but both edges and vertices +// weight_vtx - optional vector of floats, with size = graph->total. +// If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL +// weights of vertices must be provided. If weight_vtx not zero +// these weights considered to be here, otherwise function assumes +// that vertices of graph are inherited from CvGraphWeightedVtx. +// weight_edge - optional matrix of floats, of width and height = graph->total. +// If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL +// weights of edges ought to be supplied. If weight_edge is not zero +// function finds them here, otherwise function expects +// edges of graph to be inherited from CvGraphWeightedEdge. +// If this parameter is not zero structure of the graph is determined from matrix +// rather than from CvGraphEdge's. In particular, elements corresponding to +// absent edges should be zero. +// Returns: +// weight of subgraph. +// Notes: +//F*/ +/*CVAPI(float) cvSubgraphWeight( CvGraph *graph, CvSeq *subgraph, + CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED), + CvVect32f weight_vtx CV_DEFAULT(0), + CvMatr32f weight_edge CV_DEFAULT(0) );*/ + + +/*F/////////////////////////////////////////////////////////////////////////////////////// +// +// Name: cvFindCliqueEx +// Purpose: tries to find clique with maximum possible weight in a graph +// Context: +// Parameters: +// graph - input graph. +// storage - memory storage to be used by the result. +// is_complementary - optional flag showing whether function should seek for clique +// in complementary graph. +// weight_type - describes our notion about weight. +// one of the following: +// CV_NOT_WEIGHTED - weight of a clique is simply its size +// CV_WEIGHTED_VTX - weight of a clique is the sum of weights of its vertices +// CV_WEIGHTED_EDGE - the same but edges +// CV_WEIGHTED_ALL - the same but both edges and vertices +// weight_vtx - optional vector of floats, with size = graph->total. +// If weight_type is either CV_WEIGHTED_VTX or CV_WEIGHTED_ALL +// weights of vertices must be provided. If weight_vtx not zero +// these weights considered to be here, otherwise function assumes +// that vertices of graph are inherited from CvGraphWeightedVtx. +// weight_edge - optional matrix of floats, of width and height = graph->total. +// If weight_type is either CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL +// weights of edges ought to be supplied. If weight_edge is not zero +// function finds them here, otherwise function expects +// edges of graph to be inherited from CvGraphWeightedEdge. +// Note that in case of CV_WEIGHTED_EDGE or CV_WEIGHTED_ALL +// nonzero is_complementary implies nonzero weight_edge. +// start_clique - optional sequence of pairwise different ints. They are indices of +// vertices that shall be present in the output clique. +// subgraph_of_ban - optional sequence of (maybe equal) ints. They are indices of +// vertices that shall not be present in the output clique. +// clique_weight_ptr - optional output parameter. Weight of found clique stored here. +// num_generations - optional number of generations in evolutionary part of algorithm, +// zero forces to return first found clique. +// quality - optional parameter determining degree of required quality/speed tradeoff. +// Must be in the range from 0 to 9. +// 0 is fast and dirty, 9 is slow but hopefully yields good clique. +// Returns: +// sequence of pairwise different ints. +// These are indices of vertices that form found clique. +// Notes: +// in cases of CV_WEIGHTED_EDGE and CV_WEIGHTED_ALL weights should be nonnegative. +// start_clique has a priority over subgraph_of_ban. +//F*/ +/*CVAPI(CvSeq*) cvFindCliqueEx( CvGraph *graph, CvMemStorage *storage, + int is_complementary CV_DEFAULT(0), + CvGraphWeightType weight_type CV_DEFAULT(CV_NOT_WEIGHTED), + CvVect32f weight_vtx CV_DEFAULT(0), + CvMatr32f weight_edge CV_DEFAULT(0), + CvSeq *start_clique CV_DEFAULT(0), + CvSeq *subgraph_of_ban CV_DEFAULT(0), + float *clique_weight_ptr CV_DEFAULT(0), + int num_generations CV_DEFAULT(3), + int quality CV_DEFAULT(2) );*/ + + +#define CV_UNDEF_SC_PARAM 12345 //default value of parameters + +#define CV_IDP_BIRCHFIELD_PARAM1 25 +#define CV_IDP_BIRCHFIELD_PARAM2 5 +#define CV_IDP_BIRCHFIELD_PARAM3 12 +#define CV_IDP_BIRCHFIELD_PARAM4 15 +#define CV_IDP_BIRCHFIELD_PARAM5 25 + + +#define CV_DISPARITY_BIRCHFIELD 0 + + +/*F/////////////////////////////////////////////////////////////////////////// +// +// Name: cvFindStereoCorrespondence +// Purpose: find stereo correspondence on stereo-pair +// Context: +// Parameters: +// leftImage - left image of stereo-pair (format 8uC1). +// rightImage - right image of stereo-pair (format 8uC1). +// mode - mode of correspondence retrieval (now CV_DISPARITY_BIRCHFIELD only) +// dispImage - destination disparity image +// maxDisparity - maximal disparity +// param1, param2, param3, param4, param5 - parameters of algorithm +// Returns: +// Notes: +// Images must be rectified. +// All images must have format 8uC1. +//F*/ +CVAPI(void) +cvFindStereoCorrespondence( + const CvArr* leftImage, const CvArr* rightImage, + int mode, + CvArr* dispImage, + int maxDisparity, + double param1 CV_DEFAULT(CV_UNDEF_SC_PARAM), + double param2 CV_DEFAULT(CV_UNDEF_SC_PARAM), + double param3 CV_DEFAULT(CV_UNDEF_SC_PARAM), + double param4 CV_DEFAULT(CV_UNDEF_SC_PARAM), + double param5 CV_DEFAULT(CV_UNDEF_SC_PARAM) ); + +/*****************************************************************************************/ +/************ Epiline functions *******************/ + + + +typedef struct CvStereoLineCoeff +{ + double Xcoef; + double XcoefA; + double XcoefB; + double XcoefAB; + + double Ycoef; + double YcoefA; + double YcoefB; + double YcoefAB; + + double Zcoef; + double ZcoefA; + double ZcoefB; + double ZcoefAB; +}CvStereoLineCoeff; + + +typedef struct CvCamera +{ + float imgSize[2]; /* size of the camera view, used during calibration */ + float matrix[9]; /* intinsic camera parameters: [ fx 0 cx; 0 fy cy; 0 0 1 ] */ + float distortion[4]; /* distortion coefficients - two coefficients for radial distortion + and another two for tangential: [ k1 k2 p1 p2 ] */ + float rotMatr[9]; + float transVect[3]; /* rotation matrix and transition vector relatively + to some reference point in the space. */ +} CvCamera; + +typedef struct CvStereoCamera +{ + CvCamera* camera[2]; /* two individual camera parameters */ + float fundMatr[9]; /* fundamental matrix */ + + /* New part for stereo */ + CvPoint3D32f epipole[2]; + CvPoint2D32f quad[2][4]; /* coordinates of destination quadrangle after + epipolar geometry rectification */ + double coeffs[2][3][3];/* coefficients for transformation */ + CvPoint2D32f border[2][4]; + CvSize warpSize; + CvStereoLineCoeff* lineCoeffs; + int needSwapCameras;/* flag set to 1 if need to swap cameras for good reconstruction */ + float rotMatrix[9]; + float transVector[3]; +} CvStereoCamera; + + +typedef struct CvContourOrientation +{ + float egvals[2]; + float egvects[4]; + + float max, min; // minimum and maximum projections + int imax, imin; +} CvContourOrientation; + +#define CV_CAMERA_TO_WARP 1 +#define CV_WARP_TO_CAMERA 2 + +CVAPI(int) icvConvertWarpCoordinates(double coeffs[3][3], + CvPoint2D32f* cameraPoint, + CvPoint2D32f* warpPoint, + int direction); + +CVAPI(int) icvGetSymPoint3D( CvPoint3D64f pointCorner, + CvPoint3D64f point1, + CvPoint3D64f point2, + CvPoint3D64f *pointSym2); + +CVAPI(void) icvGetPieceLength3D(CvPoint3D64f point1,CvPoint3D64f point2,double* dist); + +CVAPI(int) icvCompute3DPoint( double alpha,double betta, + CvStereoLineCoeff* coeffs, + CvPoint3D64f* point); + +CVAPI(int) icvCreateConvertMatrVect( double* rotMatr1, + double* transVect1, + double* rotMatr2, + double* transVect2, + double* convRotMatr, + double* convTransVect); + +CVAPI(int) icvConvertPointSystem(CvPoint3D64f M2, + CvPoint3D64f* M1, + double* rotMatr, + double* transVect + ); + +CVAPI(int) icvComputeCoeffForStereo( CvStereoCamera* stereoCamera); + +CVAPI(int) icvGetCrossPieceVector(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f v2_start,CvPoint2D32f v2_end,CvPoint2D32f *cross); +CVAPI(int) icvGetCrossLineDirect(CvPoint2D32f p1,CvPoint2D32f p2,float a,float b,float c,CvPoint2D32f* cross); +CVAPI(float) icvDefinePointPosition(CvPoint2D32f point1,CvPoint2D32f point2,CvPoint2D32f point); +CVAPI(int) icvStereoCalibration( int numImages, + int* nums, + CvSize imageSize, + CvPoint2D32f* imagePoints1, + CvPoint2D32f* imagePoints2, + CvPoint3D32f* objectPoints, + CvStereoCamera* stereoparams + ); + + +CVAPI(int) icvComputeRestStereoParams(CvStereoCamera *stereoparams); + +CVAPI(void) cvComputePerspectiveMap( const double coeffs[3][3], CvArr* rectMapX, CvArr* rectMapY ); + +CVAPI(int) icvComCoeffForLine( CvPoint2D64f point1, + CvPoint2D64f point2, + CvPoint2D64f point3, + CvPoint2D64f point4, + double* camMatr1, + double* rotMatr1, + double* transVect1, + double* camMatr2, + double* rotMatr2, + double* transVect2, + CvStereoLineCoeff* coeffs, + int* needSwapCameras); + +CVAPI(int) icvGetDirectionForPoint( CvPoint2D64f point, + double* camMatr, + CvPoint3D64f* direct); + +CVAPI(int) icvGetCrossLines(CvPoint3D64f point11,CvPoint3D64f point12, + CvPoint3D64f point21,CvPoint3D64f point22, + CvPoint3D64f* midPoint); + +CVAPI(int) icvComputeStereoLineCoeffs( CvPoint3D64f pointA, + CvPoint3D64f pointB, + CvPoint3D64f pointCam1, + double gamma, + CvStereoLineCoeff* coeffs); + +/*CVAPI(int) icvComputeFundMatrEpipoles ( double* camMatr1, + double* rotMatr1, + double* transVect1, + double* camMatr2, + double* rotMatr2, + double* transVect2, + CvPoint2D64f* epipole1, + CvPoint2D64f* epipole2, + double* fundMatr);*/ + +CVAPI(int) icvGetAngleLine( CvPoint2D64f startPoint, CvSize imageSize,CvPoint2D64f *point1,CvPoint2D64f *point2); + +CVAPI(void) icvGetCoefForPiece( CvPoint2D64f p_start,CvPoint2D64f p_end, + double *a,double *b,double *c, + int* result); + +/*CVAPI(void) icvGetCommonArea( CvSize imageSize, + CvPoint2D64f epipole1,CvPoint2D64f epipole2, + double* fundMatr, + double* coeff11,double* coeff12, + double* coeff21,double* coeff22, + int* result);*/ + +CVAPI(void) icvComputeeInfiniteProject1(double* rotMatr, + double* camMatr1, + double* camMatr2, + CvPoint2D32f point1, + CvPoint2D32f *point2); + +CVAPI(void) icvComputeeInfiniteProject2(double* rotMatr, + double* camMatr1, + double* camMatr2, + CvPoint2D32f* point1, + CvPoint2D32f point2); + +CVAPI(void) icvGetCrossDirectDirect( double* direct1,double* direct2, + CvPoint2D64f *cross,int* result); + +CVAPI(void) icvGetCrossPieceDirect( CvPoint2D64f p_start,CvPoint2D64f p_end, + double a,double b,double c, + CvPoint2D64f *cross,int* result); + +CVAPI(void) icvGetCrossPiecePiece( CvPoint2D64f p1_start,CvPoint2D64f p1_end, + CvPoint2D64f p2_start,CvPoint2D64f p2_end, + CvPoint2D64f* cross, + int* result); + +CVAPI(void) icvGetPieceLength(CvPoint2D64f point1,CvPoint2D64f point2,double* dist); + +CVAPI(void) icvGetCrossRectDirect( CvSize imageSize, + double a,double b,double c, + CvPoint2D64f *start,CvPoint2D64f *end, + int* result); + +CVAPI(void) icvProjectPointToImage( CvPoint3D64f point, + double* camMatr,double* rotMatr,double* transVect, + CvPoint2D64f* projPoint); + +CVAPI(void) icvGetQuadsTransform( CvSize imageSize, + double* camMatr1, + double* rotMatr1, + double* transVect1, + double* camMatr2, + double* rotMatr2, + double* transVect2, + CvSize* warpSize, + double quad1[4][2], + double quad2[4][2], + double* fundMatr, + CvPoint3D64f* epipole1, + CvPoint3D64f* epipole2 + ); + +CVAPI(void) icvGetQuadsTransformStruct( CvStereoCamera* stereoCamera); + +CVAPI(void) icvComputeStereoParamsForCameras(CvStereoCamera* stereoCamera); + +CVAPI(void) icvGetCutPiece( double* areaLineCoef1,double* areaLineCoef2, + CvPoint2D64f epipole, + CvSize imageSize, + CvPoint2D64f* point11,CvPoint2D64f* point12, + CvPoint2D64f* point21,CvPoint2D64f* point22, + int* result); + +CVAPI(void) icvGetMiddleAnglePoint( CvPoint2D64f basePoint, + CvPoint2D64f point1,CvPoint2D64f point2, + CvPoint2D64f* midPoint); + +CVAPI(void) icvGetNormalDirect(double* direct,CvPoint2D64f point,double* normDirect); + +CVAPI(double) icvGetVect(CvPoint2D64f basePoint,CvPoint2D64f point1,CvPoint2D64f point2); + +CVAPI(void) icvProjectPointToDirect( CvPoint2D64f point,double* lineCoeff, + CvPoint2D64f* projectPoint); + +CVAPI(void) icvGetDistanceFromPointToDirect( CvPoint2D64f point,double* lineCoef,double*dist); + +CVAPI(IplImage*) icvCreateIsometricImage( IplImage* src, IplImage* dst, + int desired_depth, int desired_num_channels ); + +CVAPI(void) cvDeInterlace( const CvArr* frame, CvArr* fieldEven, CvArr* fieldOdd ); + +/*CVAPI(int) icvSelectBestRt( int numImages, + int* numPoints, + CvSize imageSize, + CvPoint2D32f* imagePoints1, + CvPoint2D32f* imagePoints2, + CvPoint3D32f* objectPoints, + + CvMatr32f cameraMatrix1, + CvVect32f distortion1, + CvMatr32f rotMatrs1, + CvVect32f transVects1, + + CvMatr32f cameraMatrix2, + CvVect32f distortion2, + CvMatr32f rotMatrs2, + CvVect32f transVects2, + + CvMatr32f bestRotMatr, + CvVect32f bestTransVect + );*/ + + +/****************************************************************************************\ +* Contour Tree * +\****************************************************************************************/ + +/* Contour tree header */ +typedef struct CvContourTree +{ + CV_SEQUENCE_FIELDS() + CvPoint p1; /* the first point of the binary tree root segment */ + CvPoint p2; /* the last point of the binary tree root segment */ +} CvContourTree; + +/* Builds hierarhical representation of a contour */ +CVAPI(CvContourTree*) cvCreateContourTree( const CvSeq* contour, + CvMemStorage* storage, + double threshold ); + +/* Reconstruct (completelly or partially) contour a from contour tree */ +CVAPI(CvSeq*) cvContourFromContourTree( const CvContourTree* tree, + CvMemStorage* storage, + CvTermCriteria criteria ); + +/* Compares two contour trees */ +enum { CV_CONTOUR_TREES_MATCH_I1 = 1 }; + +CVAPI(double) cvMatchContourTrees( const CvContourTree* tree1, + const CvContourTree* tree2, + int method, double threshold ); + +/****************************************************************************************\ +* Contour Morphing * +\****************************************************************************************/ + +/* finds correspondence between two contours */ +CvSeq* cvCalcContoursCorrespondence( const CvSeq* contour1, + const CvSeq* contour2, + CvMemStorage* storage); + +/* morphs contours using the pre-calculated correspondence: + alpha=0 ~ contour1, alpha=1 ~ contour2 */ +CvSeq* cvMorphContours( const CvSeq* contour1, const CvSeq* contour2, + CvSeq* corr, double alpha, + CvMemStorage* storage ); + + +/****************************************************************************************\ +* Active Contours * +\****************************************************************************************/ + +#define CV_VALUE 1 +#define CV_ARRAY 2 +/* Updates active contour in order to minimize its cummulative + (internal and external) energy. */ +CVAPI(void) cvSnakeImage( const IplImage* image, CvPoint* points, + int length, float* alpha, + float* beta, float* gamma, + int coeff_usage, CvSize win, + CvTermCriteria criteria, int calc_gradient CV_DEFAULT(1)); + +/****************************************************************************************\ +* Texture Descriptors * +\****************************************************************************************/ + +#define CV_GLCM_OPTIMIZATION_NONE -2 +#define CV_GLCM_OPTIMIZATION_LUT -1 +#define CV_GLCM_OPTIMIZATION_HISTOGRAM 0 + +#define CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST 10 +#define CV_GLCMDESC_OPTIMIZATION_ALLOWTRIPLENEST 11 +#define CV_GLCMDESC_OPTIMIZATION_HISTOGRAM 4 + +#define CV_GLCMDESC_ENTROPY 0 +#define CV_GLCMDESC_ENERGY 1 +#define CV_GLCMDESC_HOMOGENITY 2 +#define CV_GLCMDESC_CONTRAST 3 +#define CV_GLCMDESC_CLUSTERTENDENCY 4 +#define CV_GLCMDESC_CLUSTERSHADE 5 +#define CV_GLCMDESC_CORRELATION 6 +#define CV_GLCMDESC_CORRELATIONINFO1 7 +#define CV_GLCMDESC_CORRELATIONINFO2 8 +#define CV_GLCMDESC_MAXIMUMPROBABILITY 9 + +#define CV_GLCM_ALL 0 +#define CV_GLCM_GLCM 1 +#define CV_GLCM_DESC 2 + +typedef struct CvGLCM CvGLCM; + +CVAPI(CvGLCM*) cvCreateGLCM( const IplImage* srcImage, + int stepMagnitude, + const int* stepDirections CV_DEFAULT(0), + int numStepDirections CV_DEFAULT(0), + int optimizationType CV_DEFAULT(CV_GLCM_OPTIMIZATION_NONE)); + +CVAPI(void) cvReleaseGLCM( CvGLCM** GLCM, int flag CV_DEFAULT(CV_GLCM_ALL)); + +CVAPI(void) cvCreateGLCMDescriptors( CvGLCM* destGLCM, + int descriptorOptimizationType + CV_DEFAULT(CV_GLCMDESC_OPTIMIZATION_ALLOWDOUBLENEST)); + +CVAPI(double) cvGetGLCMDescriptor( CvGLCM* GLCM, int step, int descriptor ); + +CVAPI(void) cvGetGLCMDescriptorStatistics( CvGLCM* GLCM, int descriptor, + double* average, double* standardDeviation ); + +CVAPI(IplImage*) cvCreateGLCMImage( CvGLCM* GLCM, int step ); + +/****************************************************************************************\ +* Face eyes&mouth tracking * +\****************************************************************************************/ + + +typedef struct CvFaceTracker CvFaceTracker; + +#define CV_NUM_FACE_ELEMENTS 3 +enum CV_FACE_ELEMENTS +{ + CV_FACE_MOUTH = 0, + CV_FACE_LEFT_EYE = 1, + CV_FACE_RIGHT_EYE = 2 +}; + +CVAPI(CvFaceTracker*) cvInitFaceTracker(CvFaceTracker* pFaceTracking, const IplImage* imgGray, + CvRect* pRects, int nRects); +CVAPI(int) cvTrackFace( CvFaceTracker* pFaceTracker, IplImage* imgGray, + CvRect* pRects, int nRects, + CvPoint* ptRotate, double* dbAngleRotate); +CVAPI(void) cvReleaseFaceTracker(CvFaceTracker** ppFaceTracker); + + +typedef struct CvFace +{ + CvRect MouthRect; + CvRect LeftEyeRect; + CvRect RightEyeRect; +} CvFaceData; + +CvSeq * cvFindFace(IplImage * Image,CvMemStorage* storage); +CvSeq * cvPostBoostingFindFace(IplImage * Image,CvMemStorage* storage); + + +/****************************************************************************************\ +* 3D Tracker * +\****************************************************************************************/ + +typedef unsigned char CvBool; + +typedef struct Cv3dTracker2dTrackedObject +{ + int id; + CvPoint2D32f p; // pgruebele: So we do not loose precision, this needs to be float +} Cv3dTracker2dTrackedObject; + +CV_INLINE Cv3dTracker2dTrackedObject cv3dTracker2dTrackedObject(int id, CvPoint2D32f p) +{ + Cv3dTracker2dTrackedObject r; + r.id = id; + r.p = p; + return r; +} + +typedef struct Cv3dTrackerTrackedObject +{ + int id; + CvPoint3D32f p; // location of the tracked object +} Cv3dTrackerTrackedObject; + +CV_INLINE Cv3dTrackerTrackedObject cv3dTrackerTrackedObject(int id, CvPoint3D32f p) +{ + Cv3dTrackerTrackedObject r; + r.id = id; + r.p = p; + return r; +} + +typedef struct Cv3dTrackerCameraInfo +{ + CvBool valid; + float mat[4][4]; /* maps camera coordinates to world coordinates */ + CvPoint2D32f principal_point; /* copied from intrinsics so this structure */ + /* has all the info we need */ +} Cv3dTrackerCameraInfo; + +typedef struct Cv3dTrackerCameraIntrinsics +{ + CvPoint2D32f principal_point; + float focal_length[2]; + float distortion[4]; +} Cv3dTrackerCameraIntrinsics; + +CVAPI(CvBool) cv3dTrackerCalibrateCameras(int num_cameras, + const Cv3dTrackerCameraIntrinsics camera_intrinsics[], /* size is num_cameras */ + CvSize etalon_size, + float square_size, + IplImage *samples[], /* size is num_cameras */ + Cv3dTrackerCameraInfo camera_info[]); /* size is num_cameras */ + +CVAPI(int) cv3dTrackerLocateObjects(int num_cameras, int num_objects, + const Cv3dTrackerCameraInfo camera_info[], /* size is num_cameras */ + const Cv3dTracker2dTrackedObject tracking_info[], /* size is num_objects*num_cameras */ + Cv3dTrackerTrackedObject tracked_objects[]); /* size is num_objects */ +/**************************************************************************************** + tracking_info is a rectangular array; one row per camera, num_objects elements per row. + The id field of any unused slots must be -1. Ids need not be ordered or consecutive. On + completion, the return value is the number of objects located; i.e., the number of objects + visible by more than one camera. The id field of any unused slots in tracked objects is + set to -1. +****************************************************************************************/ + + +/****************************************************************************************\ +* Skeletons and Linear-Contour Models * +\****************************************************************************************/ + +typedef enum CvLeeParameters +{ + CV_LEE_INT = 0, + CV_LEE_FLOAT = 1, + CV_LEE_DOUBLE = 2, + CV_LEE_AUTO = -1, + CV_LEE_ERODE = 0, + CV_LEE_ZOOM = 1, + CV_LEE_NON = 2 +} CvLeeParameters; + +#define CV_NEXT_VORONOISITE2D( SITE ) ((SITE)->edge[0]->site[((SITE)->edge[0]->site[0] == (SITE))]) +#define CV_PREV_VORONOISITE2D( SITE ) ((SITE)->edge[1]->site[((SITE)->edge[1]->site[0] == (SITE))]) +#define CV_FIRST_VORONOIEDGE2D( SITE ) ((SITE)->edge[0]) +#define CV_LAST_VORONOIEDGE2D( SITE ) ((SITE)->edge[1]) +#define CV_NEXT_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[(EDGE)->site[0] != (SITE)]) +#define CV_PREV_VORONOIEDGE2D( EDGE, SITE ) ((EDGE)->next[2 + ((EDGE)->site[0] != (SITE))]) +#define CV_VORONOIEDGE2D_BEGINNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] != (SITE))]) +#define CV_VORONOIEDGE2D_ENDNODE( EDGE, SITE ) ((EDGE)->node[((EDGE)->site[0] == (SITE))]) +#define CV_TWIN_VORONOISITE2D( SITE, EDGE ) ( (EDGE)->site[((EDGE)->site[0] == (SITE))]) + +#define CV_VORONOISITE2D_FIELDS() \ + struct CvVoronoiNode2D *node[2]; \ + struct CvVoronoiEdge2D *edge[2]; + +typedef struct CvVoronoiSite2D +{ + CV_VORONOISITE2D_FIELDS() + struct CvVoronoiSite2D *next[2]; +} CvVoronoiSite2D; + +#define CV_VORONOIEDGE2D_FIELDS() \ + struct CvVoronoiNode2D *node[2]; \ + struct CvVoronoiSite2D *site[2]; \ + struct CvVoronoiEdge2D *next[4]; + +typedef struct CvVoronoiEdge2D +{ + CV_VORONOIEDGE2D_FIELDS() +} CvVoronoiEdge2D; + +#define CV_VORONOINODE2D_FIELDS() \ + CV_SET_ELEM_FIELDS(CvVoronoiNode2D) \ + CvPoint2D32f pt; \ + float radius; + +typedef struct CvVoronoiNode2D +{ + CV_VORONOINODE2D_FIELDS() +} CvVoronoiNode2D; + +#define CV_VORONOIDIAGRAM2D_FIELDS() \ + CV_GRAPH_FIELDS() \ + CvSet *sites; + +typedef struct CvVoronoiDiagram2D +{ + CV_VORONOIDIAGRAM2D_FIELDS() +} CvVoronoiDiagram2D; + +/* Computes Voronoi Diagram for given polygons with holes */ +CVAPI(int) cvVoronoiDiagramFromContour(CvSeq* ContourSeq, + CvVoronoiDiagram2D** VoronoiDiagram, + CvMemStorage* VoronoiStorage, + CvLeeParameters contour_type CV_DEFAULT(CV_LEE_INT), + int contour_orientation CV_DEFAULT(-1), + int attempt_number CV_DEFAULT(10)); + +/* Computes Voronoi Diagram for domains in given image */ +CVAPI(int) cvVoronoiDiagramFromImage(IplImage* pImage, + CvSeq** ContourSeq, + CvVoronoiDiagram2D** VoronoiDiagram, + CvMemStorage* VoronoiStorage, + CvLeeParameters regularization_method CV_DEFAULT(CV_LEE_NON), + float approx_precision CV_DEFAULT(CV_LEE_AUTO)); + +/* Deallocates the storage */ +CVAPI(void) cvReleaseVoronoiStorage(CvVoronoiDiagram2D* VoronoiDiagram, + CvMemStorage** pVoronoiStorage); + +/*********************** Linear-Contour Model ****************************/ + +struct CvLCMEdge; +struct CvLCMNode; + +typedef struct CvLCMEdge +{ + CV_GRAPH_EDGE_FIELDS() + CvSeq* chain; + float width; + int index1; + int index2; +} CvLCMEdge; + +typedef struct CvLCMNode +{ + CV_GRAPH_VERTEX_FIELDS() + CvContour* contour; +} CvLCMNode; + + +/* Computes hybrid model from Voronoi Diagram */ +CVAPI(CvGraph*) cvLinearContorModelFromVoronoiDiagram(CvVoronoiDiagram2D* VoronoiDiagram, + float maxWidth); + +/* Releases hybrid model storage */ +CVAPI(int) cvReleaseLinearContorModelStorage(CvGraph** Graph); + + +/* two stereo-related functions */ + +CVAPI(void) cvInitPerspectiveTransform( CvSize size, const CvPoint2D32f vertex[4], double matrix[3][3], + CvArr* rectMap ); + +/*CVAPI(void) cvInitStereoRectification( CvStereoCamera* params, + CvArr* rectMap1, CvArr* rectMap2, + int do_undistortion );*/ + +/*************************** View Morphing Functions ************************/ + +typedef struct CvMatrix3 +{ + float m[3][3]; +} CvMatrix3; + +/* The order of the function corresponds to the order they should appear in + the view morphing pipeline */ + +/* Finds ending points of scanlines on left and right images of stereo-pair */ +CVAPI(void) cvMakeScanlines( const CvMatrix3* matrix, CvSize img_size, + int* scanlines1, int* scanlines2, + int* lengths1, int* lengths2, + int* line_count ); + +/* Grab pixel values from scanlines and stores them sequentially + (some sort of perspective image transform) */ +CVAPI(void) cvPreWarpImage( int line_count, + IplImage* img, + uchar* dst, + int* dst_nums, + int* scanlines); + +/* Approximate each grabbed scanline by a sequence of runs + (lossy run-length compression) */ +CVAPI(void) cvFindRuns( int line_count, + uchar* prewarp1, + uchar* prewarp2, + int* line_lengths1, + int* line_lengths2, + int* runs1, + int* runs2, + int* num_runs1, + int* num_runs2); + +/* Compares two sets of compressed scanlines */ +CVAPI(void) cvDynamicCorrespondMulti( int line_count, + int* first, + int* first_runs, + int* second, + int* second_runs, + int* first_corr, + int* second_corr); + +/* Finds scanline ending coordinates for some intermediate "virtual" camera position */ +CVAPI(void) cvMakeAlphaScanlines( int* scanlines1, + int* scanlines2, + int* scanlinesA, + int* lengths, + int line_count, + float alpha); + +/* Blends data of the left and right image scanlines to get + pixel values of "virtual" image scanlines */ +CVAPI(void) cvMorphEpilinesMulti( int line_count, + uchar* first_pix, + int* first_num, + uchar* second_pix, + int* second_num, + uchar* dst_pix, + int* dst_num, + float alpha, + int* first, + int* first_runs, + int* second, + int* second_runs, + int* first_corr, + int* second_corr); + +/* Does reverse warping of the morphing result to make + it fill the destination image rectangle */ +CVAPI(void) cvPostWarpImage( int line_count, + uchar* src, + int* src_nums, + IplImage* img, + int* scanlines); + +/* Deletes Moire (missed pixels that appear due to discretization) */ +CVAPI(void) cvDeleteMoire( IplImage* img ); + + +typedef struct CvConDensation +{ + int MP; + int DP; + float* DynamMatr; /* Matrix of the linear Dynamics system */ + float* State; /* Vector of State */ + int SamplesNum; /* Number of the Samples */ + float** flSamples; /* arr of the Sample Vectors */ + float** flNewSamples; /* temporary array of the Sample Vectors */ + float* flConfidence; /* Confidence for each Sample */ + float* flCumulative; /* Cumulative confidence */ + float* Temp; /* Temporary vector */ + float* RandomSample; /* RandomVector to update sample set */ + struct CvRandState* RandS; /* Array of structures to generate random vectors */ +} CvConDensation; + +/* Creates ConDensation filter state */ +CVAPI(CvConDensation*) cvCreateConDensation( int dynam_params, + int measure_params, + int sample_count ); + +/* Releases ConDensation filter state */ +CVAPI(void) cvReleaseConDensation( CvConDensation** condens ); + +/* Updates ConDensation filter by time (predict future state of the system) */ +CVAPI(void) cvConDensUpdateByTime( CvConDensation* condens); + +/* Initializes ConDensation filter samples */ +CVAPI(void) cvConDensInitSampleSet( CvConDensation* condens, CvMat* lower_bound, CvMat* upper_bound ); + +CV_INLINE int iplWidth( const IplImage* img ) +{ + return !img ? 0 : !img->roi ? img->width : img->roi->width; +} + +CV_INLINE int iplHeight( const IplImage* img ) +{ + return !img ? 0 : !img->roi ? img->height : img->roi->height; +} + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus + +/****************************************************************************************\ +* Calibration engine * +\****************************************************************************************/ + +typedef enum CvCalibEtalonType +{ + CV_CALIB_ETALON_USER = -1, + CV_CALIB_ETALON_CHESSBOARD = 0, + CV_CALIB_ETALON_CHECKERBOARD = CV_CALIB_ETALON_CHESSBOARD +} +CvCalibEtalonType; + +class CV_EXPORTS CvCalibFilter +{ +public: + /* Constructor & destructor */ + CvCalibFilter(); + virtual ~CvCalibFilter(); + + /* Sets etalon type - one for all cameras. + etalonParams is used in case of pre-defined etalons (such as chessboard). + Number of elements in etalonParams is determined by etalonType. + E.g., if etalon type is CV_ETALON_TYPE_CHESSBOARD then: + etalonParams[0] is number of squares per one side of etalon + etalonParams[1] is number of squares per another side of etalon + etalonParams[2] is linear size of squares in the board in arbitrary units. + pointCount & points are used in case of + CV_CALIB_ETALON_USER (user-defined) etalon. */ + virtual bool + SetEtalon( CvCalibEtalonType etalonType, double* etalonParams, + int pointCount = 0, CvPoint2D32f* points = 0 ); + + /* Retrieves etalon parameters/or and points */ + virtual CvCalibEtalonType + GetEtalon( int* paramCount = 0, const double** etalonParams = 0, + int* pointCount = 0, const CvPoint2D32f** etalonPoints = 0 ) const; + + /* Sets number of cameras calibrated simultaneously. It is equal to 1 initially */ + virtual void SetCameraCount( int cameraCount ); + + /* Retrieves number of cameras */ + int GetCameraCount() const { return cameraCount; } + + /* Starts cameras calibration */ + virtual bool SetFrames( int totalFrames ); + + /* Stops cameras calibration */ + virtual void Stop( bool calibrate = false ); + + /* Retrieves number of cameras */ + bool IsCalibrated() const { return isCalibrated; } + + /* Feeds another serie of snapshots (one per each camera) to filter. + Etalon points on these images are found automatically. + If the function can't locate points, it returns false */ + virtual bool FindEtalon( IplImage** imgs ); + + /* The same but takes matrices */ + virtual bool FindEtalon( CvMat** imgs ); + + /* Lower-level function for feeding filter with already found etalon points. + Array of point arrays for each camera is passed. */ + virtual bool Push( const CvPoint2D32f** points = 0 ); + + /* Returns total number of accepted frames and, optionally, + total number of frames to collect */ + virtual int GetFrameCount( int* framesTotal = 0 ) const; + + /* Retrieves camera parameters for specified camera. + If camera is not calibrated the function returns 0 */ + virtual const CvCamera* GetCameraParams( int idx = 0 ) const; + + virtual const CvStereoCamera* GetStereoParams() const; + + /* Sets camera parameters for all cameras */ + virtual bool SetCameraParams( CvCamera* params ); + + /* Saves all camera parameters to file */ + virtual bool SaveCameraParams( const char* filename ); + + /* Loads all camera parameters from file */ + virtual bool LoadCameraParams( const char* filename ); + + /* Undistorts images using camera parameters. Some of src pointers can be NULL. */ + virtual bool Undistort( IplImage** src, IplImage** dst ); + + /* Undistorts images using camera parameters. Some of src pointers can be NULL. */ + virtual bool Undistort( CvMat** src, CvMat** dst ); + + /* Returns array of etalon points detected/partally detected + on the latest frame for idx-th camera */ + virtual bool GetLatestPoints( int idx, CvPoint2D32f** pts, + int* count, bool* found ); + + /* Draw the latest detected/partially detected etalon */ + virtual void DrawPoints( IplImage** dst ); + + /* Draw the latest detected/partially detected etalon */ + virtual void DrawPoints( CvMat** dst ); + + virtual bool Rectify( IplImage** srcarr, IplImage** dstarr ); + virtual bool Rectify( CvMat** srcarr, CvMat** dstarr ); + +protected: + + enum { MAX_CAMERAS = 3 }; + + /* etalon data */ + CvCalibEtalonType etalonType; + int etalonParamCount; + double* etalonParams; + int etalonPointCount; + CvPoint2D32f* etalonPoints; + CvSize imgSize; + CvMat* grayImg; + CvMat* tempImg; + CvMemStorage* storage; + + /* camera data */ + int cameraCount; + CvCamera cameraParams[MAX_CAMERAS]; + CvStereoCamera stereo; + CvPoint2D32f* points[MAX_CAMERAS]; + CvMat* undistMap[MAX_CAMERAS][2]; + CvMat* undistImg; + int latestCounts[MAX_CAMERAS]; + CvPoint2D32f* latestPoints[MAX_CAMERAS]; + CvMat* rectMap[MAX_CAMERAS][2]; + + /* Added by Valery */ + //CvStereoCamera stereoParams; + + int maxPoints; + int framesTotal; + int framesAccepted; + bool isCalibrated; +}; + +#include +#include + +class CV_EXPORTS CvImage +{ +public: + CvImage() : image(0), refcount(0) {} + CvImage( CvSize _size, int _depth, int _channels ) + { + image = cvCreateImage( _size, _depth, _channels ); + refcount = image ? new int(1) : 0; + } + + CvImage( IplImage* img ) : image(img) + { + refcount = image ? new int(1) : 0; + } + + CvImage( const CvImage& img ) : image(img.image), refcount(img.refcount) + { + if( refcount ) ++(*refcount); + } + + CvImage( const char* filename, const char* imgname=0, int color=-1 ) : image(0), refcount(0) + { load( filename, imgname, color ); } + + CvImage( CvFileStorage* fs, const char* mapname, const char* imgname ) : image(0), refcount(0) + { read( fs, mapname, imgname ); } + + CvImage( CvFileStorage* fs, const char* seqname, int idx ) : image(0), refcount(0) + { read( fs, seqname, idx ); } + + ~CvImage() + { + if( refcount && !(--*refcount) ) + { + cvReleaseImage( &image ); + delete refcount; + } + } + + CvImage clone() { return CvImage(image ? cvCloneImage(image) : 0); } + + void create( CvSize _size, int _depth, int _channels ) + { + if( !image || !refcount || + image->width != _size.width || image->height != _size.height || + image->depth != _depth || image->nChannels != _channels ) + attach( cvCreateImage( _size, _depth, _channels )); + } + + void release() { detach(); } + void clear() { detach(); } + + void attach( IplImage* img, bool use_refcount=true ) + { + if( refcount && --*refcount == 0 ) + { + cvReleaseImage( &image ); + delete refcount; + } + image = img; + refcount = use_refcount && image ? new int(1) : 0; + } + + void detach() + { + if( refcount && --*refcount == 0 ) + { + cvReleaseImage( &image ); + delete refcount; + } + image = 0; + refcount = 0; + } + + bool load( const char* filename, const char* imgname=0, int color=-1 ); + bool read( CvFileStorage* fs, const char* mapname, const char* imgname ); + bool read( CvFileStorage* fs, const char* seqname, int idx ); + void save( const char* filename, const char* imgname, const int* params=0 ); + void write( CvFileStorage* fs, const char* imgname ); + + void show( const char* window_name ); + bool is_valid() { return image != 0; } + + int width() const { return image ? image->width : 0; } + int height() const { return image ? image->height : 0; } + + CvSize size() const { return image ? cvSize(image->width, image->height) : cvSize(0,0); } + + CvSize roi_size() const + { + return !image ? cvSize(0,0) : + !image->roi ? cvSize(image->width,image->height) : + cvSize(image->roi->width, image->roi->height); + } + + CvRect roi() const + { + return !image ? cvRect(0,0,0,0) : + !image->roi ? cvRect(0,0,image->width,image->height) : + cvRect(image->roi->xOffset,image->roi->yOffset, + image->roi->width,image->roi->height); + } + + int coi() const { return !image || !image->roi ? 0 : image->roi->coi; } + + void set_roi(CvRect _roi) { cvSetImageROI(image,_roi); } + void reset_roi() { cvResetImageROI(image); } + void set_coi(int _coi) { cvSetImageCOI(image,_coi); } + int depth() const { return image ? image->depth : 0; } + int channels() const { return image ? image->nChannels : 0; } + int pix_size() const { return image ? ((image->depth & 255)>>3)*image->nChannels : 0; } + + uchar* data() { return image ? (uchar*)image->imageData : 0; } + const uchar* data() const { return image ? (const uchar*)image->imageData : 0; } + int step() const { return image ? image->widthStep : 0; } + int origin() const { return image ? image->origin : 0; } + + uchar* roi_row(int y) + { + assert(0<=y); + assert(!image ? + 1 : image->roi ? + yroi->height : yheight); + + return !image ? 0 : + !image->roi ? + (uchar*)(image->imageData + y*image->widthStep) : + (uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep + + image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels); + } + + const uchar* roi_row(int y) const + { + assert(0<=y); + assert(!image ? + 1 : image->roi ? + yroi->height : yheight); + + return !image ? 0 : + !image->roi ? + (const uchar*)(image->imageData + y*image->widthStep) : + (const uchar*)(image->imageData + (y+image->roi->yOffset)*image->widthStep + + image->roi->xOffset*((image->depth & 255)>>3)*image->nChannels); + } + + operator const IplImage* () const { return image; } + operator IplImage* () { return image; } + + CvImage& operator = (const CvImage& img) + { + if( img.refcount ) + ++*img.refcount; + if( refcount && !(--*refcount) ) + cvReleaseImage( &image ); + image=img.image; + refcount=img.refcount; + return *this; + } + +protected: + IplImage* image; + int* refcount; +}; + + +class CV_EXPORTS CvMatrix +{ +public: + CvMatrix() : matrix(0) {} + CvMatrix( int _rows, int _cols, int _type ) + { matrix = cvCreateMat( _rows, _cols, _type ); } + + CvMatrix( int _rows, int _cols, int _type, CvMat* hdr, + void* _data=0, int _step=CV_AUTOSTEP ) + { matrix = cvInitMatHeader( hdr, _rows, _cols, _type, _data, _step ); } + + CvMatrix( int rows, int cols, int type, CvMemStorage* storage, bool alloc_data=true ); + + CvMatrix( int _rows, int _cols, int _type, void* _data, int _step=CV_AUTOSTEP ) + { matrix = cvCreateMatHeader( _rows, _cols, _type ); + cvSetData( matrix, _data, _step ); } + + CvMatrix( CvMat* m ) + { matrix = m; } + + CvMatrix( const CvMatrix& m ) + { + matrix = m.matrix; + addref(); + } + + CvMatrix( const char* filename, const char* matname=0, int color=-1 ) : matrix(0) + { load( filename, matname, color ); } + + CvMatrix( CvFileStorage* fs, const char* mapname, const char* matname ) : matrix(0) + { read( fs, mapname, matname ); } + + CvMatrix( CvFileStorage* fs, const char* seqname, int idx ) : matrix(0) + { read( fs, seqname, idx ); } + + ~CvMatrix() + { + release(); + } + + CvMatrix clone() { return CvMatrix(matrix ? cvCloneMat(matrix) : 0); } + + void set( CvMat* m, bool add_ref ) + { + release(); + matrix = m; + if( add_ref ) + addref(); + } + + void create( int _rows, int _cols, int _type ) + { + if( !matrix || !matrix->refcount || + matrix->rows != _rows || matrix->cols != _cols || + CV_MAT_TYPE(matrix->type) != _type ) + set( cvCreateMat( _rows, _cols, _type ), false ); + } + + void addref() const + { + if( matrix ) + { + if( matrix->hdr_refcount ) + ++matrix->hdr_refcount; + else if( matrix->refcount ) + ++*matrix->refcount; + } + } + + void release() + { + if( matrix ) + { + if( matrix->hdr_refcount ) + { + if( --matrix->hdr_refcount == 0 ) + cvReleaseMat( &matrix ); + } + else if( matrix->refcount ) + { + if( --*matrix->refcount == 0 ) + cvFree( &matrix->refcount ); + } + matrix = 0; + } + } + + void clear() + { + release(); + } + + bool load( const char* filename, const char* matname=0, int color=-1 ); + bool read( CvFileStorage* fs, const char* mapname, const char* matname ); + bool read( CvFileStorage* fs, const char* seqname, int idx ); + void save( const char* filename, const char* matname, const int* params=0 ); + void write( CvFileStorage* fs, const char* matname ); + + void show( const char* window_name ); + + bool is_valid() { return matrix != 0; } + + int rows() const { return matrix ? matrix->rows : 0; } + int cols() const { return matrix ? matrix->cols : 0; } + + CvSize size() const + { + return !matrix ? cvSize(0,0) : cvSize(matrix->rows,matrix->cols); + } + + int type() const { return matrix ? CV_MAT_TYPE(matrix->type) : 0; } + int depth() const { return matrix ? CV_MAT_DEPTH(matrix->type) : 0; } + int channels() const { return matrix ? CV_MAT_CN(matrix->type) : 0; } + int pix_size() const { return matrix ? CV_ELEM_SIZE(matrix->type) : 0; } + + uchar* data() { return matrix ? matrix->data.ptr : 0; } + const uchar* data() const { return matrix ? matrix->data.ptr : 0; } + int step() const { return matrix ? matrix->step : 0; } + + void set_data( void* _data, int _step=CV_AUTOSTEP ) + { cvSetData( matrix, _data, _step ); } + + uchar* row(int i) { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; } + const uchar* row(int i) const + { return !matrix ? 0 : matrix->data.ptr + i*matrix->step; } + + operator const CvMat* () const { return matrix; } + operator CvMat* () { return matrix; } + + CvMatrix& operator = (const CvMatrix& _m) + { + _m.addref(); + release(); + matrix = _m.matrix; + return *this; + } + +protected: + CvMat* matrix; +}; + +/****************************************************************************************\ + * CamShiftTracker * + \****************************************************************************************/ + +class CV_EXPORTS CvCamShiftTracker +{ +public: + + CvCamShiftTracker(); + virtual ~CvCamShiftTracker(); + + /**** Characteristics of the object that are calculated by track_object method *****/ + float get_orientation() const // orientation of the object in degrees + { return m_box.angle; } + float get_length() const // the larger linear size of the object + { return m_box.size.height; } + float get_width() const // the smaller linear size of the object + { return m_box.size.width; } + CvPoint2D32f get_center() const // center of the object + { return m_box.center; } + CvRect get_window() const // bounding rectangle for the object + { return m_comp.rect; } + + /*********************** Tracking parameters ************************/ + int get_threshold() const // thresholding value that applied to back project + { return m_threshold; } + + int get_hist_dims( int* dims = 0 ) const // returns number of histogram dimensions and sets + { return m_hist ? cvGetDims( m_hist->bins, dims ) : 0; } + + int get_min_ch_val( int channel ) const // get the minimum allowed value of the specified channel + { return m_min_ch_val[channel]; } + + int get_max_ch_val( int channel ) const // get the maximum allowed value of the specified channel + { return m_max_ch_val[channel]; } + + // set initial object rectangle (must be called before initial calculation of the histogram) + bool set_window( CvRect window) + { m_comp.rect = window; return true; } + + bool set_threshold( int threshold ) // threshold applied to the histogram bins + { m_threshold = threshold; return true; } + + bool set_hist_bin_range( int dim, int min_val, int max_val ); + + bool set_hist_dims( int c_dims, int* dims );// set the histogram parameters + + bool set_min_ch_val( int channel, int val ) // set the minimum allowed value of the specified channel + { m_min_ch_val[channel] = val; return true; } + bool set_max_ch_val( int channel, int val ) // set the maximum allowed value of the specified channel + { m_max_ch_val[channel] = val; return true; } + + /************************ The processing methods *********************************/ + // update object position + virtual bool track_object( const IplImage* cur_frame ); + + // update object histogram + virtual bool update_histogram( const IplImage* cur_frame ); + + // reset histogram + virtual void reset_histogram(); + + /************************ Retrieving internal data *******************************/ + // get back project image + virtual IplImage* get_back_project() + { return m_back_project; } + + float query( int* bin ) const + { return m_hist ? (float)cvGetRealND(m_hist->bins, bin) : 0.f; } + +protected: + + // internal method for color conversion: fills m_color_planes group + virtual void color_transform( const IplImage* img ); + + CvHistogram* m_hist; + + CvBox2D m_box; + CvConnectedComp m_comp; + + float m_hist_ranges_data[CV_MAX_DIM][2]; + float* m_hist_ranges[CV_MAX_DIM]; + + int m_min_ch_val[CV_MAX_DIM]; + int m_max_ch_val[CV_MAX_DIM]; + int m_threshold; + + IplImage* m_color_planes[CV_MAX_DIM]; + IplImage* m_back_project; + IplImage* m_temp; + IplImage* m_mask; +}; + +/****************************************************************************************\ +* Expectation - Maximization * +\****************************************************************************************/ +struct CV_EXPORTS_W_MAP CvEMParams +{ + CvEMParams(); + CvEMParams( int nclusters, int cov_mat_type=cv::EM::COV_MAT_DIAGONAL, + int start_step=cv::EM::START_AUTO_STEP, + CvTermCriteria term_crit=cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON), + const CvMat* probs=0, const CvMat* weights=0, const CvMat* means=0, const CvMat** covs=0 ); + + CV_PROP_RW int nclusters; + CV_PROP_RW int cov_mat_type; + CV_PROP_RW int start_step; + const CvMat* probs; + const CvMat* weights; + const CvMat* means; + const CvMat** covs; + CV_PROP_RW CvTermCriteria term_crit; +}; + + +class CV_EXPORTS_W CvEM : public CvStatModel +{ +public: + // Type of covariation matrices + enum { COV_MAT_SPHERICAL=cv::EM::COV_MAT_SPHERICAL, + COV_MAT_DIAGONAL =cv::EM::COV_MAT_DIAGONAL, + COV_MAT_GENERIC =cv::EM::COV_MAT_GENERIC }; + + // The initial step + enum { START_E_STEP=cv::EM::START_E_STEP, + START_M_STEP=cv::EM::START_M_STEP, + START_AUTO_STEP=cv::EM::START_AUTO_STEP }; + + CV_WRAP CvEM(); + CvEM( const CvMat* samples, const CvMat* sampleIdx=0, + CvEMParams params=CvEMParams(), CvMat* labels=0 ); + + virtual ~CvEM(); + + virtual bool train( const CvMat* samples, const CvMat* sampleIdx=0, + CvEMParams params=CvEMParams(), CvMat* labels=0 ); + + virtual float predict( const CvMat* sample, CV_OUT CvMat* probs ) const; + + CV_WRAP CvEM( const cv::Mat& samples, const cv::Mat& sampleIdx=cv::Mat(), + CvEMParams params=CvEMParams() ); + + CV_WRAP virtual bool train( const cv::Mat& samples, + const cv::Mat& sampleIdx=cv::Mat(), + CvEMParams params=CvEMParams(), + CV_OUT cv::Mat* labels=0 ); + + CV_WRAP virtual float predict( const cv::Mat& sample, CV_OUT cv::Mat* probs=0 ) const; + CV_WRAP virtual double calcLikelihood( const cv::Mat &sample ) const; + + CV_WRAP int getNClusters() const; + CV_WRAP cv::Mat getMeans() const; + CV_WRAP void getCovs(CV_OUT std::vector& covs) const; + CV_WRAP cv::Mat getWeights() const; + CV_WRAP cv::Mat getProbs() const; + + CV_WRAP inline double getLikelihood() const { return emObj.isTrained() ? logLikelihood : DBL_MAX; } + + CV_WRAP virtual void clear(); + + int get_nclusters() const; + const CvMat* get_means() const; + const CvMat** get_covs() const; + const CvMat* get_weights() const; + const CvMat* get_probs() const; + + inline double get_log_likelihood() const { return getLikelihood(); } + + virtual void read( CvFileStorage* fs, CvFileNode* node ); + virtual void write( CvFileStorage* fs, const char* name ) const; + +protected: + void set_mat_hdrs(); + + cv::EM emObj; + cv::Mat probs; + double logLikelihood; + + CvMat meansHdr; + std::vector covsHdrs; + std::vector covsPtrs; + CvMat weightsHdr; + CvMat probsHdr; +}; + +namespace cv +{ + +typedef CvEMParams EMParams; +typedef CvEM ExpectationMaximization; + +/*! + The Patch Generator class + */ +class CV_EXPORTS PatchGenerator +{ +public: + PatchGenerator(); + PatchGenerator(double _backgroundMin, double _backgroundMax, + double _noiseRange, bool _randomBlur=true, + double _lambdaMin=0.6, double _lambdaMax=1.5, + double _thetaMin=-CV_PI, double _thetaMax=CV_PI, + double _phiMin=-CV_PI, double _phiMax=CV_PI ); + void operator()(const Mat& image, Point2f pt, Mat& patch, Size patchSize, RNG& rng) const; + void operator()(const Mat& image, const Mat& transform, Mat& patch, + Size patchSize, RNG& rng) const; + void warpWholeImage(const Mat& image, Mat& matT, Mat& buf, + CV_OUT Mat& warped, int border, RNG& rng) const; + void generateRandomTransform(Point2f srcCenter, Point2f dstCenter, + CV_OUT Mat& transform, RNG& rng, + bool inverse=false) const; + void setAffineParam(double lambda, double theta, double phi); + + double backgroundMin, backgroundMax; + double noiseRange; + bool randomBlur; + double lambdaMin, lambdaMax; + double thetaMin, thetaMax; + double phiMin, phiMax; +}; + + +class CV_EXPORTS LDetector +{ +public: + LDetector(); + LDetector(int _radius, int _threshold, int _nOctaves, + int _nViews, double _baseFeatureSize, double _clusteringDistance); + void operator()(const Mat& image, + CV_OUT vector& keypoints, + int maxCount=0, bool scaleCoords=true) const; + void operator()(const vector& pyr, + CV_OUT vector& keypoints, + int maxCount=0, bool scaleCoords=true) const; + void getMostStable2D(const Mat& image, CV_OUT vector& keypoints, + int maxCount, const PatchGenerator& patchGenerator) const; + void setVerbose(bool verbose); + + void read(const FileNode& node); + void write(FileStorage& fs, const String& name=String()) const; + + int radius; + int threshold; + int nOctaves; + int nViews; + bool verbose; + + double baseFeatureSize; + double clusteringDistance; +}; + +typedef LDetector YAPE; + +class CV_EXPORTS FernClassifier +{ +public: + FernClassifier(); + FernClassifier(const FileNode& node); + FernClassifier(const vector >& points, + const vector& refimgs, + const vector >& labels=vector >(), + int _nclasses=0, int _patchSize=PATCH_SIZE, + int _signatureSize=DEFAULT_SIGNATURE_SIZE, + int _nstructs=DEFAULT_STRUCTS, + int _structSize=DEFAULT_STRUCT_SIZE, + int _nviews=DEFAULT_VIEWS, + int _compressionMethod=COMPRESSION_NONE, + const PatchGenerator& patchGenerator=PatchGenerator()); + virtual ~FernClassifier(); + virtual void read(const FileNode& n); + virtual void write(FileStorage& fs, const String& name=String()) const; + virtual void trainFromSingleView(const Mat& image, + const vector& keypoints, + int _patchSize=PATCH_SIZE, + int _signatureSize=DEFAULT_SIGNATURE_SIZE, + int _nstructs=DEFAULT_STRUCTS, + int _structSize=DEFAULT_STRUCT_SIZE, + int _nviews=DEFAULT_VIEWS, + int _compressionMethod=COMPRESSION_NONE, + const PatchGenerator& patchGenerator=PatchGenerator()); + virtual void train(const vector >& points, + const vector& refimgs, + const vector >& labels=vector >(), + int _nclasses=0, int _patchSize=PATCH_SIZE, + int _signatureSize=DEFAULT_SIGNATURE_SIZE, + int _nstructs=DEFAULT_STRUCTS, + int _structSize=DEFAULT_STRUCT_SIZE, + int _nviews=DEFAULT_VIEWS, + int _compressionMethod=COMPRESSION_NONE, + const PatchGenerator& patchGenerator=PatchGenerator()); + virtual int operator()(const Mat& img, Point2f kpt, vector& signature) const; + virtual int operator()(const Mat& patch, vector& signature) const; + virtual void clear(); + virtual bool empty() const; + void setVerbose(bool verbose); + + int getClassCount() const; + int getStructCount() const; + int getStructSize() const; + int getSignatureSize() const; + int getCompressionMethod() const; + Size getPatchSize() const; + + struct Feature + { + uchar x1, y1, x2, y2; + Feature() : x1(0), y1(0), x2(0), y2(0) {} + Feature(int _x1, int _y1, int _x2, int _y2) + : x1((uchar)_x1), y1((uchar)_y1), x2((uchar)_x2), y2((uchar)_y2) + {} + template bool operator ()(const Mat_<_Tp>& patch) const + { return patch(y1,x1) > patch(y2, x2); } + }; + + enum + { + PATCH_SIZE = 31, + DEFAULT_STRUCTS = 50, + DEFAULT_STRUCT_SIZE = 9, + DEFAULT_VIEWS = 5000, + DEFAULT_SIGNATURE_SIZE = 176, + COMPRESSION_NONE = 0, + COMPRESSION_RANDOM_PROJ = 1, + COMPRESSION_PCA = 2, + DEFAULT_COMPRESSION_METHOD = COMPRESSION_NONE + }; + +protected: + virtual void prepare(int _nclasses, int _patchSize, int _signatureSize, + int _nstructs, int _structSize, + int _nviews, int _compressionMethod); + virtual void finalize(RNG& rng); + virtual int getLeaf(int fidx, const Mat& patch) const; + + bool verbose; + int nstructs; + int structSize; + int nclasses; + int signatureSize; + int compressionMethod; + int leavesPerStruct; + Size patchSize; + vector features; + vector classCounters; + vector posteriors; +}; + + +/****************************************************************************************\ + * Calonder Classifier * + \****************************************************************************************/ + +struct RTreeNode; + +struct CV_EXPORTS BaseKeypoint +{ + int x; + int y; + IplImage* image; + + BaseKeypoint() + : x(0), y(0), image(NULL) + {} + + BaseKeypoint(int _x, int _y, IplImage* _image) + : x(_x), y(_y), image(_image) + {} +}; + +class CV_EXPORTS RandomizedTree +{ +public: + friend class RTreeClassifier; + + static const uchar PATCH_SIZE = 32; + static const int DEFAULT_DEPTH = 9; + static const int DEFAULT_VIEWS = 5000; + static const size_t DEFAULT_REDUCED_NUM_DIM = 176; + static float GET_LOWER_QUANT_PERC() { return .03f; } + static float GET_UPPER_QUANT_PERC() { return .92f; } + + RandomizedTree(); + ~RandomizedTree(); + + void train(vector const& base_set, RNG &rng, + int depth, int views, size_t reduced_num_dim, int num_quant_bits); + void train(vector const& base_set, RNG &rng, + PatchGenerator &make_patch, int depth, int views, size_t reduced_num_dim, + int num_quant_bits); + + // following two funcs are EXPERIMENTAL (do not use unless you know exactly what you do) + static void quantizeVector(float *vec, int dim, int N, float bnds[2], int clamp_mode=0); + static void quantizeVector(float *src, int dim, int N, float bnds[2], uchar *dst); + + // patch_data must be a 32x32 array (no row padding) + float* getPosterior(uchar* patch_data); + const float* getPosterior(uchar* patch_data) const; + uchar* getPosterior2(uchar* patch_data); + const uchar* getPosterior2(uchar* patch_data) const; + + void read(const char* file_name, int num_quant_bits); + void read(std::istream &is, int num_quant_bits); + void write(const char* file_name) const; + void write(std::ostream &os) const; + + int classes() { return classes_; } + int depth() { return depth_; } + + //void setKeepFloatPosteriors(bool b) { keep_float_posteriors_ = b; } + void discardFloatPosteriors() { freePosteriors(1); } + + inline void applyQuantization(int num_quant_bits) { makePosteriors2(num_quant_bits); } + + // debug + void savePosteriors(std::string url, bool append=false); + void savePosteriors2(std::string url, bool append=false); + +private: + int classes_; + int depth_; + int num_leaves_; + vector nodes_; + float **posteriors_; // 16-bytes aligned posteriors + uchar **posteriors2_; // 16-bytes aligned posteriors + vector leaf_counts_; + + void createNodes(int num_nodes, RNG &rng); + void allocPosteriorsAligned(int num_leaves, int num_classes); + void freePosteriors(int which); // which: 1=posteriors_, 2=posteriors2_, 3=both + void init(int classes, int depth, RNG &rng); + void addExample(int class_id, uchar* patch_data); + void finalize(size_t reduced_num_dim, int num_quant_bits); + int getIndex(uchar* patch_data) const; + inline float* getPosteriorByIndex(int index); + inline const float* getPosteriorByIndex(int index) const; + inline uchar* getPosteriorByIndex2(int index); + inline const uchar* getPosteriorByIndex2(int index) const; + //void makeRandomMeasMatrix(float *cs_phi, PHI_DISTR_TYPE dt, size_t reduced_num_dim); + void convertPosteriorsToChar(); + void makePosteriors2(int num_quant_bits); + void compressLeaves(size_t reduced_num_dim); + void estimateQuantPercForPosteriors(float perc[2]); +}; + + +inline uchar* getData(IplImage* image) +{ + return reinterpret_cast(image->imageData); +} + +inline float* RandomizedTree::getPosteriorByIndex(int index) +{ + return const_cast(const_cast(this)->getPosteriorByIndex(index)); +} + +inline const float* RandomizedTree::getPosteriorByIndex(int index) const +{ + return posteriors_[index]; +} + +inline uchar* RandomizedTree::getPosteriorByIndex2(int index) +{ + return const_cast(const_cast(this)->getPosteriorByIndex2(index)); +} + +inline const uchar* RandomizedTree::getPosteriorByIndex2(int index) const +{ + return posteriors2_[index]; +} + +struct CV_EXPORTS RTreeNode +{ + short offset1, offset2; + + RTreeNode() {} + RTreeNode(uchar x1, uchar y1, uchar x2, uchar y2) + : offset1(y1*RandomizedTree::PATCH_SIZE + x1), + offset2(y2*RandomizedTree::PATCH_SIZE + x2) + {} + + //! Left child on 0, right child on 1 + inline bool operator() (uchar* patch_data) const + { + return patch_data[offset1] > patch_data[offset2]; + } +}; + +class CV_EXPORTS RTreeClassifier +{ +public: + static const int DEFAULT_TREES = 48; + static const size_t DEFAULT_NUM_QUANT_BITS = 4; + + RTreeClassifier(); + void train(vector const& base_set, + RNG &rng, + int num_trees = RTreeClassifier::DEFAULT_TREES, + int depth = RandomizedTree::DEFAULT_DEPTH, + int views = RandomizedTree::DEFAULT_VIEWS, + size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM, + int num_quant_bits = DEFAULT_NUM_QUANT_BITS); + void train(vector const& base_set, + RNG &rng, + PatchGenerator &make_patch, + int num_trees = RTreeClassifier::DEFAULT_TREES, + int depth = RandomizedTree::DEFAULT_DEPTH, + int views = RandomizedTree::DEFAULT_VIEWS, + size_t reduced_num_dim = RandomizedTree::DEFAULT_REDUCED_NUM_DIM, + int num_quant_bits = DEFAULT_NUM_QUANT_BITS); + + // sig must point to a memory block of at least classes()*sizeof(float|uchar) bytes + void getSignature(IplImage *patch, uchar *sig) const; + void getSignature(IplImage *patch, float *sig) const; + void getSparseSignature(IplImage *patch, float *sig, float thresh) const; + // TODO: deprecated in favor of getSignature overload, remove + void getFloatSignature(IplImage *patch, float *sig) const { getSignature(patch, sig); } + + static int countNonZeroElements(float *vec, int n, double tol=1e-10); + static inline void safeSignatureAlloc(uchar **sig, int num_sig=1, int sig_len=176); + static inline uchar* safeSignatureAlloc(int num_sig=1, int sig_len=176); + + inline int classes() const { return classes_; } + inline int original_num_classes() const { return original_num_classes_; } + + void setQuantization(int num_quant_bits); + void discardFloatPosteriors(); + + void read(const char* file_name); + void read(std::istream &is); + void write(const char* file_name) const; + void write(std::ostream &os) const; + + // experimental and debug + void saveAllFloatPosteriors(std::string file_url); + void saveAllBytePosteriors(std::string file_url); + void setFloatPosteriorsFromTextfile_176(std::string url); + float countZeroElements(); + + vector trees_; + +private: + int classes_; + int num_quant_bits_; + mutable uchar **posteriors_; + mutable unsigned short *ptemp_; + int original_num_classes_; + bool keep_floats_; +}; + +/****************************************************************************************\ +* One-Way Descriptor * +\****************************************************************************************/ + +// CvAffinePose: defines a parameterized affine transformation of an image patch. +// An image patch is rotated on angle phi (in degrees), then scaled lambda1 times +// along horizontal and lambda2 times along vertical direction, and then rotated again +// on angle (theta - phi). +class CV_EXPORTS CvAffinePose +{ +public: + float phi; + float theta; + float lambda1; + float lambda2; +}; + +class CV_EXPORTS OneWayDescriptor +{ +public: + OneWayDescriptor(); + ~OneWayDescriptor(); + + // allocates memory for given descriptor parameters + void Allocate(int pose_count, CvSize size, int nChannels); + + // GenerateSamples: generates affine transformed patches with averaging them over small transformation variations. + // If external poses and transforms were specified, uses them instead of generating random ones + // - pose_count: the number of poses to be generated + // - frontal: the input patch (can be a roi in a larger image) + // - norm: if nonzero, normalizes the output patch so that the sum of pixel intensities is 1 + void GenerateSamples(int pose_count, IplImage* frontal, int norm = 0); + + // GenerateSamplesFast: generates affine transformed patches with averaging them over small transformation variations. + // Uses precalculated transformed pca components. + // - frontal: the input patch (can be a roi in a larger image) + // - pca_hr_avg: pca average vector + // - pca_hr_eigenvectors: pca eigenvectors + // - pca_descriptors: an array of precomputed descriptors of pca components containing their affine transformations + // pca_descriptors[0] corresponds to the average, pca_descriptors[1]-pca_descriptors[pca_dim] correspond to eigenvectors + void GenerateSamplesFast(IplImage* frontal, CvMat* pca_hr_avg, + CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors); + + // sets the poses and corresponding transforms + void SetTransforms(CvAffinePose* poses, CvMat** transforms); + + // Initialize: builds a descriptor. + // - pose_count: the number of poses to build. If poses were set externally, uses them rather than generating random ones + // - frontal: input patch. Can be a roi in a larger image + // - feature_name: the feature name to be associated with the descriptor + // - norm: if 1, the affine transformed patches are normalized so that their sum is 1 + void Initialize(int pose_count, IplImage* frontal, const char* feature_name = 0, int norm = 0); + + // InitializeFast: builds a descriptor using precomputed descriptors of pca components + // - pose_count: the number of poses to build + // - frontal: input patch. Can be a roi in a larger image + // - feature_name: the feature name to be associated with the descriptor + // - pca_hr_avg: average vector for PCA + // - pca_hr_eigenvectors: PCA eigenvectors (one vector per row) + // - pca_descriptors: precomputed descriptors of PCA components, the first descriptor for the average vector + // followed by the descriptors for eigenvectors + void InitializeFast(int pose_count, IplImage* frontal, const char* feature_name, + CvMat* pca_hr_avg, CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors); + + // ProjectPCASample: unwarps an image patch into a vector and projects it into PCA space + // - patch: input image patch + // - avg: PCA average vector + // - eigenvectors: PCA eigenvectors, one per row + // - pca_coeffs: output PCA coefficients + void ProjectPCASample(IplImage* patch, CvMat* avg, CvMat* eigenvectors, CvMat* pca_coeffs) const; + + // InitializePCACoeffs: projects all warped patches into PCA space + // - avg: PCA average vector + // - eigenvectors: PCA eigenvectors, one per row + void InitializePCACoeffs(CvMat* avg, CvMat* eigenvectors); + + // EstimatePose: finds the closest match between an input patch and a set of patches with different poses + // - patch: input image patch + // - pose_idx: the output index of the closest pose + // - distance: the distance to the closest pose (L2 distance) + void EstimatePose(IplImage* patch, int& pose_idx, float& distance) const; + + // EstimatePosePCA: finds the closest match between an input patch and a set of patches with different poses. + // The distance between patches is computed in PCA space + // - patch: input image patch + // - pose_idx: the output index of the closest pose + // - distance: distance to the closest pose (L2 distance in PCA space) + // - avg: PCA average vector. If 0, matching without PCA is used + // - eigenvectors: PCA eigenvectors, one per row + void EstimatePosePCA(CvArr* patch, int& pose_idx, float& distance, CvMat* avg, CvMat* eigenvalues) const; + + // GetPatchSize: returns the size of each image patch after warping (2 times smaller than the input patch) + CvSize GetPatchSize() const + { + return m_patch_size; + } + + // GetInputPatchSize: returns the required size of the patch that the descriptor is built from + // (2 time larger than the patch after warping) + CvSize GetInputPatchSize() const + { + return cvSize(m_patch_size.width*2, m_patch_size.height*2); + } + + // GetPatch: returns a patch corresponding to specified pose index + // - index: pose index + // - return value: the patch corresponding to specified pose index + IplImage* GetPatch(int index); + + // GetPose: returns a pose corresponding to specified pose index + // - index: pose index + // - return value: the pose corresponding to specified pose index + CvAffinePose GetPose(int index) const; + + // Save: saves all patches with different poses to a specified path + void Save(const char* path); + + // ReadByName: reads a descriptor from a file storage + // - fs: file storage + // - parent: parent node + // - name: node name + // - return value: 1 if succeeded, 0 otherwise + int ReadByName(CvFileStorage* fs, CvFileNode* parent, const char* name); + + // ReadByName: reads a descriptor from a file node + // - parent: parent node + // - name: node name + // - return value: 1 if succeeded, 0 otherwise + int ReadByName(const FileNode &parent, const char* name); + + // Write: writes a descriptor into a file storage + // - fs: file storage + // - name: node name + void Write(CvFileStorage* fs, const char* name); + + // GetFeatureName: returns a name corresponding to a feature + const char* GetFeatureName() const; + + // GetCenter: returns the center of the feature + CvPoint GetCenter() const; + + void SetPCADimHigh(int pca_dim_high) {m_pca_dim_high = pca_dim_high;}; + void SetPCADimLow(int pca_dim_low) {m_pca_dim_low = pca_dim_low;}; + + int GetPCADimLow() const; + int GetPCADimHigh() const; + + CvMat** GetPCACoeffs() const {return m_pca_coeffs;} + +protected: + int m_pose_count; // the number of poses + CvSize m_patch_size; // size of each image + IplImage** m_samples; // an array of length m_pose_count containing the patch in different poses + IplImage* m_input_patch; + IplImage* m_train_patch; + CvMat** m_pca_coeffs; // an array of length m_pose_count containing pca decomposition of the patch in different poses + CvAffinePose* m_affine_poses; // an array of poses + CvMat** m_transforms; // an array of affine transforms corresponding to poses + + string m_feature_name; // the name of the feature associated with the descriptor + CvPoint m_center; // the coordinates of the feature (the center of the input image ROI) + + int m_pca_dim_high; // the number of descriptor pca components to use for generating affine poses + int m_pca_dim_low; // the number of pca components to use for comparison +}; + + +// OneWayDescriptorBase: encapsulates functionality for training/loading a set of one way descriptors +// and finding the nearest closest descriptor to an input feature +class CV_EXPORTS OneWayDescriptorBase +{ +public: + + // creates an instance of OneWayDescriptor from a set of training files + // - patch_size: size of the input (large) patch + // - pose_count: the number of poses to generate for each descriptor + // - train_path: path to training files + // - pca_config: the name of the file that contains PCA for small patches (2 times smaller + // than patch_size each dimension + // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size) + // - pca_desc_config: the name of the file that contains descriptors of PCA components + OneWayDescriptorBase(CvSize patch_size, int pose_count, const char* train_path = 0, const char* pca_config = 0, + const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1, + int pca_dim_high = 100, int pca_dim_low = 100); + + OneWayDescriptorBase(CvSize patch_size, int pose_count, const string &pca_filename, const string &train_path = string(), const string &images_list = string(), + float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1, + int pca_dim_high = 100, int pca_dim_low = 100); + + + virtual ~OneWayDescriptorBase(); + void clear (); + + + // Allocate: allocates memory for a given number of descriptors + void Allocate(int train_feature_count); + + // AllocatePCADescriptors: allocates memory for pca descriptors + void AllocatePCADescriptors(); + + // returns patch size + CvSize GetPatchSize() const {return m_patch_size;}; + // returns the number of poses for each descriptor + int GetPoseCount() const {return m_pose_count;}; + + // returns the number of pyramid levels + int GetPyrLevels() const {return m_pyr_levels;}; + + // returns the number of descriptors + int GetDescriptorCount() const {return m_train_feature_count;}; + + // CreateDescriptorsFromImage: creates descriptors for each of the input features + // - src: input image + // - features: input features + // - pyr_levels: the number of pyramid levels + void CreateDescriptorsFromImage(IplImage* src, const vector& features); + + // CreatePCADescriptors: generates descriptors for PCA components, needed for fast generation of feature descriptors + void CreatePCADescriptors(); + + // returns a feature descriptor by feature index + const OneWayDescriptor* GetDescriptor(int desc_idx) const {return &m_descriptors[desc_idx];}; + + // FindDescriptor: finds the closest descriptor + // - patch: input image patch + // - desc_idx: output index of the closest descriptor to the input patch + // - pose_idx: output index of the closest pose of the closest descriptor to the input patch + // - distance: distance from the input patch to the closest feature pose + // - _scales: scales of the input patch for each descriptor + // - scale_ranges: input scales variation (float[2]) + void FindDescriptor(IplImage* patch, int& desc_idx, int& pose_idx, float& distance, float* _scale = 0, float* scale_ranges = 0) const; + + // - patch: input image patch + // - n: number of the closest indexes + // - desc_idxs: output indexes of the closest descriptor to the input patch (n) + // - pose_idx: output indexes of the closest pose of the closest descriptor to the input patch (n) + // - distances: distance from the input patch to the closest feature pose (n) + // - _scales: scales of the input patch + // - scale_ranges: input scales variation (float[2]) + void FindDescriptor(IplImage* patch, int n, vector& desc_idxs, vector& pose_idxs, + vector& distances, vector& _scales, float* scale_ranges = 0) const; + + // FindDescriptor: finds the closest descriptor + // - src: input image + // - pt: center of the feature + // - desc_idx: output index of the closest descriptor to the input patch + // - pose_idx: output index of the closest pose of the closest descriptor to the input patch + // - distance: distance from the input patch to the closest feature pose + void FindDescriptor(IplImage* src, cv::Point2f pt, int& desc_idx, int& pose_idx, float& distance) const; + + // InitializePoses: generates random poses + void InitializePoses(); + + // InitializeTransformsFromPoses: generates 2x3 affine matrices from poses (initializes m_transforms) + void InitializeTransformsFromPoses(); + + // InitializePoseTransforms: subsequently calls InitializePoses and InitializeTransformsFromPoses + void InitializePoseTransforms(); + + // InitializeDescriptor: initializes a descriptor + // - desc_idx: descriptor index + // - train_image: image patch (ROI is supported) + // - feature_label: feature textual label + void InitializeDescriptor(int desc_idx, IplImage* train_image, const char* feature_label); + + void InitializeDescriptor(int desc_idx, IplImage* train_image, const KeyPoint& keypoint, const char* feature_label); + + // InitializeDescriptors: load features from an image and create descriptors for each of them + void InitializeDescriptors(IplImage* train_image, const vector& features, + const char* feature_label = "", int desc_start_idx = 0); + + // Write: writes this object to a file storage + // - fs: output filestorage + void Write (FileStorage &fs) const; + + // Read: reads OneWayDescriptorBase object from a file node + // - fn: input file node + void Read (const FileNode &fn); + + // LoadPCADescriptors: loads PCA descriptors from a file + // - filename: input filename + int LoadPCADescriptors(const char* filename); + + // LoadPCADescriptors: loads PCA descriptors from a file node + // - fn: input file node + int LoadPCADescriptors(const FileNode &fn); + + // SavePCADescriptors: saves PCA descriptors to a file + // - filename: output filename + void SavePCADescriptors(const char* filename); + + // SavePCADescriptors: saves PCA descriptors to a file storage + // - fs: output file storage + void SavePCADescriptors(CvFileStorage* fs) const; + + // GeneratePCA: calculate and save PCA components and descriptors + // - img_path: path to training PCA images directory + // - images_list: filename with filenames of training PCA images + void GeneratePCA(const char* img_path, const char* images_list, int pose_count=500); + + // SetPCAHigh: sets the high resolution pca matrices (copied to internal structures) + void SetPCAHigh(CvMat* avg, CvMat* eigenvectors); + + // SetPCALow: sets the low resolution pca matrices (copied to internal structures) + void SetPCALow(CvMat* avg, CvMat* eigenvectors); + + int GetLowPCA(CvMat** avg, CvMat** eigenvectors) + { + *avg = m_pca_avg; + *eigenvectors = m_pca_eigenvectors; + return m_pca_dim_low; + }; + + int GetPCADimLow() const {return m_pca_dim_low;}; + int GetPCADimHigh() const {return m_pca_dim_high;}; + + void ConvertDescriptorsArrayToTree(); // Converting pca_descriptors array to KD tree + + // GetPCAFilename: get default PCA filename + static string GetPCAFilename () { return "pca.yml"; } + + virtual bool empty() const { return m_train_feature_count <= 0 ? true : false; } + +protected: + CvSize m_patch_size; // patch size + int m_pose_count; // the number of poses for each descriptor + int m_train_feature_count; // the number of the training features + OneWayDescriptor* m_descriptors; // array of train feature descriptors + CvMat* m_pca_avg; // PCA average Vector for small patches + CvMat* m_pca_eigenvectors; // PCA eigenvectors for small patches + CvMat* m_pca_hr_avg; // PCA average Vector for large patches + CvMat* m_pca_hr_eigenvectors; // PCA eigenvectors for large patches + OneWayDescriptor* m_pca_descriptors; // an array of PCA descriptors + + cv::flann::Index* m_pca_descriptors_tree; + CvMat* m_pca_descriptors_matrix; + + CvAffinePose* m_poses; // array of poses + CvMat** m_transforms; // array of affine transformations corresponding to poses + + int m_pca_dim_high; + int m_pca_dim_low; + + int m_pyr_levels; + float scale_min; + float scale_max; + float scale_step; + + // SavePCAall: saves PCA components and descriptors to a file storage + // - fs: output file storage + void SavePCAall (FileStorage &fs) const; + + // LoadPCAall: loads PCA components and descriptors from a file node + // - fn: input file node + void LoadPCAall (const FileNode &fn); +}; + +class CV_EXPORTS OneWayDescriptorObject : public OneWayDescriptorBase +{ +public: + // creates an instance of OneWayDescriptorObject from a set of training files + // - patch_size: size of the input (large) patch + // - pose_count: the number of poses to generate for each descriptor + // - train_path: path to training files + // - pca_config: the name of the file that contains PCA for small patches (2 times smaller + // than patch_size each dimension + // - pca_hr_config: the name of the file that contains PCA for large patches (of patch_size size) + // - pca_desc_config: the name of the file that contains descriptors of PCA components + OneWayDescriptorObject(CvSize patch_size, int pose_count, const char* train_path, const char* pca_config, + const char* pca_hr_config = 0, const char* pca_desc_config = 0, int pyr_levels = 1); + + OneWayDescriptorObject(CvSize patch_size, int pose_count, const string &pca_filename, + const string &train_path = string (), const string &images_list = string (), + float _scale_min = 0.7f, float _scale_max=1.5f, float _scale_step=1.2f, int pyr_levels = 1); + + + virtual ~OneWayDescriptorObject(); + + // Allocate: allocates memory for a given number of features + // - train_feature_count: the total number of features + // - object_feature_count: the number of features extracted from the object + void Allocate(int train_feature_count, int object_feature_count); + + + void SetLabeledFeatures(const vector& features) {m_train_features = features;}; + vector& GetLabeledFeatures() {return m_train_features;}; + const vector& GetLabeledFeatures() const {return m_train_features;}; + vector _GetLabeledFeatures() const; + + // IsDescriptorObject: returns 1 if descriptor with specified index is positive, otherwise 0 + int IsDescriptorObject(int desc_idx) const; + + // MatchPointToPart: returns the part number of a feature if it matches one of the object parts, otherwise -1 + int MatchPointToPart(CvPoint pt) const; + + // GetDescriptorPart: returns the part number of the feature corresponding to a specified descriptor + // - desc_idx: descriptor index + int GetDescriptorPart(int desc_idx) const; + + + void InitializeObjectDescriptors(IplImage* train_image, const vector& features, + const char* feature_label, int desc_start_idx = 0, float scale = 1.0f, + int is_background = 0); + + // GetObjectFeatureCount: returns the number of object features + int GetObjectFeatureCount() const {return m_object_feature_count;}; + +protected: + int* m_part_id; // contains part id for each of object descriptors + vector m_train_features; // train features + int m_object_feature_count; // the number of the positive features + +}; + + +/* + * OneWayDescriptorMatcher + */ +class OneWayDescriptorMatcher; +typedef OneWayDescriptorMatcher OneWayDescriptorMatch; + +class CV_EXPORTS OneWayDescriptorMatcher : public GenericDescriptorMatcher +{ +public: + class CV_EXPORTS Params + { + public: + static const int POSE_COUNT = 500; + static const int PATCH_WIDTH = 24; + static const int PATCH_HEIGHT = 24; + static float GET_MIN_SCALE() { return 0.7f; } + static float GET_MAX_SCALE() { return 1.5f; } + static float GET_STEP_SCALE() { return 1.2f; } + + Params( int poseCount = POSE_COUNT, + Size patchSize = Size(PATCH_WIDTH, PATCH_HEIGHT), + string pcaFilename = string(), + string trainPath = string(), string trainImagesList = string(), + float minScale = GET_MIN_SCALE(), float maxScale = GET_MAX_SCALE(), + float stepScale = GET_STEP_SCALE() ); + + int poseCount; + Size patchSize; + string pcaFilename; + string trainPath; + string trainImagesList; + + float minScale, maxScale, stepScale; + }; + + OneWayDescriptorMatcher( const Params& params=Params() ); + virtual ~OneWayDescriptorMatcher(); + + void initialize( const Params& params, const Ptr& base=Ptr() ); + + // Clears keypoints storing in collection and OneWayDescriptorBase + virtual void clear(); + + virtual void train(); + + virtual bool isMaskSupported(); + + virtual void read( const FileNode &fn ); + virtual void write( FileStorage& fs ) const; + + virtual bool empty() const; + + virtual Ptr clone( bool emptyTrainData=false ) const; + +protected: + // Matches a set of keypoints from a single image of the training set. A rectangle with a center in a keypoint + // and size (patch_width/2*scale, patch_height/2*scale) is cropped from the source image for each + // keypoint. scale is iterated from DescriptorOneWayParams::min_scale to DescriptorOneWayParams::max_scale. + // The minimum distance to each training patch with all its affine poses is found over all scales. + // The class ID of a match is returned for each keypoint. The distance is calculated over PCA components + // loaded with DescriptorOneWay::Initialize, kd tree is used for finding minimum distances. + virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, int k, + const vector& masks, bool compactResult ); + virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, float maxDistance, + const vector& masks, bool compactResult ); + + Ptr base; + Params params; + int prevTrainCount; +}; + +/* + * FernDescriptorMatcher + */ +class FernDescriptorMatcher; +typedef FernDescriptorMatcher FernDescriptorMatch; + +class CV_EXPORTS FernDescriptorMatcher : public GenericDescriptorMatcher +{ +public: + class CV_EXPORTS Params + { + public: + Params( int nclasses=0, + int patchSize=FernClassifier::PATCH_SIZE, + int signatureSize=FernClassifier::DEFAULT_SIGNATURE_SIZE, + int nstructs=FernClassifier::DEFAULT_STRUCTS, + int structSize=FernClassifier::DEFAULT_STRUCT_SIZE, + int nviews=FernClassifier::DEFAULT_VIEWS, + int compressionMethod=FernClassifier::COMPRESSION_NONE, + const PatchGenerator& patchGenerator=PatchGenerator() ); + + Params( const string& filename ); + + int nclasses; + int patchSize; + int signatureSize; + int nstructs; + int structSize; + int nviews; + int compressionMethod; + PatchGenerator patchGenerator; + + string filename; + }; + + FernDescriptorMatcher( const Params& params=Params() ); + virtual ~FernDescriptorMatcher(); + + virtual void clear(); + + virtual void train(); + + virtual bool isMaskSupported(); + + virtual void read( const FileNode &fn ); + virtual void write( FileStorage& fs ) const; + virtual bool empty() const; + + virtual Ptr clone( bool emptyTrainData=false ) const; + +protected: + virtual void knnMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, int k, + const vector& masks, bool compactResult ); + virtual void radiusMatchImpl( const Mat& queryImage, vector& queryKeypoints, + vector >& matches, float maxDistance, + const vector& masks, bool compactResult ); + + void trainFernClassifier(); + void calcBestProbAndMatchIdx( const Mat& image, const Point2f& pt, + float& bestProb, int& bestMatchIdx, vector& signature ); + Ptr classifier; + Params params; + int prevTrainCount; +}; + + +/* + * CalonderDescriptorExtractor + */ +template +class CV_EXPORTS CalonderDescriptorExtractor : public DescriptorExtractor +{ +public: + CalonderDescriptorExtractor( const string& classifierFile ); + + virtual void read( const FileNode &fn ); + virtual void write( FileStorage &fs ) const; + + virtual int descriptorSize() const { return classifier_.classes(); } + virtual int descriptorType() const { return DataType::type; } + + virtual bool empty() const; + +protected: + virtual void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + + RTreeClassifier classifier_; + static const int BORDER_SIZE = 16; +}; + +template +CalonderDescriptorExtractor::CalonderDescriptorExtractor(const std::string& classifier_file) +{ + classifier_.read( classifier_file.c_str() ); +} + +template +void CalonderDescriptorExtractor::computeImpl( const Mat& image, + vector& keypoints, + Mat& descriptors) const +{ + // Cannot compute descriptors for keypoints on the image border. + KeyPointsFilter::runByImageBorder(keypoints, image.size(), BORDER_SIZE); + + /// @todo Check 16-byte aligned + descriptors.create((int)keypoints.size(), classifier_.classes(), cv::DataType::type); + + int patchSize = RandomizedTree::PATCH_SIZE; + int offset = patchSize / 2; + for (size_t i = 0; i < keypoints.size(); ++i) + { + cv::Point2f pt = keypoints[i].pt; + IplImage ipl = image( Rect((int)(pt.x - offset), (int)(pt.y - offset), patchSize, patchSize) ); + classifier_.getSignature( &ipl, descriptors.ptr((int)i)); + } +} + +template +void CalonderDescriptorExtractor::read( const FileNode& ) +{} + +template +void CalonderDescriptorExtractor::write( FileStorage& ) const +{} + +template +bool CalonderDescriptorExtractor::empty() const +{ + return classifier_.trees_.empty(); +} + + +////////////////////// Brute Force Matcher ////////////////////////// + +template +class CV_EXPORTS BruteForceMatcher : public BFMatcher +{ +public: + BruteForceMatcher( Distance d = Distance() ) : BFMatcher(Distance::normType, false) {(void)d;} + virtual ~BruteForceMatcher() {} +}; + + +/****************************************************************************************\ +* Planar Object Detection * +\****************************************************************************************/ + +class CV_EXPORTS PlanarObjectDetector +{ +public: + PlanarObjectDetector(); + PlanarObjectDetector(const FileNode& node); + PlanarObjectDetector(const vector& pyr, int _npoints=300, + int _patchSize=FernClassifier::PATCH_SIZE, + int _nstructs=FernClassifier::DEFAULT_STRUCTS, + int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, + int _nviews=FernClassifier::DEFAULT_VIEWS, + const LDetector& detector=LDetector(), + const PatchGenerator& patchGenerator=PatchGenerator()); + virtual ~PlanarObjectDetector(); + virtual void train(const vector& pyr, int _npoints=300, + int _patchSize=FernClassifier::PATCH_SIZE, + int _nstructs=FernClassifier::DEFAULT_STRUCTS, + int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, + int _nviews=FernClassifier::DEFAULT_VIEWS, + const LDetector& detector=LDetector(), + const PatchGenerator& patchGenerator=PatchGenerator()); + virtual void train(const vector& pyr, const vector& keypoints, + int _patchSize=FernClassifier::PATCH_SIZE, + int _nstructs=FernClassifier::DEFAULT_STRUCTS, + int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, + int _nviews=FernClassifier::DEFAULT_VIEWS, + const LDetector& detector=LDetector(), + const PatchGenerator& patchGenerator=PatchGenerator()); + Rect getModelROI() const; + vector getModelPoints() const; + const LDetector& getDetector() const; + const FernClassifier& getClassifier() const; + void setVerbose(bool verbose); + + void read(const FileNode& node); + void write(FileStorage& fs, const String& name=String()) const; + bool operator()(const Mat& image, CV_OUT Mat& H, CV_OUT vector& corners) const; + bool operator()(const vector& pyr, const vector& keypoints, + CV_OUT Mat& H, CV_OUT vector& corners, + CV_OUT vector* pairs=0) const; + +protected: + bool verbose; + Rect modelROI; + vector modelPoints; + LDetector ldetector; + FernClassifier fernClassifier; +}; + +} + +// 2009-01-12, Xavier Delacour + +struct lsh_hash { + int h1, h2; +}; + +struct CvLSHOperations +{ + virtual ~CvLSHOperations() {} + + virtual int vector_add(const void* data) = 0; + virtual void vector_remove(int i) = 0; + virtual const void* vector_lookup(int i) = 0; + virtual void vector_reserve(int n) = 0; + virtual unsigned int vector_count() = 0; + + virtual void hash_insert(lsh_hash h, int l, int i) = 0; + virtual void hash_remove(lsh_hash h, int l, int i) = 0; + virtual int hash_lookup(lsh_hash h, int l, int* ret_i, int ret_i_max) = 0; +}; + +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Splits color or grayscale image into multiple connected components + of nearly the same color/brightness using modification of Burt algorithm. + comp with contain a pointer to sequence (CvSeq) + of connected components (CvConnectedComp) */ +CVAPI(void) cvPyrSegmentation( IplImage* src, IplImage* dst, + CvMemStorage* storage, CvSeq** comp, + int level, double threshold1, + double threshold2 ); + +/****************************************************************************************\ +* Planar subdivisions * +\****************************************************************************************/ + +/* Initializes Delaunay triangulation */ +CVAPI(void) cvInitSubdivDelaunay2D( CvSubdiv2D* subdiv, CvRect rect ); + +/* Creates new subdivision */ +CVAPI(CvSubdiv2D*) cvCreateSubdiv2D( int subdiv_type, int header_size, + int vtx_size, int quadedge_size, + CvMemStorage* storage ); + +/************************* high-level subdivision functions ***************************/ + +/* Simplified Delaunay diagram creation */ +CV_INLINE CvSubdiv2D* cvCreateSubdivDelaunay2D( CvRect rect, CvMemStorage* storage ) +{ + CvSubdiv2D* subdiv = cvCreateSubdiv2D( CV_SEQ_KIND_SUBDIV2D, sizeof(*subdiv), + sizeof(CvSubdiv2DPoint), sizeof(CvQuadEdge2D), storage ); + + cvInitSubdivDelaunay2D( subdiv, rect ); + return subdiv; +} + + +/* Inserts new point to the Delaunay triangulation */ +CVAPI(CvSubdiv2DPoint*) cvSubdivDelaunay2DInsert( CvSubdiv2D* subdiv, CvPoint2D32f pt); + +/* Locates a point within the Delaunay triangulation (finds the edge + the point is left to or belongs to, or the triangulation point the given + point coinsides with */ +CVAPI(CvSubdiv2DPointLocation) cvSubdiv2DLocate( + CvSubdiv2D* subdiv, CvPoint2D32f pt, + CvSubdiv2DEdge* edge, + CvSubdiv2DPoint** vertex CV_DEFAULT(NULL) ); + +/* Calculates Voronoi tesselation (i.e. coordinates of Voronoi points) */ +CVAPI(void) cvCalcSubdivVoronoi2D( CvSubdiv2D* subdiv ); + + +/* Removes all Voronoi points from the tesselation */ +CVAPI(void) cvClearSubdivVoronoi2D( CvSubdiv2D* subdiv ); + + +/* Finds the nearest to the given point vertex in subdivision. */ +CVAPI(CvSubdiv2DPoint*) cvFindNearestPoint2D( CvSubdiv2D* subdiv, CvPoint2D32f pt ); + + +/************ Basic quad-edge navigation and operations ************/ + +CV_INLINE CvSubdiv2DEdge cvSubdiv2DNextEdge( CvSubdiv2DEdge edge ) +{ + return CV_SUBDIV2D_NEXT_EDGE(edge); +} + + +CV_INLINE CvSubdiv2DEdge cvSubdiv2DRotateEdge( CvSubdiv2DEdge edge, int rotate ) +{ + return (edge & ~3) + ((edge + rotate) & 3); +} + +CV_INLINE CvSubdiv2DEdge cvSubdiv2DSymEdge( CvSubdiv2DEdge edge ) +{ + return edge ^ 2; +} + +CV_INLINE CvSubdiv2DEdge cvSubdiv2DGetEdge( CvSubdiv2DEdge edge, CvNextEdgeType type ) +{ + CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); + edge = e->next[(edge + (int)type) & 3]; + return (edge & ~3) + ((edge + ((int)type >> 4)) & 3); +} + + +CV_INLINE CvSubdiv2DPoint* cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge ) +{ + CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); + return (CvSubdiv2DPoint*)e->pt[edge & 3]; +} + + +CV_INLINE CvSubdiv2DPoint* cvSubdiv2DEdgeDst( CvSubdiv2DEdge edge ) +{ + CvQuadEdge2D* e = (CvQuadEdge2D*)(edge & ~3); + return (CvSubdiv2DPoint*)e->pt[(edge + 2) & 3]; +} + +/****************************************************************************************\ +* Additional operations on Subdivisions * +\****************************************************************************************/ + +// paints voronoi diagram: just demo function +CVAPI(void) icvDrawMosaic( CvSubdiv2D* subdiv, IplImage* src, IplImage* dst ); + +// checks planar subdivision for correctness. It is not an absolute check, +// but it verifies some relations between quad-edges +CVAPI(int) icvSubdiv2DCheck( CvSubdiv2D* subdiv ); + +// returns squared distance between two 2D points with floating-point coordinates. +CV_INLINE double icvSqDist2D32f( CvPoint2D32f pt1, CvPoint2D32f pt2 ) +{ + double dx = pt1.x - pt2.x; + double dy = pt1.y - pt2.y; + + return dx*dx + dy*dy; +} + + + + +CV_INLINE double cvTriangleArea( CvPoint2D32f a, CvPoint2D32f b, CvPoint2D32f c ) +{ + return ((double)b.x - a.x) * ((double)c.y - a.y) - ((double)b.y - a.y) * ((double)c.x - a.x); +} + + +/* Constructs kd-tree from set of feature descriptors */ +CVAPI(struct CvFeatureTree*) cvCreateKDTree(CvMat* desc); + +/* Constructs spill-tree from set of feature descriptors */ +CVAPI(struct CvFeatureTree*) cvCreateSpillTree( const CvMat* raw_data, + const int naive CV_DEFAULT(50), + const double rho CV_DEFAULT(.7), + const double tau CV_DEFAULT(.1) ); + +/* Release feature tree */ +CVAPI(void) cvReleaseFeatureTree(struct CvFeatureTree* tr); + +/* Searches feature tree for k nearest neighbors of given reference points, + searching (in case of kd-tree/bbf) at most emax leaves. */ +CVAPI(void) cvFindFeatures(struct CvFeatureTree* tr, const CvMat* query_points, + CvMat* indices, CvMat* dist, int k, int emax CV_DEFAULT(20)); + +/* Search feature tree for all points that are inlier to given rect region. + Only implemented for kd trees */ +CVAPI(int) cvFindFeaturesBoxed(struct CvFeatureTree* tr, + CvMat* bounds_min, CvMat* bounds_max, + CvMat* out_indices); + + +/* Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of + given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. */ +CVAPI(struct CvLSH*) cvCreateLSH(struct CvLSHOperations* ops, int d, + int L CV_DEFAULT(10), int k CV_DEFAULT(10), + int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4), + int64 seed CV_DEFAULT(-1)); + +/* Construct in-memory LSH table, with n bins. */ +CVAPI(struct CvLSH*) cvCreateMemoryLSH(int d, int n, int L CV_DEFAULT(10), int k CV_DEFAULT(10), + int type CV_DEFAULT(CV_64FC1), double r CV_DEFAULT(4), + int64 seed CV_DEFAULT(-1)); + +/* Free the given LSH structure. */ +CVAPI(void) cvReleaseLSH(struct CvLSH** lsh); + +/* Return the number of vectors in the LSH. */ +CVAPI(unsigned int) LSHSize(struct CvLSH* lsh); + +/* Add vectors to the LSH structure, optionally returning indices. */ +CVAPI(void) cvLSHAdd(struct CvLSH* lsh, const CvMat* data, CvMat* indices CV_DEFAULT(0)); + +/* Remove vectors from LSH, as addressed by given indices. */ +CVAPI(void) cvLSHRemove(struct CvLSH* lsh, const CvMat* indices); + +/* Query the LSH n times for at most k nearest points; data is n x d, + indices and dist are n x k. At most emax stored points will be accessed. */ +CVAPI(void) cvLSHQuery(struct CvLSH* lsh, const CvMat* query_points, + CvMat* indices, CvMat* dist, int k, int emax); + +/* Kolmogorov-Zabin stereo-correspondence algorithm (a.k.a. KZ1) */ +#define CV_STEREO_GC_OCCLUDED SHRT_MAX + +typedef struct CvStereoGCState +{ + int Ithreshold; + int interactionRadius; + float K, lambda, lambda1, lambda2; + int occlusionCost; + int minDisparity; + int numberOfDisparities; + int maxIters; + + CvMat* left; + CvMat* right; + CvMat* dispLeft; + CvMat* dispRight; + CvMat* ptrLeft; + CvMat* ptrRight; + CvMat* vtxBuf; + CvMat* edgeBuf; +} CvStereoGCState; + +CVAPI(CvStereoGCState*) cvCreateStereoGCState( int numberOfDisparities, int maxIters ); +CVAPI(void) cvReleaseStereoGCState( CvStereoGCState** state ); + +CVAPI(void) cvFindStereoCorrespondenceGC( const CvArr* left, const CvArr* right, + CvArr* disparityLeft, CvArr* disparityRight, + CvStereoGCState* state, + int useDisparityGuess CV_DEFAULT(0) ); + +/* Calculates optical flow for 2 images using classical Lucas & Kanade algorithm */ +CVAPI(void) cvCalcOpticalFlowLK( const CvArr* prev, const CvArr* curr, + CvSize win_size, CvArr* velx, CvArr* vely ); + +/* Calculates optical flow for 2 images using block matching algorithm */ +CVAPI(void) cvCalcOpticalFlowBM( const CvArr* prev, const CvArr* curr, + CvSize block_size, CvSize shift_size, + CvSize max_range, int use_previous, + CvArr* velx, CvArr* vely ); + +/* Calculates Optical flow for 2 images using Horn & Schunck algorithm */ +CVAPI(void) cvCalcOpticalFlowHS( const CvArr* prev, const CvArr* curr, + int use_previous, CvArr* velx, CvArr* vely, + double lambda, CvTermCriteria criteria ); + + +/****************************************************************************************\ +* Background/foreground segmentation * +\****************************************************************************************/ + +/* We discriminate between foreground and background pixels + * by building and maintaining a model of the background. + * Any pixel which does not fit this model is then deemed + * to be foreground. + * + * At present we support two core background models, + * one of which has two variations: + * + * o CV_BG_MODEL_FGD: latest and greatest algorithm, described in + * + * Foreground Object Detection from Videos Containing Complex Background. + * Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian. + * ACM MM2003 9p + * + * o CV_BG_MODEL_FGD_SIMPLE: + * A code comment describes this as a simplified version of the above, + * but the code is in fact currently identical + * + * o CV_BG_MODEL_MOG: "Mixture of Gaussians", older algorithm, described in + * + * Moving target classification and tracking from real-time video. + * A Lipton, H Fujijoshi, R Patil + * Proceedings IEEE Workshop on Application of Computer Vision pp 8-14 1998 + * + * Learning patterns of activity using real-time tracking + * C Stauffer and W Grimson August 2000 + * IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8):747-757 + */ + + +#define CV_BG_MODEL_FGD 0 +#define CV_BG_MODEL_MOG 1 /* "Mixture of Gaussians". */ +#define CV_BG_MODEL_FGD_SIMPLE 2 + +struct CvBGStatModel; + +typedef void (CV_CDECL * CvReleaseBGStatModel)( struct CvBGStatModel** bg_model ); +typedef int (CV_CDECL * CvUpdateBGStatModel)( IplImage* curr_frame, struct CvBGStatModel* bg_model, + double learningRate ); + +#define CV_BG_STAT_MODEL_FIELDS() \ +int type; /*type of BG model*/ \ +CvReleaseBGStatModel release; \ +CvUpdateBGStatModel update; \ +IplImage* background; /*8UC3 reference background image*/ \ +IplImage* foreground; /*8UC1 foreground image*/ \ +IplImage** layers; /*8UC3 reference background image, can be null */ \ +int layer_count; /* can be zero */ \ +CvMemStorage* storage; /*storage for foreground_regions*/ \ +CvSeq* foreground_regions /*foreground object contours*/ + +typedef struct CvBGStatModel +{ + CV_BG_STAT_MODEL_FIELDS(); +} CvBGStatModel; + +// + +// Releases memory used by BGStatModel +CVAPI(void) cvReleaseBGStatModel( CvBGStatModel** bg_model ); + +// Updates statistical model and returns number of found foreground regions +CVAPI(int) cvUpdateBGStatModel( IplImage* current_frame, CvBGStatModel* bg_model, + double learningRate CV_DEFAULT(-1)); + +// Performs FG post-processing using segmentation +// (all pixels of a region will be classified as foreground if majority of pixels of the region are FG). +// parameters: +// segments - pointer to result of segmentation (for example MeanShiftSegmentation) +// bg_model - pointer to CvBGStatModel structure +CVAPI(void) cvRefineForegroundMaskBySegm( CvSeq* segments, CvBGStatModel* bg_model ); + +/* Common use change detection function */ +CVAPI(int) cvChangeDetection( IplImage* prev_frame, + IplImage* curr_frame, + IplImage* change_mask ); + +/* + Interface of ACM MM2003 algorithm + */ + +/* Default parameters of foreground detection algorithm: */ +#define CV_BGFG_FGD_LC 128 +#define CV_BGFG_FGD_N1C 15 +#define CV_BGFG_FGD_N2C 25 + +#define CV_BGFG_FGD_LCC 64 +#define CV_BGFG_FGD_N1CC 25 +#define CV_BGFG_FGD_N2CC 40 + +/* Background reference image update parameter: */ +#define CV_BGFG_FGD_ALPHA_1 0.1f + +/* stat model update parameter + * 0.002f ~ 1K frame(~45sec), 0.005 ~ 18sec (if 25fps and absolutely static BG) + */ +#define CV_BGFG_FGD_ALPHA_2 0.005f + +/* start value for alpha parameter (to fast initiate statistic model) */ +#define CV_BGFG_FGD_ALPHA_3 0.1f + +#define CV_BGFG_FGD_DELTA 2 + +#define CV_BGFG_FGD_T 0.9f + +#define CV_BGFG_FGD_MINAREA 15.f + +#define CV_BGFG_FGD_BG_UPDATE_TRESH 0.5f + +/* See the above-referenced Li/Huang/Gu/Tian paper + * for a full description of these background-model + * tuning parameters. + * + * Nomenclature: 'c' == "color", a three-component red/green/blue vector. + * We use histograms of these to model the range of + * colors we've seen at a given background pixel. + * + * 'cc' == "color co-occurrence", a six-component vector giving + * RGB color for both this frame and preceding frame. + * We use histograms of these to model the range of + * color CHANGES we've seen at a given background pixel. + */ +typedef struct CvFGDStatModelParams +{ + int Lc; /* Quantized levels per 'color' component. Power of two, typically 32, 64 or 128. */ + int N1c; /* Number of color vectors used to model normal background color variation at a given pixel. */ + int N2c; /* Number of color vectors retained at given pixel. Must be > N1c, typically ~ 5/3 of N1c. */ + /* Used to allow the first N1c vectors to adapt over time to changing background. */ + + int Lcc; /* Quantized levels per 'color co-occurrence' component. Power of two, typically 16, 32 or 64. */ + int N1cc; /* Number of color co-occurrence vectors used to model normal background color variation at a given pixel. */ + int N2cc; /* Number of color co-occurrence vectors retained at given pixel. Must be > N1cc, typically ~ 5/3 of N1cc. */ + /* Used to allow the first N1cc vectors to adapt over time to changing background. */ + + int is_obj_without_holes;/* If TRUE we ignore holes within foreground blobs. Defaults to TRUE. */ + int perform_morphing; /* Number of erode-dilate-erode foreground-blob cleanup iterations. */ + /* These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1. */ + + float alpha1; /* How quickly we forget old background pixel values seen. Typically set to 0.1 */ + float alpha2; /* "Controls speed of feature learning". Depends on T. Typical value circa 0.005. */ + float alpha3; /* Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1. */ + + float delta; /* Affects color and color co-occurrence quantization, typically set to 2. */ + float T; /* "A percentage value which determines when new features can be recognized as new background." (Typically 0.9).*/ + float minArea; /* Discard foreground blobs whose bounding box is smaller than this threshold. */ +} CvFGDStatModelParams; + +typedef struct CvBGPixelCStatTable +{ + float Pv, Pvb; + uchar v[3]; +} CvBGPixelCStatTable; + +typedef struct CvBGPixelCCStatTable +{ + float Pv, Pvb; + uchar v[6]; +} CvBGPixelCCStatTable; + +typedef struct CvBGPixelStat +{ + float Pbc; + float Pbcc; + CvBGPixelCStatTable* ctable; + CvBGPixelCCStatTable* cctable; + uchar is_trained_st_model; + uchar is_trained_dyn_model; +} CvBGPixelStat; + + +typedef struct CvFGDStatModel +{ + CV_BG_STAT_MODEL_FIELDS(); + CvBGPixelStat* pixel_stat; + IplImage* Ftd; + IplImage* Fbd; + IplImage* prev_frame; + CvFGDStatModelParams params; +} CvFGDStatModel; + +/* Creates FGD model */ +CVAPI(CvBGStatModel*) cvCreateFGDStatModel( IplImage* first_frame, + CvFGDStatModelParams* parameters CV_DEFAULT(NULL)); + +/* + Interface of Gaussian mixture algorithm + + "An improved adaptive background mixture model for real-time tracking with shadow detection" + P. KadewTraKuPong and R. Bowden, + Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001." + http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf + */ + +/* Note: "MOG" == "Mixture Of Gaussians": */ + +#define CV_BGFG_MOG_MAX_NGAUSSIANS 500 + +/* default parameters of gaussian background detection algorithm */ +#define CV_BGFG_MOG_BACKGROUND_THRESHOLD 0.7 /* threshold sum of weights for background test */ +#define CV_BGFG_MOG_STD_THRESHOLD 2.5 /* lambda=2.5 is 99% */ +#define CV_BGFG_MOG_WINDOW_SIZE 200 /* Learning rate; alpha = 1/CV_GBG_WINDOW_SIZE */ +#define CV_BGFG_MOG_NGAUSSIANS 5 /* = K = number of Gaussians in mixture */ +#define CV_BGFG_MOG_WEIGHT_INIT 0.05 +#define CV_BGFG_MOG_SIGMA_INIT 30 +#define CV_BGFG_MOG_MINAREA 15.f + + +#define CV_BGFG_MOG_NCOLORS 3 + +typedef struct CvGaussBGStatModelParams +{ + int win_size; /* = 1/alpha */ + int n_gauss; + double bg_threshold, std_threshold, minArea; + double weight_init, variance_init; +}CvGaussBGStatModelParams; + +typedef struct CvGaussBGValues +{ + int match_sum; + double weight; + double variance[CV_BGFG_MOG_NCOLORS]; + double mean[CV_BGFG_MOG_NCOLORS]; +} CvGaussBGValues; + +typedef struct CvGaussBGPoint +{ + CvGaussBGValues* g_values; +} CvGaussBGPoint; + + +typedef struct CvGaussBGModel +{ + CV_BG_STAT_MODEL_FIELDS(); + CvGaussBGStatModelParams params; + CvGaussBGPoint* g_point; + int countFrames; + void* mog; +} CvGaussBGModel; + + +/* Creates Gaussian mixture background model */ +CVAPI(CvBGStatModel*) cvCreateGaussianBGModel( IplImage* first_frame, + CvGaussBGStatModelParams* parameters CV_DEFAULT(NULL)); + + +typedef struct CvBGCodeBookElem +{ + struct CvBGCodeBookElem* next; + int tLastUpdate; + int stale; + uchar boxMin[3]; + uchar boxMax[3]; + uchar learnMin[3]; + uchar learnMax[3]; +} CvBGCodeBookElem; + +typedef struct CvBGCodeBookModel +{ + CvSize size; + int t; + uchar cbBounds[3]; + uchar modMin[3]; + uchar modMax[3]; + CvBGCodeBookElem** cbmap; + CvMemStorage* storage; + CvBGCodeBookElem* freeList; +} CvBGCodeBookModel; + +CVAPI(CvBGCodeBookModel*) cvCreateBGCodeBookModel( void ); +CVAPI(void) cvReleaseBGCodeBookModel( CvBGCodeBookModel** model ); + +CVAPI(void) cvBGCodeBookUpdate( CvBGCodeBookModel* model, const CvArr* image, + CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), + const CvArr* mask CV_DEFAULT(0) ); + +CVAPI(int) cvBGCodeBookDiff( const CvBGCodeBookModel* model, const CvArr* image, + CvArr* fgmask, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)) ); + +CVAPI(void) cvBGCodeBookClearStale( CvBGCodeBookModel* model, int staleThresh, + CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), + const CvArr* mask CV_DEFAULT(0) ); + +CVAPI(CvSeq*) cvSegmentFGMask( CvArr *fgmask, int poly1Hull0 CV_DEFAULT(1), + float perimScale CV_DEFAULT(4.f), + CvMemStorage* storage CV_DEFAULT(0), + CvPoint offset CV_DEFAULT(cvPoint(0,0))); + +#ifdef __cplusplus +} +#endif + +#endif + +/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/streams.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/streams.hpp old mode 100755 new mode 100644 similarity index 98% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/streams.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/streams.hpp index 24d83a4..6935b00 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/legacy/streams.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/legacy/streams.hpp @@ -63,7 +63,7 @@ and DirectX SDK (2006 April or later). See \samples\multimedia\directshow\readme.txt. 4. Copy the built libraries (called strmbase.lib and strmbasd.lib - in Release and Debug versions, respectively) to + in Release and Debug versions, respectively) to \lib. 5. In Developer Studio add the following paths: @@ -81,7 +81,7 @@ and DirectX SDK (2006 April or later). NOTE: PUT THE ADDED LINES ON THE VERY TOP OF THE LISTS, OTHERWISE YOU MAY STILL GET COMPILER OR LINKER ERRORS. This is necessary, because Visual Studio - may include older versions of the same headers and libraries. + may include older versions of the same headers and libraries. 6. Now you can build OpenCV DirectShow filters. diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ml/ml.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/ml/ml.hpp old mode 100755 new mode 100644 similarity index 92% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ml/ml.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/ml/ml.hpp index 867da61..3204760 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/ml/ml.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/ml/ml.hpp @@ -46,6 +46,10 @@ #ifdef __cplusplus +#include +#include +#include + // Apple defines a check() macro somewhere in the debug headers // that interferes with a method definiton in this header #undef check @@ -121,6 +125,7 @@ CV_INLINE CvParamLattice cvDefaultParamLattice( void ) #define CV_TYPE_NAME_ML_ANN_MLP "opencv-ml-ann-mlp" #define CV_TYPE_NAME_ML_CNN "opencv-ml-cnn" #define CV_TYPE_NAME_ML_RTREES "opencv-ml-random-trees" +#define CV_TYPE_NAME_ML_ERTREES "opencv-ml-extremely-randomized-trees" #define CV_TYPE_NAME_ML_GBT "opencv-ml-gradient-boosting-trees" #define CV_TRAIN_ERROR 0 @@ -165,12 +170,7 @@ struct CV_EXPORTS_W_MAP CvParamGrid min_val = max_val = step = 0; } - CvParamGrid( double _min_val, double _max_val, double log_step ) - { - min_val = _min_val; - max_val = _max_val; - step = log_step; - } + CvParamGrid( double min_val, double max_val, double log_step ); //CvParamGrid( int param_id ); bool check() const; @@ -179,6 +179,13 @@ struct CV_EXPORTS_W_MAP CvParamGrid CV_PROP_RW double step; }; +inline CvParamGrid::CvParamGrid( double _min_val, double _max_val, double _log_step ) +{ + min_val = _min_val; + max_val = _max_val; + step = _log_step; +} + class CV_EXPORTS_W CvNormalBayesClassifier : public CvStatModel { public: @@ -187,22 +194,20 @@ class CV_EXPORTS_W CvNormalBayesClassifier : public CvStatModel CvNormalBayesClassifier( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0 ); - + virtual bool train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx = 0, const CvMat* sampleIdx=0, bool update=false ); - + virtual float predict( const CvMat* samples, CV_OUT CvMat* results=0 ) const; CV_WRAP virtual void clear(); -#ifndef SWIG CV_WRAP CvNormalBayesClassifier( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat() ); CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx = cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), bool update=false ); CV_WRAP virtual float predict( const cv::Mat& samples, CV_OUT cv::Mat* results=0 ) const; -#endif - + virtual void write( CvFileStorage* storage, const char* name ) const; virtual void read( CvFileStorage* storage, CvFileNode* node ); @@ -238,31 +243,29 @@ class CV_EXPORTS_W CvKNearest : public CvStatModel virtual bool train( const CvMat* trainData, const CvMat* responses, const CvMat* sampleIdx=0, bool is_regression=false, int maxK=32, bool updateBase=false ); - + virtual float find_nearest( const CvMat* samples, int k, CV_OUT CvMat* results=0, const float** neighbors=0, CV_OUT CvMat* neighborResponses=0, CV_OUT CvMat* dist=0 ) const; - -#ifndef SWIG + CV_WRAP CvKNearest( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& sampleIdx=cv::Mat(), bool isRegression=false, int max_k=32 ); - + CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& sampleIdx=cv::Mat(), bool isRegression=false, - int maxK=32, bool updateBase=false ); - + int maxK=32, bool updateBase=false ); + virtual float find_nearest( const cv::Mat& samples, int k, cv::Mat* results=0, const float** neighbors=0, cv::Mat* neighborResponses=0, cv::Mat* dist=0 ) const; CV_WRAP virtual float find_nearest( const cv::Mat& samples, int k, CV_OUT cv::Mat& results, CV_OUT cv::Mat& neighborResponses, CV_OUT cv::Mat& dists) const; -#endif - + virtual void clear(); int get_max_k() const; int get_var_count() const; int get_sample_count() const; bool is_regression() const; - + virtual float write_results( int k, int k1, int start, int end, const float* neighbor_responses, const float* dist, CvMat* _results, CvMat* _neighbor_responses, CvMat* _dist, Cv32suf* sort_buf ) const; @@ -286,10 +289,10 @@ class CV_EXPORTS_W CvKNearest : public CvStatModel struct CV_EXPORTS_W_MAP CvSVMParams { CvSVMParams(); - CvSVMParams( int _svm_type, int _kernel_type, - double _degree, double _gamma, double _coef0, - double Cvalue, double _nu, double _p, - CvMat* _class_weights, CvTermCriteria _term_crit ); + CvSVMParams( int svm_type, int kernel_type, + double degree, double gamma, double coef0, + double Cvalue, double nu, double p, + CvMat* class_weights, CvTermCriteria term_crit ); CV_PROP_RW int svm_type; CV_PROP_RW int kernel_type; @@ -468,7 +471,7 @@ class CV_EXPORTS_W CvSVM : public CvStatModel virtual bool train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, CvSVMParams params=CvSVMParams() ); - + virtual bool train_auto( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx, const CvMat* sampleIdx, CvSVMParams params, int kfold = 10, @@ -481,17 +484,16 @@ class CV_EXPORTS_W CvSVM : public CvStatModel bool balanced=false ); virtual float predict( const CvMat* sample, bool returnDFVal=false ) const; - virtual float predict( const CvMat* samples, CvMat* results ) const; - -#ifndef SWIG + virtual float predict( const CvMat* samples, CV_OUT CvMat* results ) const; + CV_WRAP CvSVM( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), CvSVMParams params=CvSVMParams() ); - + CV_WRAP virtual bool train( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), CvSVMParams params=CvSVMParams() ); - + CV_WRAP virtual bool train_auto( const cv::Mat& trainData, const cv::Mat& responses, const cv::Mat& varIdx, const cv::Mat& sampleIdx, CvSVMParams params, int k_fold = 10, @@ -503,8 +505,8 @@ class CV_EXPORTS_W CvSVM : public CvStatModel CvParamGrid degreeGrid = CvSVM::get_default_grid(CvSVM::DEGREE), bool balanced=false); CV_WRAP virtual float predict( const cv::Mat& sample, bool returnDFVal=false ) const; -#endif - + CV_WRAP_AS(predict_all) void predict( cv::InputArray samples, cv::OutputArray results ) const; + CV_WRAP virtual int get_support_vector_count() const; virtual const float* get_support_vector(int i) const; virtual CvSVMParams get_params() const { return params; }; @@ -549,114 +551,96 @@ class CV_EXPORTS_W CvSVM : public CvStatModel /****************************************************************************************\ * Expectation - Maximization * \****************************************************************************************/ - -struct CV_EXPORTS_W_MAP CvEMParams +namespace cv { - CvEMParams(); - CvEMParams( int nclusters, int cov_mat_type=1/*CvEM::COV_MAT_DIAGONAL*/, - int start_step=0/*CvEM::START_AUTO_STEP*/, - CvTermCriteria term_crit=cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON), - const CvMat* probs=0, const CvMat* weights=0, const CvMat* means=0, const CvMat** covs=0 ); - - CV_PROP_RW int nclusters; - CV_PROP_RW int cov_mat_type; - CV_PROP_RW int start_step; - const CvMat* probs; - const CvMat* weights; - const CvMat* means; - const CvMat** covs; - CV_PROP_RW CvTermCriteria term_crit; -}; - - -class CV_EXPORTS_W CvEM : public CvStatModel +class CV_EXPORTS_W EM : public Algorithm { public: // Type of covariation matrices - enum { COV_MAT_SPHERICAL=0, COV_MAT_DIAGONAL=1, COV_MAT_GENERIC=2 }; + enum {COV_MAT_SPHERICAL=0, COV_MAT_DIAGONAL=1, COV_MAT_GENERIC=2, COV_MAT_DEFAULT=COV_MAT_DIAGONAL}; + + // Default parameters + enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; // The initial step - enum { START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0 }; - - CV_WRAP CvEM(); - CvEM( const CvMat* samples, const CvMat* sampleIdx=0, - CvEMParams params=CvEMParams(), CvMat* labels=0 ); - //CvEM (CvEMParams params, CvMat * means, CvMat ** covs, CvMat * weights, - // CvMat * probs, CvMat * log_weight_div_det, CvMat * inv_eigen_values, CvMat** cov_rotate_mats); - - virtual ~CvEM(); - - virtual bool train( const CvMat* samples, const CvMat* sampleIdx=0, - CvEMParams params=CvEMParams(), CvMat* labels=0 ); - - virtual float predict( const CvMat* sample, CV_OUT CvMat* probs ) const; - -#ifndef SWIG - CV_WRAP CvEM( const cv::Mat& samples, const cv::Mat& sampleIdx=cv::Mat(), - CvEMParams params=CvEMParams() ); - - CV_WRAP virtual bool train( const cv::Mat& samples, - const cv::Mat& sampleIdx=cv::Mat(), - CvEMParams params=CvEMParams(), - CV_OUT cv::Mat* labels=0 ); - - CV_WRAP virtual float predict( const cv::Mat& sample, CV_OUT cv::Mat* probs=0 ) const; - CV_WRAP virtual double calcLikelihood( const cv::Mat &sample ) const; - - CV_WRAP int getNClusters() const; - CV_WRAP cv::Mat getMeans() const; - CV_WRAP void getCovs(CV_OUT std::vector& covs) const; - CV_WRAP cv::Mat getWeights() const; - CV_WRAP cv::Mat getProbs() const; - - CV_WRAP inline double getLikelihood() const { return log_likelihood; } - CV_WRAP inline double getLikelihoodDelta() const { return log_likelihood_delta; } -#endif - + enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; + + CV_WRAP EM(int nclusters=EM::DEFAULT_NCLUSTERS, int covMatType=EM::COV_MAT_DIAGONAL, + const TermCriteria& termCrit=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, + EM::DEFAULT_MAX_ITERS, FLT_EPSILON)); + + virtual ~EM(); CV_WRAP virtual void clear(); - int get_nclusters() const; - const CvMat* get_means() const; - const CvMat** get_covs() const; - const CvMat* get_weights() const; - const CvMat* get_probs() const; + CV_WRAP virtual bool train(InputArray samples, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()); - inline double get_log_likelihood() const { return log_likelihood; } - inline double get_log_likelihood_delta() const { return log_likelihood_delta; } - -// inline const CvMat * get_log_weight_div_det () const { return log_weight_div_det; }; -// inline const CvMat * get_inv_eigen_values () const { return inv_eigen_values; }; -// inline const CvMat ** get_cov_rotate_mats () const { return cov_rotate_mats; }; + CV_WRAP virtual bool trainE(InputArray samples, + InputArray means0, + InputArray covs0=noArray(), + InputArray weights0=noArray(), + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()); - virtual void read( CvFileStorage* fs, CvFileNode* node ); - virtual void write( CvFileStorage* fs, const char* name ) const; + CV_WRAP virtual bool trainM(InputArray samples, + InputArray probs0, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()); - virtual void write_params( CvFileStorage* fs ) const; - virtual void read_params( CvFileStorage* fs, CvFileNode* node ); + CV_WRAP Vec2d predict(InputArray sample, + OutputArray probs=noArray()) const; + + CV_WRAP bool isTrained() const; + + AlgorithmInfo* info() const; + virtual void read(const FileNode& fn); protected: - virtual void set_params( const CvEMParams& params, - const CvVectors& train_data ); - virtual void init_em( const CvVectors& train_data ); - virtual double run_em( const CvVectors& train_data ); - virtual void init_auto( const CvVectors& samples ); - virtual void kmeans( const CvVectors& train_data, int nclusters, - CvMat* labels, CvTermCriteria criteria, - const CvMat* means ); - CvEMParams params; - double log_likelihood; - double log_likelihood_delta; - - CvMat* means; - CvMat** covs; - CvMat* weights; - CvMat* probs; + virtual void setTrainData(int startStep, const Mat& samples, + const Mat* probs0, + const Mat* means0, + const vector* covs0, + const Mat* weights0); - CvMat* log_weight_div_det; - CvMat* inv_eigen_values; - CvMat** cov_rotate_mats; + bool doTrain(int startStep, + OutputArray logLikelihoods, + OutputArray labels, + OutputArray probs); + virtual void eStep(); + virtual void mStep(); + + void clusterTrainSamples(); + void decomposeCovs(); + void computeLogWeightDivDet(); + + Vec2d computeProbabilities(const Mat& sample, Mat* probs) const; + + // all inner matrices have type CV_64FC1 + CV_PROP_RW int nclusters; + CV_PROP_RW int covMatType; + CV_PROP_RW int maxIters; + CV_PROP_RW double epsilon; + + Mat trainSamples; + Mat trainProbs; + Mat trainLogLikelihoods; + Mat trainLabels; + + CV_PROP Mat weights; + CV_PROP Mat means; + CV_PROP vector covs; + + vector covsEigenValues; + vector covsRotateMats; + vector invCovsEigenValues; + Mat logWeightDivDet; }; +} // namespace cv /****************************************************************************************\ * Decision Tree * @@ -815,7 +799,7 @@ struct CV_EXPORTS CvDTreeTrainData int buf_count, buf_size; bool shared; int is_buf_16u; - + CvMat* cat_count; CvMat* cat_ofs; CvMat* cat_map; @@ -878,18 +862,16 @@ class CV_EXPORTS_W CvDTree : public CvStatModel virtual CvDTreeNode* predict( const CvMat* sample, const CvMat* missingDataMask=0, bool preprocessedInput=false ) const; -#ifndef SWIG CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat(), CvDTreeParams params=CvDTreeParams() ); - + CV_WRAP virtual CvDTreeNode* predict( const cv::Mat& sample, const cv::Mat& missingDataMask=cv::Mat(), bool preprocessedInput=false ) const; CV_WRAP virtual cv::Mat getVarImportance(); -#endif - + virtual const CvMat* get_var_importance(); CV_WRAP virtual void clear(); @@ -913,13 +895,13 @@ class CV_EXPORTS_W CvDTree : public CvStatModel virtual void try_split_node( CvDTreeNode* n ); virtual void split_node_data( CvDTreeNode* n ); virtual CvDTreeSplit* find_best_split( CvDTreeNode* n ); - virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi, uchar* ext_buf = 0 ); @@ -1016,12 +998,11 @@ class CV_EXPORTS_W CvRTrees : public CvStatModel const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvRTParams params=CvRTParams() ); - + virtual bool train( CvMLData* data, CvRTParams params=CvRTParams() ); virtual float predict( const CvMat* sample, const CvMat* missing = 0 ) const; virtual float predict_prob( const CvMat* sample, const CvMat* missing = 0 ) const; -#ifndef SWIG CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), @@ -1030,17 +1011,16 @@ class CV_EXPORTS_W CvRTrees : public CvStatModel CV_WRAP virtual float predict( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const; CV_WRAP virtual float predict_prob( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const; CV_WRAP virtual cv::Mat getVarImportance(); -#endif - + CV_WRAP virtual void clear(); virtual const CvMat* get_var_importance(); virtual float get_proximity( const CvMat* sample1, const CvMat* sample2, const CvMat* missing1 = 0, const CvMat* missing2 = 0 ) const; - - virtual float calc_error( CvMLData* _data, int type , std::vector *resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR} - virtual float get_train_error(); + virtual float calc_error( CvMLData* data, int type , std::vector* resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR} + + virtual float get_train_error(); virtual void read( CvFileStorage* fs, CvFileNode* node ); virtual void write( CvFileStorage* fs, const char* name ) const; @@ -1052,6 +1032,7 @@ class CV_EXPORTS_W CvRTrees : public CvStatModel CvForestTree* get_tree(int i) const; protected: + virtual std::string getName() const; virtual bool grow_forest( const CvTermCriteria term_crit ); @@ -1095,13 +1076,13 @@ class CV_EXPORTS CvForestERTree : public CvForestTree { protected: virtual double calc_node_dir( CvDTreeNode* node ); - virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual void split_node_data( CvDTreeNode* n ); }; @@ -1116,15 +1097,14 @@ class CV_EXPORTS_W CvERTrees : public CvRTrees const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvRTParams params=CvRTParams()); -#ifndef SWIG CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat(), CvRTParams params=CvRTParams()); -#endif virtual bool train( CvMLData* data, CvRTParams params=CvRTParams() ); protected: + virtual std::string getName() const; virtual bool grow_forest( const CvTermCriteria term_crit ); }; @@ -1180,13 +1160,13 @@ class CV_EXPORTS CvBoostTree: public CvDTree virtual void try_split_node( CvDTreeNode* n ); virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); - virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, + virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi, float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 ); virtual void calc_node_value( CvDTreeNode* n ); virtual double calc_node_dir( CvDTreeNode* n ); @@ -1212,14 +1192,14 @@ class CV_EXPORTS_W CvBoost : public CvStatModel const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvBoostParams params=CvBoostParams() ); - + virtual bool train( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvBoostParams params=CvBoostParams(), bool update=false ); - + virtual bool train( CvMLData* data, CvBoostParams params=CvBoostParams(), bool update=false ); @@ -1228,25 +1208,23 @@ class CV_EXPORTS_W CvBoost : public CvStatModel CvMat* weak_responses=0, CvSlice slice=CV_WHOLE_SEQ, bool raw_mode=false, bool return_sum=false ) const; -#ifndef SWIG CV_WRAP CvBoost( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat(), CvBoostParams params=CvBoostParams() ); - + CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat(), CvBoostParams params=CvBoostParams(), bool update=false ); - + CV_WRAP virtual float predict( const cv::Mat& sample, const cv::Mat& missing=cv::Mat(), const cv::Range& slice=cv::Range::all(), bool rawMode=false, bool returnSum=false ) const; -#endif - + virtual float calc_error( CvMLData* _data, int type , std::vector *resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR} CV_WRAP virtual void prune( CvSlice slice ); @@ -1326,7 +1304,7 @@ struct CV_EXPORTS_W_MAP CvGBTreesParams : public CvDTreeParams // DataType: CLASS CvGBTrees // Gradient Boosting Trees (GBT) algorithm implementation. -// +// // data - training dataset // params - parameters of the CvGBTrees // weak - array[0..(class_count-1)] of CvSeq @@ -1358,7 +1336,7 @@ struct CV_EXPORTS_W_MAP CvGBTreesParams : public CvDTreeParams // missing - mask of the missing values in the training set. This // matrix has the same size as train_data. 1 - missing // value, 0 - not a missing value. -// class_labels - output class labels map. +// class_labels - output class labels map. // rng - random number generator. Used for spliting the // training set. // class_count - count of output classes. @@ -1379,15 +1357,15 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* // DataType: ENUM // Loss functions implemented in CvGBTrees. - // + // // SQUARED_LOSS // problem: regression // loss = (x - x')^2 - // + // // ABSOLUTE_LOSS // problem: regression // loss = abs(x - x') - // + // // HUBER_LOSS // problem: regression // loss = delta*( abs(x - x') - delta/2), if abs(x - x') > delta @@ -1397,18 +1375,18 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // // DEVIANCE_LOSS // problem: classification - // - */ + // + */ enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; - - + + /* // Default constructor. Creates a model only (without training). // Should be followed by one form of the train(...) function. // // API // CvGBTrees(); - + // INPUT // OUTPUT // RESULT @@ -1426,7 +1404,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams() ); - + // INPUT // trainData - a set of input feature vectors. // size of matrix is @@ -1459,13 +1437,13 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams() ); - + /* // Destructor. */ virtual ~CvGBTrees(); - - + + /* // Gradient tree boosting model training // @@ -1476,7 +1454,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams(), bool update=false ); - + // INPUT // trainData - a set of input feature vectors. // size of matrix is @@ -1511,8 +1489,8 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams(), bool update=false ); - - + + /* // Gradient tree boosting model training // @@ -1520,7 +1498,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // virtual bool train( CvMLData* data, CvGBTreesParams params=CvGBTreesParams(), bool update=false ) {return false;}; - + // INPUT // data - training set. // params - parameters of GTB algorithm. @@ -1533,7 +1511,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel CvGBTreesParams params=CvGBTreesParams(), bool update=false ); - + /* // Response value prediction // @@ -1541,7 +1519,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // virtual float predict_serial( const CvMat* sample, const CvMat* missing=0, CvMat* weak_responses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const; - + // INPUT // sample - input sample of the same type as in the training set. // missing - missing values mask. missing=0 if there are no @@ -1552,7 +1530,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // slice = CV_WHOLE_SEQ when all trees are used. // k - number of ensemble used. // k is in {-1,0,1,..,}. - // in the case of classification problem + // in the case of classification problem // ensembles are built. // If k = -1 ordinary prediction is the result, // otherwise function gives the prediction of the @@ -1564,7 +1542,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel virtual float predict_serial( const CvMat* sample, const CvMat* missing=0, CvMat* weakResponses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const; - + /* // Response value prediction. // Parallel version (in the case of TBB existence) @@ -1573,7 +1551,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // virtual float predict( const CvMat* sample, const CvMat* missing=0, CvMat* weak_responses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const; - + // INPUT // sample - input sample of the same type as in the training set. // missing - missing values mask. missing=0 if there are no @@ -1584,7 +1562,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // slice = CV_WHOLE_SEQ when all trees are used. // k - number of ensemble used. // k is in {-1,0,1,..,}. - // in the case of classification problem + // in the case of classification problem // ensembles are built. // If k = -1 ordinary prediction is the result, // otherwise function gives the prediction of the @@ -1592,7 +1570,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // OUTPUT // RESULT // Predicted value. - */ + */ virtual float predict( const CvMat* sample, const CvMat* missing=0, CvMat* weakResponses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const; @@ -1602,7 +1580,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // // API // virtual void clear(); - + // INPUT // OUTPUT // delete data, weak, orig_response, sum_response, @@ -1633,7 +1611,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel std::vector *resp = 0 ); /* - // + // // Write parameters of the gtb model and data. Write learned model. // // API @@ -1649,7 +1627,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* - // + // // Read parameters of the gtb model and data. Read learned model. // // API @@ -1663,14 +1641,14 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel */ virtual void read( CvFileStorage* fs, CvFileNode* node ); - + // new-style C++ interface CV_WRAP CvGBTrees( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), const cv::Mat& missingDataMask=cv::Mat(), CvGBTreesParams params=CvGBTreesParams() ); - + CV_WRAP virtual bool train( const cv::Mat& trainData, int tflag, const cv::Mat& responses, const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(), const cv::Mat& varType=cv::Mat(), @@ -1681,7 +1659,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel CV_WRAP virtual float predict( const cv::Mat& sample, const cv::Mat& missing=cv::Mat(), const cv::Range& slice = cv::Range::all(), int k=-1 ) const; - + protected: /* @@ -1689,7 +1667,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // // API // virtual void find_gradient( const int k = 0); - + // INPUT // k - used for classification problem, determining current // tree ensemble. @@ -1701,9 +1679,9 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel */ virtual void find_gradient( const int k = 0); - + /* - // + // // Change values in tree leaves according to the used loss function. // // API @@ -1722,7 +1700,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* - // + // // Find optimal constant prediction value according to the used loss // function. // The goal is to find a constant which gives the minimal summary loss @@ -1739,9 +1717,9 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel */ virtual float find_optimal_value( const CvMat* _Idx ); - + /* - // + // // Randomly split the whole training set in two parts according // to params.portion. // @@ -1758,7 +1736,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* - // + // // Internal recursive function giving an array of subtree tree leaves. // // API @@ -1772,10 +1750,10 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // RESULT */ void leaves_get( CvDTreeNode** leaves, int& count, CvDTreeNode* node ); - - + + /* - // + // // Get leaves of the tree. // // API @@ -1790,9 +1768,9 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel */ CvDTreeNode** GetLeaves( const CvDTree* dtree, int& len ); - + /* - // + // // Is it a regression or a classification. // // API @@ -1808,7 +1786,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* - // + // // Write parameters of the gtb model. // // API @@ -1823,7 +1801,7 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel /* - // + // // Read parameters of the gtb model and data. // // API @@ -1840,9 +1818,9 @@ class CV_EXPORTS_W CvGBTrees : public CvStatModel // RESULT */ virtual void read_params( CvFileStorage* fs, CvFileNode* fnode ); - int get_len(const CvMat* mat) const; + int get_len(const CvMat* mat) const; + - CvDTreeTrainData* data; CvGBTreesParams params; @@ -1905,30 +1883,28 @@ class CV_EXPORTS_W CvANN_MLP : public CvStatModel virtual void create( const CvMat* layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 ); - + virtual int train( const CvMat* inputs, const CvMat* outputs, const CvMat* sampleWeights, const CvMat* sampleIdx=0, CvANN_MLP_TrainParams params = CvANN_MLP_TrainParams(), int flags=0 ); virtual float predict( const CvMat* inputs, CV_OUT CvMat* outputs ) const; - -#ifndef SWIG + CV_WRAP CvANN_MLP( const cv::Mat& layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 ); - + CV_WRAP virtual void create( const cv::Mat& layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, - double fparam1=0, double fparam2=0 ); - + double fparam1=0, double fparam2=0 ); + CV_WRAP virtual int train( const cv::Mat& inputs, const cv::Mat& outputs, const cv::Mat& sampleWeights, const cv::Mat& sampleIdx=cv::Mat(), CvANN_MLP_TrainParams params = CvANN_MLP_TrainParams(), - int flags=0 ); - + int flags=0 ); + CV_WRAP virtual float predict( const cv::Mat& inputs, CV_OUT cv::Mat& outputs ) const; -#endif - + CV_WRAP virtual void clear(); // possible activation functions @@ -2012,17 +1988,10 @@ CVAPI(void) cvCreateTestSet( int type, CvMat** samples, CvMat** responses, int num_classes, ... ); - -#endif - /****************************************************************************************\ * Data * \****************************************************************************************/ -#include -#include -#include - #define CV_COUNT 0 #define CV_PORTION 1 @@ -2049,8 +2018,8 @@ class CV_EXPORTS CvMLData virtual ~CvMLData(); // returns: - // 0 - OK - // 1 - file can not be opened or is not correct + // 0 - OK + // -1 - file can not be opened or is not correct int read_csv( const char* filename ); const CvMat* get_values() const; @@ -2065,9 +2034,11 @@ class CV_EXPORTS CvMLData const CvMat* get_train_sample_idx() const; const CvMat* get_test_sample_idx() const; void mix_train_and_test_idx(); - + const CvMat* get_var_idx(); - void chahge_var_idx( int vi, bool state ); // state == true to set vi-variable as predictor + void chahge_var_idx( int vi, bool state ); // misspelled (saved for back compitability), + // use change_var_idx + void change_var_idx( int vi, bool state ); // state == true to set vi-variable as predictor const CvMat* get_var_types(); int get_var_type( int var_idx ) const; @@ -2077,14 +2048,14 @@ class CV_EXPORTS CvMLData void set_var_types( const char* str ); // str examples: // "ord[0-17],cat[18]", "ord[0,2,4,10-12], cat[1,3,5-9,13,14]", // "cat", "ord" (all vars are categorical/ordered) - void change_var_type( int var_idx, int type); // type in { CV_VAR_ORDERED, CV_VAR_CATEGORICAL } - + void change_var_type( int var_idx, int type); // type in { CV_VAR_ORDERED, CV_VAR_CATEGORICAL } + void set_delimiter( char ch ); char get_delimiter() const; void set_miss_ch( char ch ); char get_miss_ch() const; - + const std::map& get_class_labels_map() const; protected: @@ -2092,7 +2063,7 @@ class CV_EXPORTS CvMLData void str_to_flt_elem( const char* token, float& flt_elem, int& type); void free_train_test_idx(); - + char delimiter; char miss_ch; //char flt_separator; @@ -2110,7 +2081,7 @@ class CV_EXPORTS CvMLData int train_sample_count; bool mix; - + int total_class_count; std::map class_map; @@ -2124,7 +2095,7 @@ class CV_EXPORTS CvMLData namespace cv { - + typedef CvStatModel StatModel; typedef CvParamGrid ParamGrid; typedef CvNormalBayesClassifier NormalBayesClassifier; @@ -2133,8 +2104,6 @@ typedef CvSVMParams SVMParams; typedef CvSVMKernel SVMKernel; typedef CvSVMSolver SVMSolver; typedef CvSVM SVM; -typedef CvEMParams EMParams; -typedef CvEM ExpectationMaximization; typedef CvDTreeParams DTreeParams; typedef CvMLData TrainData; typedef CvDTree DecisionTree; @@ -2153,8 +2122,12 @@ typedef CvGBTreesParams GradientBoostingTreeParams; typedef CvGBTrees GradientBoostingTrees; template<> CV_EXPORTS void Ptr::delete_obj(); - + +CV_EXPORTS bool initModule_ml(void); + } -#endif +#endif // __cplusplus +#endif // __OPENCV_ML_HPP__ + /* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/features2d.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/features2d.hpp new file mode 100644 index 0000000..f23bec8 --- /dev/null +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/features2d.hpp @@ -0,0 +1,155 @@ +/*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. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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 __OPENCV_NONFREE_FEATURES_2D_HPP__ +#define __OPENCV_NONFREE_FEATURES_2D_HPP__ + +#include "opencv2/features2d/features2d.hpp" + +#ifdef __cplusplus + +namespace cv +{ + +/*! + SIFT implementation. + + The class implements SIFT algorithm by D. Lowe. +*/ +class CV_EXPORTS_W SIFT : public Feature2D +{ +public: + CV_WRAP explicit SIFT( int nfeatures=0, int nOctaveLayers=3, + double contrastThreshold=0.04, double edgeThreshold=10, + double sigma=1.6); + + //! returns the descriptor size in floats (128) + CV_WRAP int descriptorSize() const; + + //! returns the descriptor type + CV_WRAP int descriptorType() const; + + //! finds the keypoints using SIFT algorithm + void operator()(InputArray img, InputArray mask, + vector& keypoints) const; + //! finds the keypoints and computes descriptors for them using SIFT algorithm. + //! Optionally it can compute descriptors for the user-provided keypoints + void operator()(InputArray img, InputArray mask, + vector& keypoints, + OutputArray descriptors, + bool useProvidedKeypoints=false) const; + + AlgorithmInfo* info() const; + + void buildGaussianPyramid( const Mat& base, vector& pyr, int nOctaves ) const; + void buildDoGPyramid( const vector& pyr, vector& dogpyr ) const; + void findScaleSpaceExtrema( const vector& gauss_pyr, const vector& dog_pyr, + vector& keypoints ) const; + +protected: + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; + + CV_PROP_RW int nfeatures; + CV_PROP_RW int nOctaveLayers; + CV_PROP_RW double contrastThreshold; + CV_PROP_RW double edgeThreshold; + CV_PROP_RW double sigma; +}; + +typedef SIFT SiftFeatureDetector; +typedef SIFT SiftDescriptorExtractor; + +/*! + SURF implementation. + + The class implements SURF algorithm by H. Bay et al. + */ +class CV_EXPORTS_W SURF : public Feature2D +{ +public: + //! the default constructor + CV_WRAP SURF(); + //! the full constructor taking all the necessary parameters + explicit CV_WRAP SURF(double hessianThreshold, + int nOctaves=4, int nOctaveLayers=2, + bool extended=true, bool upright=false); + + //! returns the descriptor size in float's (64 or 128) + CV_WRAP int descriptorSize() const; + + //! returns the descriptor type + CV_WRAP int descriptorType() const; + + //! finds the keypoints using fast hessian detector used in SURF + void operator()(InputArray img, InputArray mask, + CV_OUT vector& keypoints) const; + //! finds the keypoints and computes their descriptors. Optionally it can compute descriptors for the user-provided keypoints + void operator()(InputArray img, InputArray mask, + CV_OUT vector& keypoints, + OutputArray descriptors, + bool useProvidedKeypoints=false) const; + + AlgorithmInfo* info() const; + + CV_PROP_RW double hessianThreshold; + CV_PROP_RW int nOctaves; + CV_PROP_RW int nOctaveLayers; + CV_PROP_RW bool extended; + CV_PROP_RW bool upright; + +protected: + + void detectImpl( const Mat& image, vector& keypoints, const Mat& mask=Mat() ) const; + void computeImpl( const Mat& image, vector& keypoints, Mat& descriptors ) const; +}; + +typedef SURF SurfFeatureDetector; +typedef SURF SurfDescriptorExtractor; + +} /* namespace cv */ + +#endif /* __cplusplus */ + +#endif + +/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cv.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/nonfree.hpp old mode 100755 new mode 100644 similarity index 87% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cv.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/nonfree.hpp index 37b523b..c64c566 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv/cv.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/nonfree/nonfree.hpp @@ -11,7 +11,7 @@ // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2009-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, @@ -40,13 +40,18 @@ // //M*/ -#ifndef __OPENCV_OLD_CV_HPP__ -#define __OPENCV_OLD_CV_HPP__ +#ifndef __OPENCV_NONFREE_HPP__ +#define __OPENCV_NONFREE_HPP__ -//#if defined(__GNUC__) -//#warning "This is a deprecated opencv header provided for compatibility. Please include a header from a corresponding opencv module" -//#endif +#include "opencv2/nonfree/features2d.hpp" -#include +namespace cv +{ + +CV_EXPORTS_W bool initModule_nonfree(); + +} #endif + +/* End of file. */ diff --git a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/objdetect/objdetect.hpp b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/objdetect/objdetect.hpp old mode 100755 new mode 100644 similarity index 53% rename from Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/objdetect/objdetect.hpp rename to Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/objdetect/objdetect.hpp index 3300c20..8d7efb0 --- a/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv/include/opencv2/objdetect/objdetect.hpp +++ b/Chapter2_iPhoneAR/Example_MarkerBasedAR/opencv2.framework/Versions/A/Headers/objdetect/objdetect.hpp @@ -44,9 +44,11 @@ #define __OPENCV_OBJDETECT_HPP__ #include "opencv2/core/core.hpp" -#include "opencv2/features2d/features2d.hpp" #ifdef __cplusplus +#include +#include + extern "C" { #endif @@ -135,7 +137,7 @@ CVAPI(void) cvReleaseHaarClassifierCascade( CvHaarClassifierCascade** cascade ); CVAPI(CvSeq*) cvHaarDetectObjects( const CvArr* image, - CvHaarClassifierCascade* cascade, CvMemStorage* storage, + CvHaarClassifierCascade* cascade, CvMemStorage* storage, double scale_factor CV_DEFAULT(1.1), int min_neighbors CV_DEFAULT(3), int flags CV_DEFAULT(0), CvSize min_size CV_DEFAULT(cvSize(0,0)), CvSize max_size CV_DEFAULT(cvSize(0,0))); @@ -158,7 +160,7 @@ CVAPI(int) cvRunHaarClassifierCascade( const CvHaarClassifierCascade* cascade, // Structure describes the position of the filter in the feature pyramid // l - level in the feature pyramid // (x, y) - coordinate in level l -typedef struct +typedef struct CvLSVMFilterPosition { int x; int y; @@ -172,14 +174,14 @@ typedef struct // penaltyFunction - vector describes penalty function (d_i in the paper) // pf[0] * x + pf[1] * y + pf[2] * x^2 + pf[3] * y^2 // FILTER DESCRIPTION -// Rectangular map (sizeX x sizeY), +// Rectangular map (sizeX x sizeY), // every cell stores feature vector (dimension = p) // H - matrix of feature vectors -// to set and get feature vectors (i,j) +// to set and get feature vectors (i,j) // used formula H[(j * sizeX + i) * p + k], where // k - component of feature vector in cell (i, j) // END OF FILTER DESCRIPTION -typedef struct{ +typedef struct CvLSVMFilterObject{ CvLSVMFilterPosition V; float fineFunction[4]; int sizeX; @@ -190,7 +192,7 @@ typedef struct{ // data type: STRUCT CvLatentSvmDetector // structure contains internal representation of trained Latent SVM detector -// num_filters - total number of filters (root plus part) in model +// num_filters - total number of filters (root plus part) in model // num_components - number of components in model // num_part_filters - array containing number of part filters for each component // filters - root and part filters for all model components @@ -198,23 +200,23 @@ typedef struct{ // score_threshold - confidence level threshold typedef struct CvLatentSvmDetector { - int num_filters; - int num_components; - int* num_part_filters; - CvLSVMFilterObject** filters; - float* b; - float score_threshold; + int num_filters; + int num_components; + int* num_part_filters; + CvLSVMFilterObject** filters; + float* b; + float score_threshold; } CvLatentSvmDetector; // data type: STRUCT CvObjectDetection -// structure contains the bounding box and confidence level for detected object +// structure contains the bounding box and confidence level for detected object // rect - bounding box for a detected object -// score - confidence level +// score - confidence level typedef struct CvObjectDetection { - CvRect rect; - float score; + CvRect rect; + float score; } CvObjectDetection; //////////////// Object Detection using Latent SVM ////////////// @@ -227,7 +229,7 @@ typedef struct CvObjectDetection // CvLatentSvmDetector* cvLoadLatentSvmDetector(const char* filename); // INPUT // filename - path to the file containing the parameters of - - trained Latent SVM detector + - trained Latent SVM detector // OUTPUT // trained Latent SVM detector in internal representation */ @@ -245,29 +247,29 @@ CVAPI(CvLatentSvmDetector*) cvLoadLatentSvmDetector(const char* filename); CVAPI(void) cvReleaseLatentSvmDetector(CvLatentSvmDetector** detector); /* -// find rectangular regions in the given image that are likely +// find rectangular regions in the given image that are likely // to contain objects and corresponding confidence levels // // API -// CvSeq* cvLatentSvmDetectObjects(const IplImage* image, -// CvLatentSvmDetector* detector, -// CvMemStorage* storage, +// CvSeq* cvLatentSvmDetectObjects(const IplImage* image, +// CvLatentSvmDetector* detector, +// CvMemStorage* storage, // float overlap_threshold = 0.5f, // int numThreads = -1); // INPUT // image - image to detect objects in // detector - Latent SVM detector in internal representation -// storage - memory storage to store the resultant sequence +// storage - memory storage to store the resultant sequence // of the object candidate rectangles -// overlap_threshold - threshold for the non-maximum suppression algorithm +// overlap_threshold - threshold for the non-maximum suppression algorithm = 0.5f [here will be the reference to original paper] // OUTPUT // sequence of detected objects (bounding boxes and confidence levels stored in CvObjectDetection structures) */ -CVAPI(CvSeq*) cvLatentSvmDetectObjects(IplImage* image, - CvLatentSvmDetector* detector, - CvMemStorage* storage, - float overlap_threshold CV_DEFAULT(0.5f), +CVAPI(CvSeq*) cvLatentSvmDetectObjects(IplImage* image, + CvLatentSvmDetector* detector, + CvMemStorage* storage, + float overlap_threshold CV_DEFAULT(0.5f), int numThreads CV_DEFAULT(-1)); #ifdef __cplusplus @@ -283,7 +285,7 @@ CV_EXPORTS CvSeq* cvHaarDetectObjectsForROC( const CvArr* image, namespace cv { - + ///////////////////////////// Object Detection //////////////////////////// /* @@ -328,23 +330,23 @@ class CV_EXPORTS LatentSvmDetector CV_EXPORTS void groupRectangles(CV_OUT CV_IN_OUT vector& rectList, int groupThreshold, double eps=0.2); CV_EXPORTS_W void groupRectangles(CV_OUT CV_IN_OUT vector& rectList, CV_OUT vector& weights, int groupThreshold, double eps=0.2); CV_EXPORTS void groupRectangles( vector& rectList, int groupThreshold, double eps, vector* weights, vector* levelWeights ); -CV_EXPORTS void groupRectangles(vector& rectList, vector& rejectLevels, +CV_EXPORTS void groupRectangles(vector& rectList, vector& rejectLevels, vector& levelWeights, int groupThreshold, double eps=0.2); -CV_EXPORTS void groupRectangles_meanshift(vector& rectList, vector& foundWeights, vector& foundScales, - double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); +CV_EXPORTS void groupRectangles_meanshift(vector& rectList, vector& foundWeights, vector& foundScales, + double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); + - class CV_EXPORTS FeatureEvaluator { -public: +public: enum { HAAR = 0, LBP = 1, HOG = 2 }; virtual ~FeatureEvaluator(); virtual bool read(const FileNode& node); virtual Ptr clone() const; virtual int getFeatureType() const; - - virtual bool setImage(const Mat&, Size origWinSize); + + virtual bool setImage(const Mat& img, Size origWinSize); virtual bool setWindow(Point p); virtual double calcOrd(int featureIdx) const; @@ -357,10 +359,10 @@ template<> CV_EXPORTS void Ptr::delete_obj(); enum { - CASCADE_DO_CANNY_PRUNING=1, - CASCADE_SCALE_IMAGE=2, - CASCADE_FIND_BIGGEST_OBJECT=4, - CASCADE_DO_ROUGH_SEARCH=8 + CASCADE_DO_CANNY_PRUNING=1, + CASCADE_SCALE_IMAGE=2, + CASCADE_FIND_BIGGEST_OBJECT=4, + CASCADE_DO_ROUGH_SEARCH=8 }; class CV_EXPORTS_W CascadeClassifier @@ -369,7 +371,7 @@ class CV_EXPORTS_W CascadeClassifier CV_WRAP CascadeClassifier(); CV_WRAP CascadeClassifier( const string& filename ); virtual ~CascadeClassifier(); - + CV_WRAP virtual bool empty() const; CV_WRAP bool load( const string& filename ); virtual bool read( const FileNode& node ); @@ -409,7 +411,7 @@ class CV_EXPORTS_W CascadeClassifier enum { DO_CANNY_PRUNING = 1, SCALE_IMAGE = 2, FIND_BIGGEST_OBJECT = 4, DO_ROUGH_SEARCH = 8 }; - friend struct CascadeClassifierInvoker; + friend class CascadeClassifierInvoker; template friend int predictOrdered( CascadeClassifier& cascade, Ptr &featureEvaluator, double& weight); @@ -423,8 +425,8 @@ class CV_EXPORTS_W CascadeClassifier template friend int predictCategoricalStump( CascadeClassifier& cascade, Ptr &featureEvaluator, double& weight); - bool setImage( Ptr&, const Mat& ); - virtual int runAt( Ptr&, Point, double& weight ); + bool setImage( Ptr& feval, const Mat& image); + virtual int runAt( Ptr& feval, Point pt, double& weight ); class Data { @@ -470,11 +472,12 @@ class CV_EXPORTS_W CascadeClassifier Ptr oldCascade; public: - class MaskGenerator + class CV_EXPORTS MaskGenerator { - public: - virtual cv::Mat generateMask(const cv::Mat& src)=0; - virtual void initializeMask(const cv::Mat& /*src*/) {}; + public: + virtual ~MaskGenerator() {} + virtual cv::Mat generateMask(const cv::Mat& src)=0; + virtual void initializeMask(const cv::Mat& /*src*/) {}; }; void setMaskGenerator(Ptr maskGenerator); Ptr getMaskGenerator(); @@ -485,21 +488,32 @@ class CV_EXPORTS_W CascadeClassifier Ptr maskGenerator; }; - + //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// +// struct for detection region of interest (ROI) +struct DetectionROI +{ + // scale(size) of the bounding box + double scale; + // set of requrested locations to be evaluated + vector locations; + // vector that will contain confidence values for each location + vector confidences; +}; + struct CV_EXPORTS_W HOGDescriptor { public: enum { L2Hys=0 }; enum { DEFAULT_NLEVELS=64 }; - + CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), - cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), - histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), + cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), + histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), nlevels(HOGDescriptor::DEFAULT_NLEVELS) {} - + CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, int _histogramNormType=HOGDescriptor::L2Hys, @@ -510,28 +524,28 @@ struct CV_EXPORTS_W HOGDescriptor histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), gammaCorrection(_gammaCorrection), nlevels(_nlevels) {} - + CV_WRAP HOGDescriptor(const String& filename) { load(filename); } - + HOGDescriptor(const HOGDescriptor& d) { d.copyTo(*this); } - + virtual ~HOGDescriptor() {} - + CV_WRAP size_t getDescriptorSize() const; CV_WRAP bool checkDetectorSize() const; CV_WRAP double getWinSigma() const; - + CV_WRAP virtual void setSVMDetector(InputArray _svmdetector); - + virtual bool read(FileNode& fn); virtual void write(FileStorage& fs, const String& objname) const; - + CV_WRAP virtual bool load(const String& filename, const String& objname=String()); CV_WRAP virtual void save(const String& filename, const String& objname=String()) const; virtual void copyTo(HOGDescriptor& c) const; @@ -540,34 +554,34 @@ struct CV_EXPORTS_W HOGDescriptor CV_OUT vector& descriptors, Size winStride=Size(), Size padding=Size(), const vector& locations=vector()) const; - //with found weights output - CV_WRAP virtual void detect(const Mat& img, CV_OUT vector& foundLocations, - vector& weights, - double hitThreshold=0, Size winStride=Size(), - Size padding=Size(), - const vector& searchLocations=vector()) const; - //without found weights output + //with found weights output CV_WRAP virtual void detect(const Mat& img, CV_OUT vector& foundLocations, + CV_OUT vector& weights, + double hitThreshold=0, Size winStride=Size(), + Size padding=Size(), + const vector& searchLocations=vector()) const; + //without found weights output + virtual void detect(const Mat& img, CV_OUT vector& foundLocations, double hitThreshold=0, Size winStride=Size(), Size padding=Size(), const vector& searchLocations=vector()) const; - //with result weights output - CV_WRAP virtual void detectMultiScale(const Mat& img, CV_OUT vector& foundLocations, - vector& foundWeights, double hitThreshold=0, - Size winStride=Size(), Size padding=Size(), double scale=1.05, - double finalThreshold=2.0,bool useMeanshiftGrouping = false) const; - //without found weights output - CV_WRAP virtual void detectMultiScale(const Mat& img, CV_OUT vector& foundLocations, - double hitThreshold=0, Size winStride=Size(), - Size padding=Size(), double scale=1.05, - double finalThreshold=2.0, bool useMeanshiftGrouping = false) const; + //with result weights output + CV_WRAP virtual void detectMultiScale(const Mat& img, CV_OUT vector& foundLocations, + CV_OUT vector& foundWeights, double hitThreshold=0, + Size winStride=Size(), Size padding=Size(), double scale=1.05, + double finalThreshold=2.0,bool useMeanshiftGrouping = false) const; + //without found weights output + virtual void detectMultiScale(const Mat& img, CV_OUT vector& foundLocations, + double hitThreshold=0, Size winStride=Size(), + Size padding=Size(), double scale=1.05, + double finalThreshold=2.0, bool useMeanshiftGrouping = false) const; CV_WRAP virtual void computeGradient(const Mat& img, CV_OUT Mat& grad, CV_OUT Mat& angleOfs, Size paddingTL=Size(), Size paddingBR=Size()) const; - + CV_WRAP static vector getDefaultPeopleDetector(); - CV_WRAP static vector getDaimlerPeopleDetector(); - + CV_WRAP static vector getDaimlerPeopleDetector(); + CV_PROP Size winSize; CV_PROP Size blockSize; CV_PROP Size blockStride; @@ -580,68 +594,33 @@ struct CV_EXPORTS_W HOGDescriptor CV_PROP bool gammaCorrection; CV_PROP vector svmDetector; CV_PROP int nlevels; -}; -/****************************************************************************************\ -* Planar Object Detection * -\****************************************************************************************/ -class CV_EXPORTS PlanarObjectDetector -{ -public: - PlanarObjectDetector(); - PlanarObjectDetector(const FileNode& node); - PlanarObjectDetector(const vector& pyr, int _npoints=300, - int _patchSize=FernClassifier::PATCH_SIZE, - int _nstructs=FernClassifier::DEFAULT_STRUCTS, - int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, - int _nviews=FernClassifier::DEFAULT_VIEWS, - const LDetector& detector=LDetector(), - const PatchGenerator& patchGenerator=PatchGenerator()); - virtual ~PlanarObjectDetector(); - virtual void train(const vector& pyr, int _npoints=300, - int _patchSize=FernClassifier::PATCH_SIZE, - int _nstructs=FernClassifier::DEFAULT_STRUCTS, - int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, - int _nviews=FernClassifier::DEFAULT_VIEWS, - const LDetector& detector=LDetector(), - const PatchGenerator& patchGenerator=PatchGenerator()); - virtual void train(const vector& pyr, const vector& keypoints, - int _patchSize=FernClassifier::PATCH_SIZE, - int _nstructs=FernClassifier::DEFAULT_STRUCTS, - int _structSize=FernClassifier::DEFAULT_STRUCT_SIZE, - int _nviews=FernClassifier::DEFAULT_VIEWS, - const LDetector& detector=LDetector(), - const PatchGenerator& patchGenerator=PatchGenerator()); - Rect getModelROI() const; - vector getModelPoints() const; - const LDetector& getDetector() const; - const FernClassifier& getClassifier() const; - void setVerbose(bool verbose); - - void read(const FileNode& node); - void write(FileStorage& fs, const String& name=String()) const; - bool operator()(const Mat& image, CV_OUT Mat& H, CV_OUT vector& corners) const; - bool operator()(const vector& pyr, const vector& keypoints, - CV_OUT Mat& H, CV_OUT vector& corners, - CV_OUT vector* pairs=0) const; + // evaluate specified ROI and return confidence value for each location + void detectROI(const cv::Mat& img, const vector &locations, + CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, + double hitThreshold = 0, cv::Size winStride = Size(), + cv::Size padding = Size()) const; -protected: - bool verbose; - Rect modelROI; - vector modelPoints; - LDetector ldetector; - FernClassifier fernClassifier; -}; + // evaluate specified ROI and return confidence value for each location in multiple scales + void detectMultiScaleROI(const cv::Mat& img, + CV_OUT std::vector& foundLocations, + std::vector& locations, + double hitThreshold = 0, + int groupThreshold = 0) const; -struct CV_EXPORTS DataMatrixCode { - char msg[4]; //TODO std::string - Mat original; - Point corners[4]; //TODO vector + // read/parse Dalal's alt model file + void readALTModel(std::string modelfile); }; -CV_EXPORTS void findDataMatrix(const Mat& image, std::vector& codes); -CV_EXPORTS void drawDataMatrixCodes(const std::vector& codes, Mat& drawImage); + +CV_EXPORTS_W void findDataMatrix(InputArray image, + CV_OUT vector& codes, + OutputArray corners=noArray(), + OutputArrayOfArrays dmtx=noArray()); +CV_EXPORTS_W void drawDataMatrixCodes(InputOutputArray image, + const vector& codes, + InputArray corners); } /****************************************************************************************\ @@ -654,8 +633,423 @@ struct CV_EXPORTS CvDataMatrixCode { CvMat *corners; }; -#include CV_EXPORTS std::deque cvFindDataMatrix(CvMat *im); + +/****************************************************************************************\ +* LINE-MOD * +\****************************************************************************************/ + +namespace cv { +namespace linemod { + +using cv::FileNode; +using cv::FileStorage; +using cv::Mat; +using cv::noArray; +using cv::OutputArrayOfArrays; +using cv::Point; +using cv::Ptr; +using cv::Rect; +using cv::Size; + +/// @todo Convert doxy comments to rst + +/** + * \brief Discriminant feature described by its location and label. + */ +struct CV_EXPORTS Feature +{ + int x; ///< x offset + int y; ///< y offset + int label; ///< Quantization + + Feature() : x(0), y(0), label(0) {} + Feature(int x, int y, int label); + + void read(const FileNode& fn); + void write(FileStorage& fs) const; +}; + +inline Feature::Feature(int _x, int _y, int _label) : x(_x), y(_y), label(_label) {} + +struct CV_EXPORTS Template +{ + int width; + int height; + int pyramid_level; + std::vector features; + + void read(const FileNode& fn); + void write(FileStorage& fs) const; +}; + +/** + * \brief Represents a modality operating over an image pyramid. + */ +class QuantizedPyramid +{ +public: + // Virtual destructor + virtual ~QuantizedPyramid() {} + + /** + * \brief Compute quantized image at current pyramid level for online detection. + * + * \param[out] dst The destination 8-bit image. For each pixel at most one bit is set, + * representing its classification. + */ + virtual void quantize(Mat& dst) const =0; + + /** + * \brief Extract most discriminant features at current pyramid level to form a new template. + * + * \param[out] templ The new template. + */ + virtual bool extractTemplate(Template& templ) const =0; + + /** + * \brief Go to the next pyramid level. + * + * \todo Allow pyramid scale factor other than 2 + */ + virtual void pyrDown() =0; + +protected: + /// Candidate feature with a score + struct Candidate + { + Candidate(int x, int y, int label, float score); + + /// Sort candidates with high score to the front + bool operator<(const Candidate& rhs) const + { + return score > rhs.score; + } + + Feature f; + float score; + }; + + /** + * \brief Choose candidate features so that they are not bunched together. + * + * \param[in] candidates Candidate features sorted by score. + * \param[out] features Destination vector of selected features. + * \param[in] num_features Number of candidates to select. + * \param[in] distance Hint for desired distance between features. + */ + static void selectScatteredFeatures(const std::vector& candidates, + std::vector& features, + size_t num_features, float distance); +}; + +inline QuantizedPyramid::Candidate::Candidate(int x, int y, int label, float _score) : f(x, y, label), score(_score) {} + +/** + * \brief Interface for modalities that plug into the LINE template matching representation. + * + * \todo Max response, to allow optimization of summing (255/MAX) features as uint8 + */ +class CV_EXPORTS Modality +{ +public: + // Virtual destructor + virtual ~Modality() {} + + /** + * \brief Form a quantized image pyramid from a source image. + * + * \param[in] src The source image. Type depends on the modality. + * \param[in] mask Optional mask. If not empty, unmasked pixels are set to zero + * in quantized image and cannot be extracted as features. + */ + Ptr process(const Mat& src, + const Mat& mask = Mat()) const + { + return processImpl(src, mask); + } + + virtual std::string name() const =0; + + virtual void read(const FileNode& fn) =0; + virtual void write(FileStorage& fs) const =0; + + /** + * \brief Create modality by name. + * + * The following modality types are supported: + * - "ColorGradient" + * - "DepthNormal" + */ + static Ptr create(const std::string& modality_type); + + /** + * \brief Load a modality from file. + */ + static Ptr create(const FileNode& fn); + +protected: + // Indirection is because process() has a default parameter. + virtual Ptr processImpl(const Mat& src, + const Mat& mask) const =0; +}; + +/** + * \brief Modality that computes quantized gradient orientations from a color image. + */ +class CV_EXPORTS ColorGradient : public Modality +{ +public: + /** + * \brief Default constructor. Uses reasonable default parameter values. + */ + ColorGradient(); + + /** + * \brief Constructor. + * + * \param weak_threshold When quantizing, discard gradients with magnitude less than this. + * \param num_features How many features a template must contain. + * \param strong_threshold Consider as candidate features only gradients whose norms are + * larger than this. + */ + ColorGradient(float weak_threshold, size_t num_features, float strong_threshold); + + virtual std::string name() const; + + virtual void read(const FileNode& fn); + virtual void write(FileStorage& fs) const; + + float weak_threshold; + size_t num_features; + float strong_threshold; + +protected: + virtual Ptr processImpl(const Mat& src, + const Mat& mask) const; +}; + +/** + * \brief Modality that computes quantized surface normals from a dense depth map. + */ +class CV_EXPORTS DepthNormal : public Modality +{ +public: + /** + * \brief Default constructor. Uses reasonable default parameter values. + */ + DepthNormal(); + + /** + * \brief Constructor. + * + * \param distance_threshold Ignore pixels beyond this distance. + * \param difference_threshold When computing normals, ignore contributions of pixels whose + * depth difference with the central pixel is above this threshold. + * \param num_features How many features a template must contain. + * \param extract_threshold Consider as candidate feature only if there are no differing + * orientations within a distance of extract_threshold. + */ + DepthNormal(int distance_threshold, int difference_threshold, size_t num_features, + int extract_threshold); + + virtual std::string name() const; + + virtual void read(const FileNode& fn); + virtual void write(FileStorage& fs) const; + + int distance_threshold; + int difference_threshold; + size_t num_features; + int extract_threshold; + +protected: + virtual Ptr processImpl(const Mat& src, + const Mat& mask) const; +}; + +/** + * \brief Debug function to colormap a quantized image for viewing. + */ +void colormap(const Mat& quantized, Mat& dst); + +/** + * \brief Represents a successful template match. + */ +struct CV_EXPORTS Match +{ + Match() + { + } + + Match(int x, int y, float similarity, const std::string& class_id, int template_id); + + /// Sort matches with high similarity to the front + bool operator<(const Match& rhs) const + { + // Secondarily sort on template_id for the sake of duplicate removal + if (similarity != rhs.similarity) + return similarity > rhs.similarity; + else + return template_id < rhs.template_id; + } + + bool operator==(const Match& rhs) const + { + return x == rhs.x && y == rhs.y && similarity == rhs.similarity && class_id == rhs.class_id; + } + + int x; + int y; + float similarity; + std::string class_id; + int template_id; +}; + +inline Match::Match(int _x, int _y, float _similarity, const std::string& _class_id, int _template_id) + : x(_x), y(_y), similarity(_similarity), class_id(_class_id), template_id(_template_id) + { + } + +/** + * \brief Object detector using the LINE template matching algorithm with any set of + * modalities. + */ +class CV_EXPORTS Detector +{ +public: + /** + * \brief Empty constructor, initialize with read(). + */ + Detector(); + + /** + * \brief Constructor. + * + * \param modalities Modalities to use (color gradients, depth normals, ...). + * \param T_pyramid Value of the sampling step T at each pyramid level. The + * number of pyramid levels is T_pyramid.size(). + */ + Detector(const std::vector< Ptr >& modalities, const std::vector& T_pyramid); + + /** + * \brief Detect objects by template matching. + * + * Matches globally at the lowest pyramid level, then refines locally stepping up the pyramid. + * + * \param sources Source images, one for each modality. + * \param threshold Similarity threshold, a percentage between 0 and 100. + * \param[out] matches Template matches, sorted by similarity score. + * \param class_ids If non-empty, only search for the desired object classes. + * \param[out] quantized_images Optionally return vector of quantized images. + * \param masks The masks for consideration during matching. The masks should be CV_8UC1 + * where 255 represents a valid pixel. If non-empty, the vector must be + * the same size as sources. Each element must be + * empty or the same size as its corresponding source. + */ + void match(const std::vector& sources, float threshold, std::vector& matches, + const std::vector& class_ids = std::vector(), + OutputArrayOfArrays quantized_images = noArray(), + const std::vector& masks = std::vector()) const; + + /** + * \brief Add new object template. + * + * \param sources Source images, one for each modality. + * \param class_id Object class ID. + * \param object_mask Mask separating object from background. + * \param[out] bounding_box Optionally return bounding box of the extracted features. + * + * \return Template ID, or -1 if failed to extract a valid template. + */ + int addTemplate(const std::vector& sources, const std::string& class_id, + const Mat& object_mask, Rect* bounding_box = NULL); + + /** + * \brief Add a new object template computed by external means. + */ + int addSyntheticTemplate(const std::vector