1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-25 05:13:04 +04:00

Compare commits

...

38 Commits

Author SHA1 Message Date
Marina Kolpakova 4b1724aeb9 fix for ORB tests 2012-06-01 15:12:10 +00:00
Alexander Shishkov a3c4d1b679 updated pdf's to 2.4.1 2012-06-01 13:44:23 +00:00
Alexander Shishkov e0b1697cc9 update FFMPEG wrapper binaries 2012-06-01 11:00:59 +00:00
Andrey Kamaev 059b79f7c2 Merged the trunk r8542:8544 2012-06-01 10:59:27 +00:00
Andrey Kamaev 8159ea3386 Merged the trunk r8537 (fixed pdf documentation build) 2012-06-01 08:46:54 +00:00
Andrey Kamaev 50c2443691 Merged Android samples from trunk r8423 r8533 2012-06-01 08:45:45 +00:00
Philipp Wagner 0bd287a8f2 Fixed reconstruction, so that the mean is correctly added to the reconstructed image. 2012-05-31 20:27:46 +00:00
Andrey Kamaev 2ee917c646 Version of 2.4 branch is adjusted to 2.4.1 2012-05-31 11:26:23 +00:00
Andrey Kamaev ca0962c738 Megred fix for pyrhon API generator regression r8528 2012-05-31 11:12:12 +00:00
Andrey Kamaev daad7900e2 Merged the trunk r8517:8524 2012-05-31 10:53:28 +00:00
Andrey Kamaev 9ad470ba5c backported API for storing OpenCV data structures to text string and reading them back (r8481, r8516, r8518, r8522) 2012-05-31 10:25:29 +00:00
Vladislav Vinogradov 4e4b96e3d9 Merged revision(s) 8484 from trunk:
fixed some bugs in gpu module under Windows:
* convertTo alignment error
........
2012-05-30 17:06:39 +00:00
Andrey Kamaev 4ddcc31edc Fixed few errors in documentation backporting 2012-05-30 11:20:55 +00:00
Andrey Kamaev 81a5988015 Merged the trunk r8467:8507 (inclusive) (big bunch of documentation fixes) 2012-05-30 11:13:07 +00:00
Andrey Kamaev 052d2dc23a Merged the trunk r8459:8466 (inclusive) 2012-05-30 09:00:32 +00:00
Andrey Kamaev 949c4edf41 Merged the trunk r8408:8457 (inclusive) 2012-05-30 08:47:34 +00:00
Andrey Kamaev 7b5a45eac4 Merged the trunk r8384:8407 (inclusive) 2012-05-30 08:04:37 +00:00
Vladislav Vinogradov 72d2311edf Merged revision(s) 8495 from trunk:
Bug #1991 : fixed gpu interpolation (remap, resize, warp...)
........
2012-05-29 11:35:30 +00:00
Vladislav Vinogradov d382fa56c7 Merged revision(s) 8474 from trunk:
fixed several problems with CUDA 5.0
* gpu::LUT, uses device memory instead of host memory
* gpu::multiply, round mod for CV_8U depth
........
2012-05-28 14:04:39 +00:00
Marina Kolpakova 00117d2a6e warp Affine tegra integration 2012-05-28 08:53:03 +00:00
Anatoly Baksheev 4ce8de5174 Merged revision(s) 8455 from trunk/opencv/modules/gpu/src:
compilation with CUDA5.0 (#1982, thanks to Rodrigo)
........
2012-05-25 09:45:42 +00:00
Andrey Kamaev e1c4fd9e1f Merged the trunk r8345:8376 2012-05-18 13:18:37 +00:00
Andrey Kamaev 70166820ea Merged the trunk r8324:8345 2012-05-18 12:59:40 +00:00
Andrey Kamaev aebed446b1 Partly merged the trunk r8322 2012-05-18 12:46:44 +00:00
Andrey Kamaev c3577a288b Merged the trunk r8291:8321 2012-05-18 12:34:01 +00:00
Andrey Kamaev 50ad690993 Merged the trunk till r8291 2012-05-18 12:18:17 +00:00
Anatoly Baksheev caddd398e6 Merged revision(s) 8368 from trunk/opencv/modules/gpu/src/imgproc.cpp:
fixed possible compilation error for macos
........
2012-05-17 15:00:36 +00:00
Alexander Smorkalov e62f147edc ColorBlobDetection example. Bug fix. Refactring. 2012-05-12 06:15:32 +00:00
Alexander Smorkalov b7c1fd34b9 ColorBlobDetection example. Pyrdown added. Contour area filtering added. 2012-05-12 05:19:17 +00:00
Andrey Kamaev ba238562c6 Fix for #1902 is merged from trunk 2012-05-07 14:05:06 +00:00
Anatoly Baksheev 01e93d57f0 Merged from trunk. 2012-05-05 09:25:37 +00:00
Philipp Wagner 86524b0e4a Fixed facerec_demo.cpp. 2012-05-05 09:16:21 +00:00
Anatoly Baksheev 70f74b70b7 fixed GPU compilation 2012-05-04 11:07:36 +00:00
Anatoly Baksheev 10459a886b Added check for CUDA toolkit version ( older can't compile Kepler ) 2012-05-04 10:34:57 +00:00
Anatoly Baksheev 215dd2a41b Merged revision(s) 8304 from trunk/opencv/cmake/OpenCVDetectCUDA.cmake:
Added check for CUDA toolkit version ( older can't compile Kepler )
........
2012-05-04 10:24:23 +00:00
Marina Kolpakova 025f6674db update for kepler arch support 2012-05-04 10:09:17 +00:00
Vadim Pisarevsky 3f5d722f34 fixed typo in mulSpectrums description (ticket #1868) 2012-05-03 15:14:53 +00:00
Anatoly Baksheev ab4025f8de fixed for Kepler 2012-05-03 10:23:23 +00:00
282 changed files with 55074 additions and 51687 deletions
Binary file not shown.
Binary file not shown.
+502
View File
@@ -0,0 +1,502 @@
//=============================================================================
//
// multimon.h -- Stub module that fakes multiple monitor apis on Win32 OSes
// without them.
//
// By using this header your code will get back default values from
// GetSystemMetrics() for new metrics, and the new multimonitor APIs
// will act like only one display is present on a Win32 OS without
// multimonitor APIs.
//
// Exactly one source must include this with COMPILE_MULTIMON_STUBS defined.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//=============================================================================
#ifdef __cplusplus
extern "C" { // Assume C declarations for C++
#endif // __cplusplus
//
// If we are building with Win95/NT4 headers, we need to declare
// the multimonitor-related metrics and APIs ourselves.
//
#ifndef SM_CMONITORS
#define SM_XVIRTUALSCREEN 76
#define SM_YVIRTUALSCREEN 77
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
#define SM_CMONITORS 80
#define SM_SAMEDISPLAYFORMAT 81
// HMONITOR is already declared if WINVER >= 0x0500 in windef.h
// This is for components built with an older version number.
//
#if !defined(HMONITOR_DECLARED) && (WINVER < 0x0500)
DECLARE_HANDLE(HMONITOR);
#define HMONITOR_DECLARED
#endif
#define MONITOR_DEFAULTTONULL 0x00000000
#define MONITOR_DEFAULTTOPRIMARY 0x00000001
#define MONITOR_DEFAULTTONEAREST 0x00000002
#define MONITORINFOF_PRIMARY 0x00000001
typedef struct tagMONITORINFO
{
DWORD cbSize;
RECT rcMonitor;
RECT rcWork;
DWORD dwFlags;
} MONITORINFO, *LPMONITORINFO;
#ifndef CCHDEVICENAME
#define CCHDEVICENAME 32
#endif
#ifdef __cplusplus
typedef struct tagMONITORINFOEXA : public tagMONITORINFO
{
CHAR szDevice[CCHDEVICENAME];
} MONITORINFOEXA, *LPMONITORINFOEXA;
typedef struct tagMONITORINFOEXW : public tagMONITORINFO
{
WCHAR szDevice[CCHDEVICENAME];
} MONITORINFOEXW, *LPMONITORINFOEXW;
#ifdef UNICODE
typedef MONITORINFOEXW MONITORINFOEX;
typedef LPMONITORINFOEXW LPMONITORINFOEX;
#else
typedef MONITORINFOEXA MONITORINFOEX;
typedef LPMONITORINFOEXA LPMONITORINFOEX;
#endif // UNICODE
#else // ndef __cplusplus
typedef struct tagMONITORINFOEXA
{
MONITORINFO;
CHAR szDevice[CCHDEVICENAME];
} MONITORINFOEXA, *LPMONITORINFOEXA;
typedef struct tagMONITORINFOEXW
{
MONITORINFO;
WCHAR szDevice[CCHDEVICENAME];
} MONITORINFOEXW, *LPMONITORINFOEXW;
#ifdef UNICODE
typedef MONITORINFOEXW MONITORINFOEX;
typedef LPMONITORINFOEXW LPMONITORINFOEX;
#else
typedef MONITORINFOEXA MONITORINFOEX;
typedef LPMONITORINFOEXA LPMONITORINFOEX;
#endif // UNICODE
#endif
typedef BOOL (CALLBACK* MONITORENUMPROC)(HMONITOR, HDC, LPRECT, LPARAM);
#ifndef DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
typedef struct _DISPLAY_DEVICEA {
DWORD cb;
CHAR DeviceName[32];
CHAR DeviceString[128];
DWORD StateFlags;
CHAR DeviceID[128];
CHAR DeviceKey[128];
} DISPLAY_DEVICEA, *PDISPLAY_DEVICEA, *LPDISPLAY_DEVICEA;
typedef struct _DISPLAY_DEVICEW {
DWORD cb;
WCHAR DeviceName[32];
WCHAR DeviceString[128];
DWORD StateFlags;
WCHAR DeviceID[128];
WCHAR DeviceKey[128];
} DISPLAY_DEVICEW, *PDISPLAY_DEVICEW, *LPDISPLAY_DEVICEW;
#ifdef UNICODE
typedef DISPLAY_DEVICEW DISPLAY_DEVICE;
typedef PDISPLAY_DEVICEW PDISPLAY_DEVICE;
typedef LPDISPLAY_DEVICEW LPDISPLAY_DEVICE;
#else
typedef DISPLAY_DEVICEA DISPLAY_DEVICE;
typedef PDISPLAY_DEVICEA PDISPLAY_DEVICE;
typedef LPDISPLAY_DEVICEA LPDISPLAY_DEVICE;
#endif // UNICODE
#define DISPLAY_DEVICE_ATTACHED_TO_DESKTOP 0x00000001
#define DISPLAY_DEVICE_MULTI_DRIVER 0x00000002
#define DISPLAY_DEVICE_PRIMARY_DEVICE 0x00000004
#define DISPLAY_DEVICE_MIRRORING_DRIVER 0x00000008
#define DISPLAY_DEVICE_VGA_COMPATIBLE 0x00000010
#endif
#endif // SM_CMONITORS
#undef GetMonitorInfo
#undef GetSystemMetrics
#undef MonitorFromWindow
#undef MonitorFromRect
#undef MonitorFromPoint
#undef EnumDisplayMonitors
#undef EnumDisplayDevices
//
// Define COMPILE_MULTIMON_STUBS to compile the stubs;
// otherwise, you get the declarations.
//
#ifdef COMPILE_MULTIMON_STUBS
//-----------------------------------------------------------------------------
//
// Implement the API stubs.
//
//-----------------------------------------------------------------------------
#ifndef _MULTIMON_USE_SECURE_CRT
#if defined(__GOT_SECURE_LIB__) && __GOT_SECURE_LIB__ >= 200402L
#define _MULTIMON_USE_SECURE_CRT 1
#else
#define _MULTIMON_USE_SECURE_CRT 0
#endif
#endif
#ifndef MULTIMON_FNS_DEFINED
int (WINAPI* g_pfnGetSystemMetrics)(int) = NULL;
HMONITOR (WINAPI* g_pfnMonitorFromWindow)(HWND, DWORD) = NULL;
HMONITOR (WINAPI* g_pfnMonitorFromRect)(LPCRECT, DWORD) = NULL;
HMONITOR (WINAPI* g_pfnMonitorFromPoint)(POINT, DWORD) = NULL;
BOOL (WINAPI* g_pfnGetMonitorInfo)(HMONITOR, LPMONITORINFO) = NULL;
BOOL (WINAPI* g_pfnEnumDisplayMonitors)(HDC, LPCRECT, MONITORENUMPROC, LPARAM) = NULL;
BOOL (WINAPI* g_pfnEnumDisplayDevices)(PVOID, DWORD, PDISPLAY_DEVICE,DWORD) = NULL;
BOOL g_fMultiMonInitDone = FALSE;
BOOL g_fMultimonPlatformNT = FALSE;
#endif
BOOL IsPlatformNT()
{
OSVERSIONINFOA osvi = {0};
osvi.dwOSVersionInfoSize = sizeof(osvi);
GetVersionExA((OSVERSIONINFOA*)&osvi);
return (VER_PLATFORM_WIN32_NT == osvi.dwPlatformId);
}
BOOL InitMultipleMonitorStubs(void)
{
HMODULE hUser32;
if (g_fMultiMonInitDone)
{
return g_pfnGetMonitorInfo != NULL;
}
g_fMultimonPlatformNT = IsPlatformNT();
hUser32 = GetModuleHandle(TEXT("USER32"));
if (hUser32 &&
(*(FARPROC*)&g_pfnGetSystemMetrics = GetProcAddress(hUser32,"GetSystemMetrics")) != NULL &&
(*(FARPROC*)&g_pfnMonitorFromWindow = GetProcAddress(hUser32,"MonitorFromWindow")) != NULL &&
(*(FARPROC*)&g_pfnMonitorFromRect = GetProcAddress(hUser32,"MonitorFromRect")) != NULL &&
(*(FARPROC*)&g_pfnMonitorFromPoint = GetProcAddress(hUser32,"MonitorFromPoint")) != NULL &&
(*(FARPROC*)&g_pfnEnumDisplayMonitors = GetProcAddress(hUser32,"EnumDisplayMonitors")) != NULL &&
#ifdef UNICODE
(*(FARPROC*)&g_pfnEnumDisplayDevices = GetProcAddress(hUser32,"EnumDisplayDevicesW")) != NULL &&
(*(FARPROC*)&g_pfnGetMonitorInfo = g_fMultimonPlatformNT ? GetProcAddress(hUser32,"GetMonitorInfoW") :
GetProcAddress(hUser32,"GetMonitorInfoA")) != NULL
#else
(*(FARPROC*)&g_pfnGetMonitorInfo = GetProcAddress(hUser32,"GetMonitorInfoA")) != NULL &&
(*(FARPROC*)&g_pfnEnumDisplayDevices = GetProcAddress(hUser32,"EnumDisplayDevicesA")) != NULL
#endif
) {
g_fMultiMonInitDone = TRUE;
return TRUE;
}
else
{
g_pfnGetSystemMetrics = NULL;
g_pfnMonitorFromWindow = NULL;
g_pfnMonitorFromRect = NULL;
g_pfnMonitorFromPoint = NULL;
g_pfnGetMonitorInfo = NULL;
g_pfnEnumDisplayMonitors = NULL;
g_pfnEnumDisplayDevices = NULL;
g_fMultiMonInitDone = TRUE;
return FALSE;
}
}
//-----------------------------------------------------------------------------
//
// fake implementations of Monitor APIs that work with the primary display
// no special parameter validation is made since these run in client code
//
//-----------------------------------------------------------------------------
int WINAPI
xGetSystemMetrics(int nIndex)
{
if (InitMultipleMonitorStubs())
return g_pfnGetSystemMetrics(nIndex);
switch (nIndex)
{
case SM_CMONITORS:
case SM_SAMEDISPLAYFORMAT:
return 1;
case SM_XVIRTUALSCREEN:
case SM_YVIRTUALSCREEN:
return 0;
case SM_CXVIRTUALSCREEN:
nIndex = SM_CXSCREEN;
break;
case SM_CYVIRTUALSCREEN:
nIndex = SM_CYSCREEN;
break;
}
return GetSystemMetrics(nIndex);
}
#define xPRIMARY_MONITOR ((HMONITOR)0x12340042)
HMONITOR WINAPI
xMonitorFromPoint(POINT ptScreenCoords, DWORD dwFlags)
{
if (InitMultipleMonitorStubs())
return g_pfnMonitorFromPoint(ptScreenCoords, dwFlags);
if ((dwFlags & (MONITOR_DEFAULTTOPRIMARY | MONITOR_DEFAULTTONEAREST)) ||
((ptScreenCoords.x >= 0) &&
(ptScreenCoords.x < GetSystemMetrics(SM_CXSCREEN)) &&
(ptScreenCoords.y >= 0) &&
(ptScreenCoords.y < GetSystemMetrics(SM_CYSCREEN))))
{
return xPRIMARY_MONITOR;
}
return NULL;
}
HMONITOR WINAPI
xMonitorFromRect(LPCRECT lprcScreenCoords, DWORD dwFlags)
{
if (InitMultipleMonitorStubs())
return g_pfnMonitorFromRect(lprcScreenCoords, dwFlags);
if ((dwFlags & (MONITOR_DEFAULTTOPRIMARY | MONITOR_DEFAULTTONEAREST)) ||
((lprcScreenCoords->right > 0) &&
(lprcScreenCoords->bottom > 0) &&
(lprcScreenCoords->left < GetSystemMetrics(SM_CXSCREEN)) &&
(lprcScreenCoords->top < GetSystemMetrics(SM_CYSCREEN))))
{
return xPRIMARY_MONITOR;
}
return NULL;
}
HMONITOR WINAPI
xMonitorFromWindow(HWND hWnd, DWORD dwFlags)
{
WINDOWPLACEMENT wp;
if (InitMultipleMonitorStubs())
return g_pfnMonitorFromWindow(hWnd, dwFlags);
if (dwFlags & (MONITOR_DEFAULTTOPRIMARY | MONITOR_DEFAULTTONEAREST))
return xPRIMARY_MONITOR;
if (IsIconic(hWnd) ?
GetWindowPlacement(hWnd, &wp) :
GetWindowRect(hWnd, &wp.rcNormalPosition)) {
return xMonitorFromRect(&wp.rcNormalPosition, dwFlags);
}
return NULL;
}
BOOL WINAPI
xGetMonitorInfo(HMONITOR hMonitor, __inout LPMONITORINFO lpMonitorInfo)
{
RECT rcWork;
if (InitMultipleMonitorStubs())
{
BOOL f = g_pfnGetMonitorInfo(hMonitor, lpMonitorInfo);
#ifdef UNICODE
if (f && !g_fMultimonPlatformNT && (lpMonitorInfo->cbSize >= sizeof(MONITORINFOEX)))
{
MultiByteToWideChar(CP_ACP, 0,
(LPSTR)((MONITORINFOEX*)lpMonitorInfo)->szDevice, -1,
((MONITORINFOEX*)lpMonitorInfo)->szDevice, (sizeof(((MONITORINFOEX*)lpMonitorInfo)->szDevice)/sizeof(TCHAR)));
}
#endif
return f;
}
if ((hMonitor == xPRIMARY_MONITOR) &&
lpMonitorInfo &&
(lpMonitorInfo->cbSize >= sizeof(MONITORINFO)) &&
SystemParametersInfoA(SPI_GETWORKAREA, 0, &rcWork, 0))
{
lpMonitorInfo->rcMonitor.left = 0;
lpMonitorInfo->rcMonitor.top = 0;
lpMonitorInfo->rcMonitor.right = GetSystemMetrics(SM_CXSCREEN);
lpMonitorInfo->rcMonitor.bottom = GetSystemMetrics(SM_CYSCREEN);
lpMonitorInfo->rcWork = rcWork;
lpMonitorInfo->dwFlags = MONITORINFOF_PRIMARY;
if (lpMonitorInfo->cbSize >= sizeof(MONITORINFOEX))
{
#ifdef UNICODE
MultiByteToWideChar(CP_ACP, 0, "DISPLAY", -1, ((MONITORINFOEX*)lpMonitorInfo)->szDevice, (sizeof(((MONITORINFOEX*)lpMonitorInfo)->szDevice)/sizeof(TCHAR)));
#else // UNICODE
#if _MULTIMON_USE_SECURE_CRT
strncpy_s(((MONITORINFOEX*)lpMonitorInfo)->szDevice, (sizeof(((MONITORINFOEX*)lpMonitorInfo)->szDevice)/sizeof(TCHAR)), TEXT("DISPLAY"), (sizeof(((MONITORINFOEX*)lpMonitorInfo)->szDevice)/sizeof(TCHAR)) - 1);
#else
lstrcpyn(((MONITORINFOEX*)lpMonitorInfo)->szDevice, TEXT("DISPLAY"), (sizeof(((MONITORINFOEX*)lpMonitorInfo)->szDevice)/sizeof(TCHAR)));
#endif // _MULTIMON_USE_SECURE_CRT
#endif // UNICODE
}
return TRUE;
}
return FALSE;
}
BOOL WINAPI
xEnumDisplayMonitors(
HDC hdcOptionalForPainting,
LPCRECT lprcEnumMonitorsThatIntersect,
MONITORENUMPROC lpfnEnumProc,
LPARAM dwData)
{
RECT rcLimit;
if (InitMultipleMonitorStubs()) {
return g_pfnEnumDisplayMonitors(
hdcOptionalForPainting,
lprcEnumMonitorsThatIntersect,
lpfnEnumProc,
dwData);
}
if (!lpfnEnumProc)
return FALSE;
rcLimit.left = 0;
rcLimit.top = 0;
rcLimit.right = GetSystemMetrics(SM_CXSCREEN);
rcLimit.bottom = GetSystemMetrics(SM_CYSCREEN);
if (hdcOptionalForPainting)
{
RECT rcClip;
POINT ptOrg;
switch (GetClipBox(hdcOptionalForPainting, &rcClip))
{
default:
if (!GetDCOrgEx(hdcOptionalForPainting, &ptOrg))
return FALSE;
OffsetRect(&rcLimit, -ptOrg.x, -ptOrg.y);
if (IntersectRect(&rcLimit, &rcLimit, &rcClip) &&
(!lprcEnumMonitorsThatIntersect ||
IntersectRect(&rcLimit, &rcLimit, lprcEnumMonitorsThatIntersect))) {
break;
}
//fall thru
case NULLREGION:
return TRUE;
case ERROR:
return FALSE;
}
} else {
if ( lprcEnumMonitorsThatIntersect &&
!IntersectRect(&rcLimit, &rcLimit, lprcEnumMonitorsThatIntersect)) {
return TRUE;
}
}
return lpfnEnumProc(
xPRIMARY_MONITOR,
hdcOptionalForPainting,
&rcLimit,
dwData);
}
BOOL WINAPI
xEnumDisplayDevices(
PVOID Unused,
DWORD iDevNum,
__inout PDISPLAY_DEVICE lpDisplayDevice,
DWORD dwFlags)
{
if (InitMultipleMonitorStubs())
return g_pfnEnumDisplayDevices(Unused, iDevNum, lpDisplayDevice, dwFlags);
if (Unused != NULL)
return FALSE;
if (iDevNum != 0)
return FALSE;
if (lpDisplayDevice == NULL || lpDisplayDevice->cb < sizeof(DISPLAY_DEVICE))
return FALSE;
#ifdef UNICODE
MultiByteToWideChar(CP_ACP, 0, "DISPLAY", -1, lpDisplayDevice->DeviceName, (sizeof(lpDisplayDevice->DeviceName)/sizeof(TCHAR)));
MultiByteToWideChar(CP_ACP, 0, "DISPLAY", -1, lpDisplayDevice->DeviceString, (sizeof(lpDisplayDevice->DeviceString)/sizeof(TCHAR)));
#else // UNICODE
#if _MULTIMON_USE_SECURE_CRT
strncpy_s((LPTSTR)lpDisplayDevice->DeviceName, (sizeof(lpDisplayDevice->DeviceName)/sizeof(TCHAR)), TEXT("DISPLAY"), (sizeof(lpDisplayDevice->DeviceName)/sizeof(TCHAR)) - 1);
strncpy_s((LPTSTR)lpDisplayDevice->DeviceString, (sizeof(lpDisplayDevice->DeviceString)/sizeof(TCHAR)), TEXT("DISPLAY"), (sizeof(lpDisplayDevice->DeviceName)/sizeof(TCHAR)) - 1);
#else
lstrcpyn((LPTSTR)lpDisplayDevice->DeviceName, TEXT("DISPLAY"), (sizeof(lpDisplayDevice->DeviceName)/sizeof(TCHAR)));
lstrcpyn((LPTSTR)lpDisplayDevice->DeviceString, TEXT("DISPLAY"), (sizeof(lpDisplayDevice->DeviceString)/sizeof(TCHAR)));
#endif // _MULTIMON_USE_SECURE_CRT
#endif // UNICODE
lpDisplayDevice->StateFlags = DISPLAY_DEVICE_ATTACHED_TO_DESKTOP | DISPLAY_DEVICE_PRIMARY_DEVICE;
return TRUE;
}
#undef xPRIMARY_MONITOR
#undef COMPILE_MULTIMON_STUBS
#else // COMPILE_MULTIMON_STUBS
extern int WINAPI xGetSystemMetrics(int);
extern HMONITOR WINAPI xMonitorFromWindow(HWND, DWORD);
extern HMONITOR WINAPI xMonitorFromRect(LPCRECT, DWORD);
extern HMONITOR WINAPI xMonitorFromPoint(POINT, DWORD);
extern BOOL WINAPI xGetMonitorInfo(HMONITOR, LPMONITORINFO);
extern BOOL WINAPI xEnumDisplayMonitors(HDC, LPCRECT, MONITORENUMPROC, LPARAM);
extern BOOL WINAPI xEnumDisplayDevices(PVOID, DWORD, PDISPLAY_DEVICE, DWORD);
#endif // COMPILE_MULTIMON_STUBS
//
// build defines that replace the regular APIs with our versions
//
#define GetSystemMetrics xGetSystemMetrics
#define MonitorFromWindow xMonitorFromWindow
#define MonitorFromRect xMonitorFromRect
#define MonitorFromPoint xMonitorFromPoint
#define GetMonitorInfo xGetMonitorInfo
#define EnumDisplayMonitors xEnumDisplayMonitors
#define EnumDisplayDevices xEnumDisplayDevices
#ifdef __cplusplus
}
#endif // __cplusplus
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+22 -7
View File
@@ -5,20 +5,31 @@ endif()
project(tbb)
# 4.0 update 4 - works fine
set(tbb_ver "tbb40_20120408oss")
set(tbb_url "http://threadingbuildingblocks.org/uploads/77/185/4.0%20update%204/tbb40_20120408oss_src.tgz")
set(tbb_md5 "734b356da7fe0ed308741f3e6018251e")
set(tbb_version_file "version_string.ver")
# 4.0 update 3 - build broken
#set(tbb_ver "tbb40_20120201oss")
#set(tbb_url "http://threadingbuildingblocks.org/uploads/77/182/4.0%20update%203/tbb40_20120201oss_src.tgz")
#set(tbb_md5 "4669e7d4adee018de7a7b8b972987218")
#set(tbb_version_file "version_string.tmp")
# 4.0 update 2 - works fine
set(tbb_ver "tbb40_20111130oss")
set(tbb_url "http://threadingbuildingblocks.org/uploads/77/180/4.0%20update%202/tbb40_20111130oss_src.tgz")
set(tbb_md5 "1e6926b21e865e79772119cd44fc3ad8")
#set(tbb_ver "tbb40_20111130oss")
#set(tbb_url "http://threadingbuildingblocks.org/uploads/77/180/4.0%20update%202/tbb40_20111130oss_src.tgz")
#set(tbb_md5 "1e6926b21e865e79772119cd44fc3ad8")
#set(tbb_version_file "version_string.tmp")
#set(tbb_need_GENERIC_DWORD_LOAD_STORE TRUE)
# 4.0 update 1 - works fine
#set(tbb_ver "tbb40_20111003oss")
#set(tbb_url "http://threadingbuildingblocks.org/uploads/77/177/4.0%20update%201/tbb40_20111003oss_src.tgz")
#set(tbb_md5 "7b5d94eb35a563b29ef402e0fd8f15c9")
#set(tbb_version_file "version_string.tmp")
#set(tbb_need_GENERIC_DWORD_LOAD_STORE TRUE)
set(tbb_tarball "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_ver}_src.tgz")
set(tbb_src_dir "${CMAKE_CURRENT_BINARY_DIR}/${tbb_ver}")
@@ -92,16 +103,20 @@ list(APPEND lib_srcs "${tbb_src_dir}/src/rml/client/rml_tbb.cpp")
add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0 #required
-D__TBB_BUILD=1 #required
-D__TBB_SURVIVE_THREAD_SWITCH=0 #no cilk on Android
-D__TBB_USE_GENERIC_DWORD_LOAD_STORE=1 #needed by TBB 4.0 update 1,2; fixed in TBB 4.0 update 3 but it has 2 new problems
-D__TBB_SURVIVE_THREAD_SWITCH=0 #no cilk on Android ?
-DUSE_PTHREAD #required
-DTBB_USE_GCC_BUILTINS=1 #required
-DTBB_USE_DEBUG=0 #just ot be sure
-DTBB_USE_DEBUG=0 #just to be sure
-DTBB_NO_LEGACY=1 #don't need backward compatibility
-DDO_ITT_NOTIFY=0 #it seems that we don't need these notifications
)
add_library(tbb STATIC ${lib_srcs} ${lib_hdrs} "${CMAKE_CURRENT_SOURCE_DIR}/android_additional.h" "${CMAKE_CURRENT_SOURCE_DIR}/version_string.tmp")
if(tbb_need_GENERIC_DWORD_LOAD_STORE)
#needed by TBB 4.0 update 1,2; fixed in TBB 4.0 update 3 but it has 2 new problems
add_definitions(-D__TBB_USE_GENERIC_DWORD_LOAD_STORE=1)
endif()
add_library(tbb STATIC ${lib_srcs} ${lib_hdrs} "${CMAKE_CURRENT_SOURCE_DIR}/android_additional.h" "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_version_file}")
target_link_libraries(tbb c m dl)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -w -include \"${CMAKE_CURRENT_SOURCE_DIR}/android_additional.h\"")
+7 -9
View File
@@ -1,11 +1,9 @@
#define __TBB_VERSION_STRINGS \
"TBB: BUILD_HOST buit as part of OpenCV" ENDL \
"TBB: BUILD_OS crosscompiling" ENDL \
"TBB: BUILD_KERNEL UNKNOWN" ENDL \
"TBB: BUILD_HOST Unknown" ENDL \
"TBB: BUILD_OS Android" ENDL \
"TBB: BUILD_KERNEL Unknown" ENDL \
"TBB: BUILD_GCC gcc version 4.4.3" ENDL \
"TBB: BUILD_GLIBC 2.11.1" ENDL \
"TBB: BUILD_LD " ENDL \
"TBB: BUILD_TARGET on " ENDL \
"TBB: BUILD_COMMAND TBD" ENDL \
#define __TBB_DATETIME "Sun Jan 01 00:00:01 UTC 2012"
"TBB: BUILD_GLIBC Unknown" ENDL \
"TBB: BUILD_LD Unknown" ENDL \
"TBB: BUILD_TARGET Unknown" ENDL \
"TBB: BUILD_COMMAND use cv::getBuildInformation() for details" ENDL \
+9
View File
@@ -0,0 +1,9 @@
#define __TBB_VERSION_STRINGS(N) \
#N": BUILD_HOST Unknown" ENDL \
#N": BUILD_OS Android" ENDL \
#N": BUILD_KERNEL Unknown" ENDL \
#N": BUILD_GCC gcc version 4.4.3" ENDL \
#N": BUILD_GLIBC Unknown" ENDL \
#N": BUILD_LD Unknown" ENDL \
#N": BUILD_TARGET Unknown" ENDL \
#N": BUILD_COMMAND use cv::getBuildInformation() for details" ENDL \
+157 -345
View File
@@ -50,6 +50,7 @@ else()
cmake_minimum_required(VERSION 2.6.3)
endif()
# must go before the project command
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
if(DEFINED CMAKE_BUILD_TYPE AND CMAKE_VERSION VERSION_GREATER "2.8")
set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} )
@@ -59,6 +60,14 @@ project(OpenCV CXX C)
include(cmake/OpenCVUtils.cmake REQUIRED)
# ----------------------------------------------------------------------------
# Break in case of popular CMake configuration mistakes
# ----------------------------------------------------------------------------
if(NOT CMAKE_SIZEOF_VOID_P GREATER 0)
message(FATAL_ERROR "CMake fails to deterimine the bitness of target platform.
Please check your CMake and compiler installation. If you are crosscompiling then ensure that your CMake toolchain file correctly sets the compiler details.")
endif()
# ----------------------------------------------------------------------------
# Detect compiler and target platform architecture
# ----------------------------------------------------------------------------
@@ -109,14 +118,15 @@ OCV_OPTION(WITH_EIGEN "Include Eigen2/Eigen3 support" ON)
OCV_OPTION(WITH_FFMPEG "Include FFMPEG support" ON IF (NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_GSTREAMER "Include Gstreamer support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_GTK "Include GTK support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_IMAGEIO "ImageIO support for OS X" OFF IF APPLE)
OCV_OPTION(WITH_IPP "Include Intel IPP support" OFF IF (MSVC OR X86 OR X86_64) )
OCV_OPTION(WITH_JASPER "Include JPEG2K support" ON IF (NOT IOS) )
OCV_OPTION(WITH_JPEG "Include JPEG support" ON IF (NOT IOS) )
OCV_OPTION(WITH_OPENEXR "Include ILM support via OpenEXR" ON IF (NOT IOS) )
OCV_OPTION(WITH_OPENGL "Include OpenGL support" OFF IF (NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_OPENGL "Include OpenGL support" OFF IF (NOT ANDROID AND NOT IOS AND NOT APPLE) )
OCV_OPTION(WITH_OPENNI "Include OpenNI support" OFF IF (NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_PNG "Include PNG support" ON IF (NOT IOS) )
OCV_OPTION(WITH_PVAPI "Include Prosilica GigE support" ON IF (UNIX AND NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_PVAPI "Include Prosilica GigE support" ON IF (NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_QT "Build with Qt Backend support" OFF IF (NOT ANDROID AND NOT IOS) )
OCV_OPTION(WITH_QUICKTIME "Use QuickTime for Video I/O insted of QTKit" OFF IF APPLE )
OCV_OPTION(WITH_TBB "Include Intel TBB support" OFF IF (NOT IOS) )
@@ -154,10 +164,17 @@ OCV_OPTION(INSTALL_PYTHON_EXAMPLES "Install Python examples" OFF )
OCV_OPTION(INSTALL_ANDROID_EXAMPLES "Install Android examples" OFF IF ANDROID )
OCV_OPTION(INSTALL_TO_MANGLED_PATHS "Enables mangled install paths, that help with side by side installs." OFF IF (UNIX AND NOT ANDROID AND NOT IOS AND BUILD_SHARED_LIBS) )
if(MSVC_IDE OR CMAKE_GENERATOR MATCHES Xcode)
set(ENABLE_SOLUTION_FOLDERS0 ON)
else()
set(ENABLE_SOLUTION_FOLDERS0 OFF)
endif()
# OpenCV build options
# ===================================================
OCV_OPTION(ENABLE_PRECOMPILED_HEADERS "Use precompiled headers" ON IF (NOT IOS) )
OCV_OPTION(ENABLE_SOLUTION_FOLDERS "Solution folder in Visual Studio or in other IDEs" MSVC_IDE IF (CMAKE_VERSION VERSION_GREATER "2.8.0") )
OCV_OPTION(ENABLE_SOLUTION_FOLDERS "Solution folder in Visual Studio or in other IDEs" ${ENABLE_SOLUTION_FOLDERS0} IF (CMAKE_VERSION VERSION_GREATER "2.8.0") )
OCV_OPTION(ENABLE_PROFILING "Enable profiling in the GCC compiler (Add flags: -g -pg)" OFF IF CMAKE_COMPILER_IS_GNUCXX )
OCV_OPTION(ENABLE_OMIT_FRAME_POINTER "Enable -fomit-frame-pointer for GCC" ON IF CMAKE_COMPILER_IS_GNUCXX )
OCV_OPTION(ENABLE_POWERPC "Enable PowerPC for GCC" ON IF (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_SYSTEM_PROCESSOR MATCHES powerpc.*) )
@@ -293,190 +310,58 @@ if(UNIX)
include(cmake/OpenCVFindPkgConfig.cmake OPTIONAL)
include(CheckFunctionExists)
include(CheckIncludeFile)
if(NOT APPLE)
CHECK_INCLUDE_FILE(alloca.h HAVE_ALLOCA_H)
CHECK_FUNCTION_EXISTS(alloca HAVE_ALLOCA)
CHECK_INCLUDE_FILE(unistd.h HAVE_UNISTD_H)
CHECK_INCLUDE_FILE(pthread.h HAVE_LIBPTHREAD)
if(ANDROID)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m log)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR ${CMAKE_SYSTEM_NAME} MATCHES "NetBSD")
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} m pthread)
else()
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m pthread rt)
endif()
else()
add_definitions(-DHAVE_ALLOCA -DHAVE_ALLOCA_H -DHAVE_LIBPTHREAD -DHAVE_UNISTD_H)
endif()
endif()
include(cmake/OpenCVPCHSupport.cmake REQUIRED)
include(cmake/OpenCVModule.cmake REQUIRED)
# ----------------------------------------------------------------------------
# Detect 3rd-party tools and libraries
# Detect 3rd-party libraries
# ----------------------------------------------------------------------------
# IO libraries
include(cmake/OpenCVIOLibs.cmake REQUIRED)
include(cmake/OpenCVFindLibsGrfmt.cmake REQUIRED)
include(cmake/OpenCVFindLibsGUI.cmake REQUIRED)
include(cmake/OpenCVFindLibsVideo.cmake REQUIRED)
include(cmake/OpenCVFindLibsPerf.cmake REQUIRED)
#Graphic libraries
set(HAVE_OPENGL 0)
if(UNIX)
if(NOT APPLE)
if(WITH_GTK)
CHECK_MODULE(gtk+-2.0 HAVE_GTK)
CHECK_MODULE(gthread-2.0 HAVE_GTHREAD)
if(WITH_OPENGL)
CHECK_MODULE(gtkglext-1.0 HAVE_GTKGLEXT)
if(HAVE_GTKGLEXT)
find_package(OpenGL QUIET)
if(OPENGL_FOUND)
set(HAVE_OPENGL 1)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${OPENGL_LIBRARIES})
ocv_include_directories(${OPENGL_INCLUDE_DIR})
endif()
endif()
endif()
else()
set(HAVE_GTK FALSE)
set(HAVE_GTHREAD FALSE)
endif()
if(WITH_GSTREAMER)
CHECK_MODULE(gstreamer-base-0.10 HAVE_GSTREAMER)
CHECK_MODULE(gstreamer-app-0.10 HAVE_GSTREAMER)
CHECK_MODULE(gstreamer-video-0.10 HAVE_GSTREAMER)
else()
set(HAVE_GSTREAMER FALSE)
endif()
endif()
if(WITH_UNICAP)
CHECK_MODULE(libunicap HAVE_UNICAP_)
CHECK_MODULE(libucil HAVE_UNICAP_UCIL)
if(HAVE_UNICAP_ AND HAVE_UNICAP_UCIL)
set(HAVE_UNICAP 1)
endif()
else()
set(HAVE_UNICAP FALSE)
endif()
# ----------------------------------------------------------------------------
# Detect other 3rd-party libraries/tools
# ----------------------------------------------------------------------------
if(WITH_PVAPI)
find_path(PVAPI_INCLUDE_PATH "PvApi.h"
PATHS "/usr/local/include" "/usr/include"
DOC "The path to PvAPI header")
if(PVAPI_INCLUDE_PATH)
set(HAVE_PVAPI 1)
endif()
endif()
set(HAVE_FFMPEG 0)
if(WITH_FFMPEG)
CHECK_MODULE(libavcodec HAVE_FFMPEG_CODEC)
CHECK_MODULE(libavformat HAVE_FFMPEG_FORMAT)
CHECK_MODULE(libavutil HAVE_FFMPEG_UTIL)
CHECK_MODULE(libswscale HAVE_FFMPEG_SWSCALE)
CHECK_INCLUDE_FILE(libavformat/avformat.h HAVE_GENTOO_FFMPEG)
CHECK_INCLUDE_FILE(ffmpeg/avformat.h HAVE_FFMPEG_FFMPEG)
if(NOT HAVE_GENTOO_FFMPEG AND NOT HAVE_FFMPEG_FFMPEG)
if(EXISTS /usr/include/ffmpeg/libavformat/avformat.h OR HAVE_FFMPEG_SWSCALE)
set(HAVE_GENTOO_FFMPEG 1)
endif()
endif()
if(HAVE_FFMPEG_CODEC AND HAVE_FFMPEG_FORMAT AND HAVE_FFMPEG_UTIL)
if(HAVE_FFMPEG_SWSCALE)
set(HAVE_FFMPEG 1)
endif()
endif()
# Find the bzip2 library because it is required on some systems
FIND_LIBRARY(BZIP2_LIBRARIES NAMES bz2 bzip2)
if(NOT BZIP2_LIBRARIES)
# Do an other trial
FIND_FILE(BZIP2_LIBRARIES NAMES libbz2.so.1 PATHS /lib)
endif()
endif()
if(WITH_1394)
CHECK_MODULE(libdc1394-2 HAVE_DC1394_2)
if(NOT HAVE_DC1394_2)
CHECK_MODULE(libdc1394 HAVE_DC1394)
endif()
else()
set(HAVE_DC1394_2 FALSE)
set(HAVE_DC1394 FALSE)
endif()
if(NOT APPLE)
CHECK_INCLUDE_FILE(alloca.h HAVE_ALLOCA_H)
CHECK_FUNCTION_EXISTS(alloca HAVE_ALLOCA)
CHECK_INCLUDE_FILE(unistd.h HAVE_UNISTD_H)
CHECK_INCLUDE_FILE(pthread.h HAVE_LIBPTHREAD)
if(WITH_XINE)
CHECK_MODULE(libxine HAVE_XINE)
else()
set(HAVE_XINE FALSE)
endif()
if(WITH_V4L)
CHECK_MODULE(libv4l1 HAVE_LIBV4L)
CHECK_INCLUDE_FILE(linux/videodev.h HAVE_CAMV4L)
CHECK_INCLUDE_FILE(linux/videodev2.h HAVE_CAMV4L2)
else()
set(HAVE_LIBV4L FALSE)
set(HAVE_CAMV4L FALSE)
set(HAVE_CAMV4L2 FALSE)
endif()
if(ANDROID)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m log)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR ${CMAKE_SYSTEM_NAME} MATCHES "NetBSD")
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} m pthread)
else()
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m pthread rt)
endif()
else()
add_definitions(-DHAVE_ALLOCA -DHAVE_ALLOCA_H -DHAVE_LIBPTHREAD -DHAVE_UNISTD_H)
endif()
endif()
if(APPLE AND WITH_FFMPEG)
set(FFMPEG_DEFAULT_INCLUDE_DIRS "/usr/local/include/" "/usr/include/" "opt/include/")
find_path(FFMPEG_INCLUDE_DIR "libavformat/avformat.h" PATHS ${FFMPEG_DEFAULT_INCLUDE_DIRS} DOC "The path to FFMPEG headers")
if(FFMPEG_INCLUDE_DIR)
set(HAVE_GENTOO_FFMPEG 1)
set(FFMPEG_LIB_DIR "${FFMPEG_INCLUDE_DIR}/../lib" CACHE PATH "Full path of FFMPEG library directory")
if(EXISTS "${FFMPEG_LIB_DIR}/libavcodec.a")
set(HAVE_FFMPEG_CODEC 1)
set(ALIASOF_libavcodec_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libavformat.a")
set(HAVE_FFMPEG_FORMAT 1)
set(ALIASOF_libavformat_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libavutil.a")
set(HAVE_FFMPEG_UTIL 1)
set(ALIASOF_libavutil_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libswscale.a")
ocv_include_directories(${FFMPEG_INCLUDE_DIR})
set(HAVE_FFMPEG_SWSCALE 1)
set(ALIASOF_libswscale_VERSION "Unknown")
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} "${FFMPEG_LIB_DIR}/libavcodec.a"
"${FFMPEG_LIB_DIR}/libavformat.a" "${FFMPEG_LIB_DIR}/libavutil.a"
"${FFMPEG_LIB_DIR}/libswscale.a")
set(HAVE_FFMPEG 1)
endif()
endif()
endif()
endif()
endif()
endif()
if(WIN32 AND WITH_FFMPEG)
include(3rdparty/ffmpeg/ffmpeg_version.cmake REQUIRED)
endif()
#################### LATEX for dpf documentation ##################
# --- LATEX for pdf documentation ---
if(BUILD_DOCS)
include(cmake/OpenCVFindLATEX.cmake REQUIRED)
endif()
endif(BUILD_DOCS)
########################## Python Support #########################
# --- Python Support ---
include(cmake/OpenCVDetectPython.cmake REQUIRED)
########################### Java Support ##########################
# --- Java Support ---
if(ANDROID)
include(cmake/OpenCVDetectApacheAnt.cmake REQUIRED)
include(cmake/OpenCVDetectAndroidSDK.cmake REQUIRED)
if(NOT ANDROID_TOOLS_Pkg_Revision GREATER 13)
message(WARNING "OpenCV requires Android SDK tools revision 14 or newer. Otherwise tests and samples will no be compiled.")
endif()
endif()
endif(ANDROID)
if(ANDROID AND ANDROID_EXECUTABLE AND ANT_EXECUTABLE AND (ANT_VERSION VERSION_GREATER 1.7) AND (ANDROID_TOOLS_Pkg_Revision GREATER 13))
SET(CAN_BUILD_ANDROID_PROJECTS TRUE)
@@ -484,115 +369,6 @@ else()
SET(CAN_BUILD_ANDROID_PROJECTS FALSE)
endif()
############################### QT ################################
set(HAVE_QT 0)
set(HAVE_QT_OPENGL 0)
if(WITH_QT)
find_package(Qt4)
if(QT4_FOUND)
set(HAVE_QT 1)
add_definitions(-DHAVE_QT) #We need to define te macro this way, using cvconfig.h.cmake does not work
if(WITH_OPENGL)
find_package (OpenGL QUIET)
if(QT_QTOPENGL_FOUND AND OPENGL_FOUND)
set(HAVE_OPENGL 1)
set(HAVE_QT_OPENGL 1)
add_definitions(-DHAVE_QT_OPENGL)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${OPENGL_LIBRARIES})
endif()
endif()
endif()
endif()
############################### TBB ################################
if(WITH_TBB)
include(cmake/OpenCVDetectTBB.cmake REQUIRED)
endif()
############################ Intel IPP #############################
set(IPP_FOUND)
if(WITH_IPP)
include(cmake/OpenCVFindIPP.cmake)
endif()
if(IPP_FOUND)
add_definitions(-DHAVE_IPP)
ocv_include_directories(${IPP_INCLUDE_DIRS})
link_directories(${IPP_LIBRARY_DIRS})
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${IPP_LIBRARIES})
endif()
############################### CUDA ################################
if(WITH_CUDA)
include(cmake/OpenCVDetectCUDA.cmake REQUIRED)
endif()
############################### OpenNI ################################
set(HAVE_OPENNI FALSE)
set(HAVE_OPENNI_PRIME_SENSOR_MODULE FALSE)
if(WITH_OPENNI)
include(cmake/OpenCVFindOpenNI.cmake)
endif()
############################### XIMEA ################################
set(HAVE_XIMEA FALSE)
if(WITH_XIMEA)
include(cmake/OpenCVFindXimea.cmake)
endif()
if(XIMEA_FOUND)
set(HAVE_XIMEA TRUE)
endif()
############################## Eigen ##############################
if(WITH_EIGEN)
find_path(EIGEN_INCLUDE_PATH "Eigen/Core"
PATHS "/usr/local/include/eigen2" "/opt/include/eigen2" "/usr/include/eigen2"
"/usr/local/include/eigen3" "/opt/include/eigen3" "/usr/include/eigen3"
DOC "The path to Eigen2/Eigen3 headers")
if(EIGEN_INCLUDE_PATH)
ocv_include_directories(${EIGEN_INCLUDE_PATH})
ocv_parse_header("${EIGEN_INCLUDE_PATH}/Eigen/src/Core/util/Macros.h" EIGEN_VERSION_LINES EIGEN_WORLD_VERSION EIGEN_MAJOR_VERSION EIGEN_MINOR_VERSION)
set(HAVE_EIGEN 1)
endif()
endif()
################## Extra HighGUI libs on Windows ###################
if(WIN32)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} comctl32 gdi32 ole32)
if(WITH_VIDEOINPUT)
set(HAVE_VIDEOINPUT 1)
endif()
if(MSVC)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} vfw32)
endif()
if(MINGW)
if(MINGW64)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} msvfw32 avifil32 avicap32 winmm)
else()
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} vfw32 winmm)
endif()
endif()
if(WITH_OPENGL AND NOT HAVE_QT_OPENGL)
find_package(OpenGL QUIET)
if(OPENGL_FOUND)
set(HAVE_OPENGL 1)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${OPENGL_LIBRARIES})
ocv_include_directories(${OPENGL_INCLUDE_DIR})
endif()
endif()
endif()
# ----------------------------------------------------------------------------
# Solution folders:
@@ -658,12 +434,12 @@ if(OPENCV_SVNVERSION)
status("Version control:" ${OPENCV_SVNVERSION})
endif()
#build platform
# ========================== build platform ==========================
status("")
status(" Platform:")
status(" Host:" ${CMAKE_HOST_SYSTEM_NAME} ${CMAKE_HOST_SYSTEM_VERSION} ${CMAKE_HOST_SYSTEM_PROCESSOR})
if(CMAKE_CROSSCOMPILING)
status(" Target:" ${CMAKE_SYSTEM_NAME} ${CMAKE_SYSTEM_VERSION} ${CMAKE_SYSTEM_PROCESSOR})
status(" Target:" ${CMAKE_SYSTEM_NAME} ${CMAKE_SYSTEM_VERSION} ${CMAKE_SYSTEM_PROCESSOR})
endif()
status(" CMake:" ${CMAKE_VERSION})
status(" CMake generator:" ${CMAKE_GENERATOR})
@@ -678,7 +454,7 @@ if(NOT CMAKE_GENERATOR MATCHES "Xcode|Visual Studio")
status(" Configuration:" ${CMAKE_BUILD_TYPE})
endif()
# C/C++ options
# ========================== C/C++ options ==========================
status("")
status(" C/C++:")
status(" Built as dynamic libs?:" BUILD_SHARED_LIBS THEN YES ELSE NO)
@@ -696,7 +472,7 @@ else()
status(" Linker flags (Debug):" ${CMAKE_SHARED_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS_DEBUG})
endif()
# OpenCV modules
# ========================== OpenCV modules ==========================
status("")
status(" OpenCV modules:")
string(REPLACE "opencv_" "" OPENCV_MODULES_BUILD_ST "${OPENCV_MODULES_BUILD}")
@@ -715,11 +491,11 @@ endforeach()
string(REPLACE "opencv_" "" OPENCV_MODULES_DISABLED_AUTO_ST "${OPENCV_MODULES_DISABLED_AUTO_ST}")
status(" To be built:" OPENCV_MODULES_BUILD THEN ${OPENCV_MODULES_BUILD_ST} ELSE "-")
status(" Disabled by user:" OPENCV_MODULES_DISABLED_USER THEN ${OPENCV_MODULES_DISABLED_USER_ST} ELSE "-")
status(" Disabled:" OPENCV_MODULES_DISABLED_USER THEN ${OPENCV_MODULES_DISABLED_USER_ST} ELSE "-")
status(" Disabled by dependency:" OPENCV_MODULES_DISABLED_AUTO THEN ${OPENCV_MODULES_DISABLED_AUTO_ST} ELSE "-")
status(" Unavailable:" OPENCV_MODULES_DISABLED_FORCE THEN ${OPENCV_MODULES_DISABLED_FORCE_ST} ELSE "-")
# Android extra
# ========================== Android details ==========================
if(ANDROID)
status("")
status(" Android: ")
@@ -735,14 +511,17 @@ if(ANDROID)
status(" ant:" ANT_EXECUTABLE THEN "${ANT_EXECUTABLE} (ver ${ANT_VERSION})" ELSE NO)
endif()
#YV
# ========================== GUI ==========================
status("")
status(" GUI: ")
if (HAVE_QT)
if(HAVE_QT)
status(" QT 4.x:" HAVE_QT THEN "YES (ver ${QT_VERSION_MAJOR}.${QT_VERSION_MINOR}.${QT_VERSION_PATCH} ${QT_EDITION})" ELSE NO)
status(" QT OpenGL support:" HAVE_QT_OPENGL THEN "YES (${QT_QTOPENGL_LIBRARY})" ELSE NO)
else()
if(DEFINED WITH_QT)
status(" QT 4.x:" NO)
endif()
if(WIN32)
status(" Win32 UI:" YES)
else()
@@ -762,7 +541,7 @@ endif()
status(" OpenGL support:" HAVE_OPENGL THEN "YES (${OPENGL_LIBRARIES})" ELSE NO)
# media
# ========================== MEDIA IO ==========================
status("")
status(" Media I/O: ")
status(" ZLib:" BUILD_ZLIB THEN "build (ver ${ZLIB_VERSION_STRING})" ELSE "${ZLIB_LIBRARY} (ver ${ZLIB_VERSION_STRING})")
@@ -793,82 +572,120 @@ else()
endif()
status(" OpenEXR:" WITH_OPENEXR AND OPENEXR_FOUND THEN "${OPENEXR_LIBRARIES} (ver ${OPENEXR_VERSION})" ELSE NO)
status(" OpenNI:" HAVE_OPENNI THEN "YES (ver ${OPENNI_VERSION_STRING}, build ${OPENNI_VERSION_BUILD})" ELSE NO)
status(" OpenNI PrimeSensor Modules:"
HAVE_OPENNI_PRIME_SENSOR_MODULE THEN "YES (${OPENNI_PRIME_SENSOR_MODULE})" ELSE NO)
if(WIN32)
status(" XIMEA:" HAVE_XIMEA THEN YES ELSE NO)
endif()
# video
# ========================== VIDEO IO ==========================
status("")
if(UNIX AND NOT APPLE)
status(" Video I/O:")
status(" Video I/O:")
if(DEFINED WITH_1394)
status(" DC1394 1.x:" HAVE_DC1394 THEN "YES (ver ${ALIASOF_libdc1394_VERSION})" ELSE NO)
status(" DC1394 2.x:" HAVE_DC1394_2 THEN "YES (ver ${ALIASOF_libdc1394-2_VERSION})" ELSE NO)
status(" GStreamer:" HAVE_GSTREAMER THEN "" ELSE NO)
endif(DEFINED WITH_1394)
if(ANDROID)
if(HAVE_opencv_androidcamera)
status(" AndroidNativeCamera:" BUILD_ANDROID_CAMERA_WRAPPER
THEN "YES, build for Android${ANDROID_VERSION}" ELSE "YES, use prebuilt libraries")
else()
status(" AndroidNativeCamera:" "NO (native camera requires Android API level 8 or higher)")
endif()
endif()
if(DEFINED WITH_AVFOUNDATION)
status(" AVFoundation:" WITH_AVFOUNDATION THEN YES ELSE NO)
endif(DEFINED WITH_AVFOUNDATION)
if(DEFINED WITH_FFMPEG)
if(WIN32)
status(" FFMPEG:" WITH_FFMPEG THEN "YES (prebuilt binaries)" ELSE NO)
else()
status(" FFMPEG:" HAVE_FFMPEG THEN YES ELSE NO)
endif()
status(" codec:" HAVE_FFMPEG_CODEC THEN "YES (ver ${ALIASOF_libavcodec_VERSION})" ELSE NO)
status(" format:" HAVE_FFMPEG_FORMAT THEN "YES (ver ${ALIASOF_libavformat_VERSION})" ELSE NO)
status(" util:" HAVE_FFMPEG_UTIL THEN "YES (ver ${ALIASOF_libavutil_VERSION})" ELSE NO)
status(" swscale:" HAVE_FFMPEG_SWSCALE THEN "YES (ver ${ALIASOF_libswscale_VERSION})" ELSE NO)
status(" gentoo-style:" HAVE_GENTOO_FFMPEG THEN YES ELSE NO)
endif(DEFINED WITH_FFMPEG)
if(DEFINED WITH_GSTREAMER)
status(" GStreamer:" HAVE_GSTREAMER THEN "" ELSE NO)
if(HAVE_GSTREAMER)
status(" base:" "YES (ver ${ALIASOF_gstreamer-base-0.10_VERSION})")
status(" app:" "YES (ver ${ALIASOF_gstreamer-app-0.10_VERSION})")
status(" video:" "YES (ver ${ALIASOF_gstreamer-video-0.10_VERSION})")
endif()
status(" UniCap:" HAVE_UNICAP THEN "YES (ver ${ALIASOF_libunicap_VERSION})" ELSE NO)
status(" UniCap ucil:" HAVE_UNICAP_UCIL THEN "YES (ver ${ALIASOF_libucil_VERSION})" ELSE NO)
status(" PvAPI:" HAVE_PVAPI THEN YES ELSE NO)
endif(DEFINED WITH_GSTREAMER)
if(DEFINED WITH_OPENNI)
status(" OpenNI:" HAVE_OPENNI THEN "YES (ver ${OPENNI_VERSION_STRING}, build ${OPENNI_VERSION_BUILD})"
ELSE NO)
status(" OpenNI PrimeSensor Modules:" HAVE_OPENNI_PRIME_SENSOR_MODULE
THEN "YES (${OPENNI_PRIME_SENSOR_MODULE})" ELSE NO)
endif(DEFINED WITH_OPENNI)
if(DEFINED WITH_PVAPI)
status(" PvAPI:" HAVE_PVAPI THEN YES ELSE NO)
endif(DEFINED WITH_PVAPI)
if(DEFINED WITH_QUICKTIME)
status(" QuickTime:" WITH_QUICKTIME THEN YES ELSE NO)
status(" QTKit:" WITH_QUICKTIME THEN NO ELSE YES)
endif(DEFINED WITH_QUICKTIME)
if(DEFINED WITH_UNICAP)
status(" UniCap:" HAVE_UNICAP THEN "YES (ver ${ALIASOF_libunicap_VERSION})" ELSE NO)
status(" UniCap ucil:" HAVE_UNICAP_UCIL THEN "YES (ver ${ALIASOF_libucil_VERSION})" ELSE NO)
endif(DEFINED WITH_UNICAP)
if(DEFINED WITH_V4L)
if(HAVE_CAMV4L)
set(HAVE_CAMV4L_STR "YES")
else()
set(HAVE_CAMV4L_STR "NO")
endif()
if(HAVE_CAMV4L2)
if(HAVE_CAMV4L2)
set(HAVE_CAMV4L2_STR "YES")
else()
set(HAVE_CAMV4L2_STR "NO")
endif()
status(" V4L/V4L2:" HAVE_LIBV4L THEN "Using libv4l (ver ${ALIASOF_libv4l1_VERSION})" ELSE "${HAVE_CAMV4L_STR}/${HAVE_CAMV4L2_STR}")
status(" Xine:" HAVE_XINE THEN "YES (ver ${ALIASOF_libxine_VERSION})" ELSE NO)
status(" V4L/V4L2:" HAVE_LIBV4L THEN "Using libv4l (ver ${ALIASOF_libv4l1_VERSION})"
ELSE "${HAVE_CAMV4L_STR}/${HAVE_CAMV4L2_STR}")
endif(DEFINED WITH_V4L)
if(ANDROID)
if(HAVE_opencv_androidcamera)
status(" AndroidNativeCamera:" BUILD_ANDROID_CAMERA_WRAPPER THEN "YES, build for Android ${ANDROID_VERSION}" ELSE "YES, use prebuilt libraries")
else()
status(" AndroidNativeCamera:" "NO (native camera requires Android API level 8 or higher)")
endif()
endif()
elseif(APPLE)
if(NOT IOS)
status(" Video I/O:" WITH_QUICKTIME THEN QuickTime ELSE QTKit)
else()
status(" Video I/O: AVFoundation")
endif()
elseif(WIN32)
status(" Video I/O:" HAVE_VIDEOINPUT THEN DirectShow ELSE NO)
endif()
if(DEFINED WITH_VIDEOINPUT)
status(" DirectShow:" HAVE_VIDEOINPUT THEN YES ELSE NO)
endif(DEFINED WITH_VIDEOINPUT)
if(WIN32)
status(" FFMPEG:" WITH_FFMPEG THEN "YES (prebuilt binaries)" ELSE NO)
else()
status(" FFMPEG:" HAVE_FFMPEG THEN YES ELSE NO)
endif()
status(" codec:" HAVE_FFMPEG_CODEC THEN "YES (ver ${ALIASOF_libavcodec_VERSION})" ELSE NO)
status(" format:" HAVE_FFMPEG_FORMAT THEN "YES (ver ${ALIASOF_libavformat_VERSION})" ELSE NO)
status(" util:" HAVE_FFMPEG_UTIL THEN "YES (ver ${ALIASOF_libavutil_VERSION})" ELSE NO)
status(" swscale:" HAVE_FFMPEG_SWSCALE THEN "YES (ver ${ALIASOF_libswscale_VERSION})" ELSE NO)
status(" gentoo-style:" HAVE_GENTOO_FFMPEG THEN YES ELSE NO)
if(DEFINED WITH_XIMEA)
status(" XIMEA:" HAVE_XIMEA THEN YES ELSE NO)
endif(DEFINED WITH_XIMEA)
# Other third-party libraries
if(DEFINED WITH_XINE)
status(" Xine:" HAVE_XINE THEN "YES (ver ${ALIASOF_libxine_VERSION})" ELSE NO)
endif(DEFINED WITH_XINE)
# ========================== Other third-party libraries ==========================
status("")
status(" Other third-party libraries:")
if(WITH_IPP AND IPP_FOUND)
status(" Use IPP:" "${IPP_LATEST_VERSION_STR} [${IPP_LATEST_VERSION_MAJOR}.${IPP_LATEST_VERSION_MINOR}.${IPP_LATEST_VERSION_BUILD}]")
status(" at:" "${IPP_ROOT_DIR}")
else()
status(" Use IPP:" WITH_IPP AND NOT IPP_FOUND THEN "IPP not found" ELSE NO)
endif()
if(DEFINED WITH_IPP)
if(WITH_IPP AND IPP_FOUND)
status(" Use IPP:" "${IPP_LATEST_VERSION_STR} [${IPP_LATEST_VERSION_MAJOR}.${IPP_LATEST_VERSION_MINOR}.${IPP_LATEST_VERSION_BUILD}]")
status(" at:" "${IPP_ROOT_DIR}")
else()
status(" Use IPP:" WITH_IPP AND NOT IPP_FOUND THEN "IPP not found" ELSE NO)
endif()
endif(DEFINED WITH_IPP)
if(DEFINED WITH_TBB)
status(" Use TBB:" HAVE_TBB THEN "YES (ver ${TBB_VERSION_MAJOR}.${TBB_VERSION_MINOR} interface ${TBB_INTERFACE_VERSION})" ELSE NO)
endif(DEFINED WITH_TBB)
if(DEFINED WITH_CUDA)
status(" Use Cuda:" HAVE_CUDA THEN "YES (ver ${CUDA_VERSION_STRING})" ELSE NO)
endif(DEFINED WITH_CUDA)
status(" Use TBB:" HAVE_TBB THEN "YES (ver ${TBB_VERSION_MAJOR}.${TBB_VERSION_MINOR} interface ${TBB_INTERFACE_VERSION})" ELSE NO)
status(" Use Cuda:" HAVE_CUDA THEN "YES (ver ${CUDA_VERSION_STRING})" ELSE NO)
status(" Use Eigen:" HAVE_EIGEN THEN "YES (ver ${EIGEN_WORLD_VERSION}.${EIGEN_MAJOR_VERSION}.${EIGEN_MINOR_VERSION})" ELSE NO)
if(HAVE_CUDA)
@@ -882,7 +699,7 @@ if(HAVE_CUDA)
status(" NVIDIA GPU features:" ${OPENCV_CUDA_ARCH_FEATURES})
endif()
# interfaces to other languages
# ========================== python ==========================
status("")
status(" Python:")
status(" Interpreter:" PYTHON_EXECUTABLE THEN "${PYTHON_EXECUTABLE} (ver ${PYTHON_VERSION_FULL})" ELSE NO)
@@ -896,12 +713,7 @@ if(BUILD_opencv_python)
status(" packages path:" PYTHON_EXECUTABLE THEN "${PYTHON_PACKAGES_PATH}" ELSE "-")
endif()
if(BUILD_opencv_java)
status("")
status(" Java:" HAVE_opencv_java THEN YES ELSE NO)
endif()
# documentation
# ========================== documentation ==========================
if(BUILD_DOCS)
status("")
status(" Documentation:")
@@ -914,7 +726,7 @@ if(BUILD_DOCS)
status(" PdfLaTeX compiler:" PDFLATEX_COMPILER THEN "${PDFLATEX_COMPILER}" ELSE NO)
endif()
# samples and tests
# ========================== samples and tests ==========================
status("")
status(" Tests and samples:")
status(" Tests:" BUILD_TESTS AND HAVE_opencv_ts THEN YES ELSE NO)
@@ -922,11 +734,11 @@ status(" Performance tests:" BUILD_PERF_TESTS AND HAVE_opencv_ts THEN YES EL
status(" Examples:" BUILD_EXAMPLES THEN YES ELSE NO)
if(ANDROID)
status(" Android tests:" BUILD_TESTS AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO)
status(" Android examples:" BUILD_ANDROID_EXAMPLES THEN YES ELSE NO)
status(" Android tests:" BUILD_TESTS AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO)
status(" Android examples:" BUILD_ANDROID_EXAMPLES AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO)
endif()
#auxiliary
# ========================== auxiliary ==========================
status("")
status(" Install path:" "${CMAKE_INSTALL_PREFIX}")
status("")
+87 -57
View File
@@ -1,5 +1,5 @@
# ------------------------------------------------------------------------------
# Android CMake toolchain file, for use with the Android NDK r5-r7
# Android CMake toolchain file, for use with the Android NDK r5-r8
# Requires cmake 2.6.3 or newer (2.8.3 or newer is recommended).
# See home page: http://code.google.com/p/android-cmake/
#
@@ -20,7 +20,7 @@
#
# Usage Windows:
# You need native port of make to build your project.
# Android NDK r7 already has make.exe on board.
# Android NDK r7 (or newer) already has make.exe on board.
# For older NDK you have to install it separately.
# For example, this one: http://gnuwin32.sourceforge.net/packages/make.htm
#
@@ -177,6 +177,9 @@
# [+] updated for NDK r7c
# [~] fixed most of problems with compiler/linker flags and caching
# [+] added option ANDROID_FUNCTION_LEVEL_LINKING
# - modified May 2012
# [+] updated for NDK r8
# [+] added mips architecture support
# ------------------------------------------------------------------------------
cmake_minimum_required( VERSION 2.6.3 )
@@ -186,7 +189,8 @@ if( DEFINED CMAKE_CROSSCOMPILING )
return()
endif()
if( PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" )
get_property(_CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE)
if( _CMAKE_IN_TRY_COMPILE )
include( "${CMAKE_CURRENT_SOURCE_DIR}/../android.toolchain.config.cmake" OPTIONAL )
endif()
@@ -195,7 +199,7 @@ set( CMAKE_SYSTEM_NAME Linux )
#this one not so much
set( CMAKE_SYSTEM_VERSION 1 )
set( ANDROID_SUPPORTED_NDK_VERSIONS ${ANDROID_EXTRA_NDK_VERSIONS} -r7c -r7b -r7 -r6b -r6 -r5c -r5b -r5 "" )
set( ANDROID_SUPPORTED_NDK_VERSIONS ${ANDROID_EXTRA_NDK_VERSIONS} -r8 -r7c -r7b -r7 -r6b -r6 -r5c -r5b -r5 "" )
if(NOT DEFINED ANDROID_NDK_SEARCH_PATHS)
if( CMAKE_HOST_WIN32 )
file( TO_CMAKE_PATH "$ENV{PROGRAMFILES}" ANDROID_NDK_SEARCH_PATHS )
@@ -211,9 +215,11 @@ endif()
set( ANDROID_SUPPORTED_ABIS_arm "armeabi-v7a;armeabi;armeabi-v7a with NEON;armeabi-v7a with VFPV3;armeabi-v6 with VFP" )
set( ANDROID_SUPPORTED_ABIS_x86 "x86" )
set( ANDROID_SUPPORTED_ABIS_mipsel "mips" )
set( ANDROID_DEFAULT_NDK_API_LEVEL 8 )
set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 9 )
set( ANDROID_DEFAULT_NDK_API_LEVEL_mips 9 )
macro( __LIST_FILTER listvar regex )
@@ -432,6 +438,7 @@ endif()
#get all the details about standalone toolchain
if( BUILD_WITH_STANDALONE_TOOLCHAIN )
__DETECT_NATIVE_API_LEVEL( ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h" )
set( ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} )
set( __availableToolchains "standalone" )
__DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" )
if( NOT __availableToolchainMachines )
@@ -441,6 +448,8 @@ if( BUILD_WITH_STANDALONE_TOOLCHAIN )
set( __availableToolchainArchs "x86" )
elseif( __availableToolchainMachines MATCHES arm )
set( __availableToolchainArchs "arm" )
elseif( __availableToolchainMachines MATCHES mipsel )
set( __availableToolchainArchs "mipsel" )
endif()
if( ANDROID_COMPILER_VERSION )
#do not run gcc every time because it is relatevely expencive
@@ -513,16 +522,25 @@ if( ANDROID_ABI STREQUAL "x86" )
set( X86 true )
set( ANDROID_NDK_ABI_NAME "x86" )
set( ANDROID_ARCH_NAME "x86" )
set( ANDROID_ARCH_FULLNAME "x86" )
set( CMAKE_SYSTEM_PROCESSOR "i686" )
elseif( ANDROID_ABI STREQUAL "mips" )
set( MIPS true )
set( ANDROID_NDK_ABI_NAME "mips" )
set( ANDROID_ARCH_NAME "mips" )
set( ANDROID_ARCH_FULLNAME "mipsel" )
set( CMAKE_SYSTEM_PROCESSOR "mips" )
elseif( ANDROID_ABI STREQUAL "armeabi" )
set( ARMEABI true )
set( ANDROID_NDK_ABI_NAME "armeabi" )
set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv5te" )
elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" )
set( ARMEABI_V6 true )
set( ANDROID_NDK_ABI_NAME "armeabi" )
set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv6" )
#need always fallback to older platform
set( ARMEABI true )
@@ -530,17 +548,20 @@ elseif( ANDROID_ABI STREQUAL "armeabi-v7a")
set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" )
set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
set( VFPV3 true )
elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" )
set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
set( VFPV3 true )
set( NEON true )
@@ -554,10 +575,10 @@ if( CMAKE_BINARY_DIR AND EXISTS "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMa
file( APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" "SET(CMAKE_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")\n" )
endif()
set( ANDROID_SUPPORTED_ABIS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_NAME}} CACHE INTERNAL "ANDROID_ABI can be changed only to one of these ABIs. Changing to any other ABI requires to reset cmake cache." )
set( ANDROID_SUPPORTED_ABIS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} CACHE INTERNAL "ANDROID_ABI can be changed only to one of these ABIs. Changing to any other ABI requires to reset cmake cache." )
if( CMAKE_VERSION VERSION_GREATER "2.8" )
list( SORT ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_NAME} )
set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_NAME}} )
list( SORT ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME} )
set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} )
endif()
if( ANDROID_ARCH_NAME STREQUAL "arm" AND NOT ARMEABI_V6 )
@@ -575,7 +596,7 @@ if( ANDROID_TOOLCHAIN_NAME )
message( FATAL_ERROR "Previously selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is missing. You need to remove CMakeCache.txt and rerun cmake manually to change the toolchain" )
endif()
list( GET __availableToolchainArchs ${__toolchainIdx} __toolchainArch )
if( NOT __toolchainArch STREQUAL ANDROID_ARCH_NAME )
if( NOT __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME )
message( SEND_ERROR "Previously selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is not able to compile binaries for the \"${ANDROID_ARCH_NAME}\" platform." )
endif()
else()
@@ -586,7 +607,7 @@ else()
math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" )
foreach( __idx RANGE ${__availableToolchainsCount} )
list( GET __availableToolchainArchs ${__idx} __toolchainArch )
if( __toolchainArch STREQUAL ANDROID_ARCH_NAME )
if( __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME )
list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion )
if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion )
set( __toolchainMaxVersion "${__toolchainVersion}" )
@@ -614,7 +635,7 @@ unset( __availableToolchainArchs )
unset( __availableToolchainCompilerVersions )
#choose native API level
__INIT_VARIABLE( ANDROID_NATIVE_API_LEVEL ENV_ANDROID_NATIVE_API_LEVEL ANDROID_API_LEVEL ENV_ANDROID_API_LEVEL ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME} ANDROID_DEFAULT_NDK_API_LEVEL )
__INIT_VARIABLE( ANDROID_NATIVE_API_LEVEL ENV_ANDROID_NATIVE_API_LEVEL ANDROID_API_LEVEL ENV_ANDROID_API_LEVEL ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME} ANDROID_DEFAULT_NDK_API_LEVEL )
string( REGEX MATCH "[0-9]+" ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" )
#validate
list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx )
@@ -745,32 +766,30 @@ set( CMAKE_COMPILER_IS_GNUASM 1)
# NDK flags
if( ARMEABI OR ARMEABI_V7A )
# NDK also defines -ffunction-sections -funwind-tables but they result in worse OpenCV performance
set( CMAKE_CXX_FLAGS "-fPIC -Wno-psabi" )
set( CMAKE_C_FLAGS "-fPIC -Wno-psabi" )
if( ANDROID_USE_STLPORT )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions" )
else()
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -frtti -fexceptions" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fexceptions" )
endif()
set( _CMAKE_CXX_FLAGS "-fPIC -Wno-psabi" )
set( _CMAKE_C_FLAGS "-fPIC -Wno-psabi" )
remove_definitions( -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ )
add_definitions( -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ )
# extra arm-specific flags
set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" )
elseif( X86 )
set( CMAKE_CXX_FLAGS "-funwind-tables" )
set( CMAKE_C_FLAGS "-funwind-tables" )
if( ANDROID_USE_STLPORT )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions" )
else()
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -frtti -fexceptions" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fexceptions" )
endif()
set( _CMAKE_CXX_FLAGS "-funwind-tables" )
set( _CMAKE_C_FLAGS "-funwind-tables" )
elseif( MIPS )
set( _CMAKE_CXX_FLAGS "-fpic -Wno-psabi -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
set( _CMAKE_CXX_FLAGS "-fpic -Wno-psabi -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" )
else()
set( CMAKE_CXX_FLAGS "" )
set( CMAKE_C_FLAGS "" )
set( _CMAKE_CXX_FLAGS "" )
set( _CMAKE_C_FLAGS "" )
endif()
if( ANDROID_USE_STLPORT )
set( _CMAKE_CXX_FLAGS "${_CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions" )
set( _CMAKE_C_FLAGS "${_CMAKE_C_FLAGS} -fno-rtti -fno-exceptions" )
else()
set( _CMAKE_CXX_FLAGS "${_CMAKE_CXX_FLAGS} -frtti -fexceptions" )
set( _CMAKE_C_FLAGS "${_CMAKE_C_FLAGS} -fexceptions" )
endif()
#release and debug flags
@@ -779,28 +798,33 @@ if( ARMEABI OR ARMEABI_V7A )
#It is recommended to use the -mthumb compiler flag to force the generation
#of 16-bit Thumb-1 instructions (the default being 32-bit ARM ones).
# O3 instead of O2/Os in release mode - like cmake sets for desktop gcc
set( CMAKE_CXX_FLAGS_RELEASE "-mthumb -O3" )
set( CMAKE_C_FLAGS_RELEASE "-mthumb -O3" )
set( CMAKE_CXX_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
set( CMAKE_C_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
set( _CMAKE_CXX_FLAGS_RELEASE "-mthumb -O3" )
set( _CMAKE_C_FLAGS_RELEASE "-mthumb -O3" )
set( _CMAKE_CXX_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
set( _CMAKE_C_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
else()
# always compile ARMEABI_V6 in arm mode; otherwise there is no difference from ARMEABI
# O3 instead of O2/Os in release mode - like cmake sets for desktop gcc
set( CMAKE_CXX_FLAGS_RELEASE "-marm -O3 -fstrict-aliasing" )
set( CMAKE_C_FLAGS_RELEASE "-marm -O3 -fstrict-aliasing" )
set( CMAKE_CXX_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
set( CMAKE_C_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
set( _CMAKE_CXX_FLAGS_RELEASE "-marm -O3 -fstrict-aliasing" )
set( _CMAKE_C_FLAGS_RELEASE "-marm -O3 -fstrict-aliasing" )
set( _CMAKE_CXX_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
set( _CMAKE_C_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
endif()
elseif( X86 )
set( CMAKE_CXX_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( CMAKE_C_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( CMAKE_CXX_FLAGS_DEBUG "-O0 -finline-limit=300" )
set( CMAKE_C_FLAGS_DEBUG "-O0 -finline-limit=300" )
set( _CMAKE_CXX_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( _CMAKE_C_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( _CMAKE_CXX_FLAGS_DEBUG "-O0 -finline-limit=300" )
set( _CMAKE_C_FLAGS_DEBUG "-O0 -finline-limit=300" )
elseif( MIPS )
set( _CMAKE_CXX_FLAGS_RELEASE "-O3 -funswitch-loops -finline-limit=300" )
set( _CMAKE_C_FLAGS_RELEASE "-O3 -funswitch-loops -finline-limit=300" )
set( _CMAKE_CXX_FLAGS_DEBUG "-O0 -g" )
set( _CMAKE_C_FLAGS_DEBUG "-O0 -g" )
endif()
set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -DNDEBUG" )
set( CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fomit-frame-pointer -DNDEBUG" )
set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-strict-aliasing -fno-omit-frame-pointer -DDEBUG -D_DEBUG" )
set( CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fno-strict-aliasing -fno-omit-frame-pointer -DDEBUG -D_DEBUG" )
set( _CMAKE_CXX_FLAGS_RELEASE "${_CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -DNDEBUG" )
set( _CMAKE_C_FLAGS_RELEASE "${_CMAKE_C_FLAGS_RELEASE} -fomit-frame-pointer -DNDEBUG" )
set( _CMAKE_CXX_FLAGS_DEBUG "${_CMAKE_CXX_FLAGS_DEBUG} -fno-strict-aliasing -fno-omit-frame-pointer -DDEBUG -D_DEBUG" )
set( _CMAKE_C_FLAGS_DEBUG "${_CMAKE_C_FLAGS_DEBUG} -fno-strict-aliasing -fno-omit-frame-pointer -DDEBUG -D_DEBUG" )
#ABI-specific flags
if( ARMEABI_V7A )
@@ -904,12 +928,12 @@ if( ARMEABI_V7A )
endif()
#cache flags
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" CACHE STRING "c++ flags" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS}" CACHE STRING "c flags" )
set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}" CACHE STRING "c++ Release flags" )
set( CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}" CACHE STRING "c Release flags" )
set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING "c++ Debug flags" )
set( CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}" CACHE STRING "c Debug flags" )
set( CMAKE_CXX_FLAGS "${_CMAKE_CXX_FLAGS}" CACHE STRING "c++ flags" )
set( CMAKE_C_FLAGS "${_CMAKE_C_FLAGS}" CACHE STRING "c flags" )
set( CMAKE_CXX_FLAGS_RELEASE "${_CMAKE_CXX_FLAGS_RELEASE}" CACHE STRING "c++ Release flags" )
set( CMAKE_C_FLAGS_RELEASE "${_CMAKE_C_FLAGS_RELEASE}" CACHE STRING "c Release flags" )
set( CMAKE_CXX_FLAGS_DEBUG "${_CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING "c++ Debug flags" )
set( CMAKE_C_FLAGS_DEBUG "${_CMAKE_C_FLAGS_DEBUG}" CACHE STRING "c Debug flags" )
set( CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "linker flags" )
set( CMAKE_MODULE_LINKER_FLAGS "" CACHE STRING "linker flags" )
set( CMAKE_EXE_LINKER_FLAGS "-Wl,-z,nocopyreloc" CACHE STRING "linker flags" )
@@ -922,9 +946,15 @@ set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS}" CACHE INTERNAL "Extra Androi
set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}" CACHE INTERNAL "Extra Android linker flags")
set( CMAKE_CXX_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" )
set( CMAKE_C_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" )
set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
set( CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" )
if( MIPS AND BUILD_WITH_ANDROID_NDK )
set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.xsc ${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
set( CMAKE_MODULE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.xsc ${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
set( CMAKE_EXE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.x ${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" )
else()
set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
set( CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" )
endif()
#set these global flags for cmake client scripts to change behavior
set( ANDROID True )
@@ -1020,7 +1050,7 @@ endif()
# Variables controlling behavior or set by cmake toolchain:
# ANDROID_ABI : "armeabi-v7a" (default), "armeabi", "armeabi-v7a with NEON", "armeabi-v7a with VFPV3", "armeabi-v6 with VFP", "x86"
# ANDROID_ABI : "armeabi-v7a" (default), "armeabi", "armeabi-v7a with NEON", "armeabi-v7a with VFPV3", "armeabi-v6 with VFP", "x86", "mips"
# ANDROID_NATIVE_API_LEVEL : 3,4,5,8,9,14 (depends on NDK version)
# ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF
# ANDROID_USE_STLPORT : OFF/ON - EXPERIMENTAL!!!
@@ -1054,7 +1084,7 @@ endif()
# BUILD_WITH_STANDALONE_TOOLCHAIN : TRUE if standalone toolchain is used
# ANDROID_NDK_HOST_SYSTEM_NAME : "windows", "linux-x86" or "darwin-x86" depending on host platform
# ANDROID_NDK_ABI_NAME : "armeabi", "armeabi-v7a" or "x86" depending on ANDROID_ABI
# ANDROID_ARCH_NAME : "arm" or "x86" depending on ANDROID_ABI
# ANDROID_ARCH_NAME : "arm" or "x86" or "mips" depending on ANDROID_ABI
# TOOL_OS_SUFFIX : "" or ".exe" depending on host platform
# ANDROID_SYSROOT : path to the compiler sysroot
# ANDROID_SYSTEM_INCLUDE_DIRS
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
cd `dirname $0`/..
mkdir -p build_x86
cd build_x86
cmake -DANDROID_ABI=x86 -DCMAKE_TOOLCHAIN_FILE=../android.toolchain.cmake $@ ../..
+28 -2
View File
@@ -1,5 +1,16 @@
if (WIN32 AND CMAKE_GENERATOR MATCHES "(MinGW)|(MSYS)")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG" CACHE STRING "")
if(MINGW)
# mingw compiler is known to produce unstable SSE code with -O3 hence we are trying to use -O2 instead
if(CMAKE_COMPILER_IS_GNUCXX)
foreach(flags CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_DEBUG)
string(REPLACE "-O3" "-O2" ${flags} "${${flags}}")
endforeach()
endif()
if(CMAKE_COMPILER_IS_GNUCC)
foreach(flags CMAKE_C_FLAGS CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_DEBUG)
string(REPLACE "-O3" "-O2" ${flags} "${${flags}}")
endforeach()
endif()
endif()
if(MSVC)
@@ -17,6 +28,21 @@ set(OPENCV_EXTRA_EXE_LINKER_FLAGS "")
set(OPENCV_EXTRA_EXE_LINKER_FLAGS_RELEASE "")
set(OPENCV_EXTRA_EXE_LINKER_FLAGS_DEBUG "")
if(MINGW)
# http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40838
# here we are trying to workaround the problem
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG(-mstackrealign HAVE_STACKREALIGN_FLAG)
if(HAVE_STACKREALIGN_FLAG)
set(OPENCV_EXTRA_C_FLAGS "${OPENCV_EXTRA_C_FLAGS} -mstackrealign")
else()
CHECK_CXX_COMPILER_FLAG(-mpreferred-stack-boundary=2 HAVE_PREFERRED_STACKBOUNDARY_FLAG)
if(HAVE_PREFERRED_STACKBOUNDARY_FLAG)
set(OPENCV_EXTRA_C_FLAGS "${OPENCV_EXTRA_C_FLAGS} -mstackrealign")
endif()
endif()
endif()
if(CMAKE_COMPILER_IS_GNUCXX)
# High level of warnings.
set(OPENCV_EXTRA_C_FLAGS "${OPENCV_EXTRA_C_FLAGS} -Wall")
+1 -1
View File
@@ -8,7 +8,7 @@ file(TO_CMAKE_PATH "$ENV{HOME}" HOME_ENV_PATH)
if(CMAKE_HOST_WIN32)
set(ANDROID_SDK_OS windows)
elseif(CMAKE_HOST_APPLE)
set(ANDROID_SDK_OS mac)
set(ANDROID_SDK_OS macosx)
else()
set(ANDROID_SDK_OS linux)
endif()
+11 -1
View File
@@ -1,3 +1,8 @@
if(${CMAKE_VERSION} VERSION_LESS "2.8.3")
message(STATUS WITH_CUDA flag requires CMake 2.8.3. CUDA support is disabled.)
return()
endif()
find_package(CUDA 4.1)
if(CUDA_FOUND)
@@ -13,7 +18,12 @@ if(CUDA_FOUND)
message(STATUS "CUDA detected: " ${CUDA_VERSION})
set(CUDA_ARCH_BIN "1.1 1.2 1.3 2.0 2.1(2.0)" CACHE STRING "Specify 'real' GPU architectures to build binaries for, BIN(PTX) format is supported")
if(${CUDA_VERSION_STRING} VERSION_GREATER "4.1")
set(CUDA_ARCH_BIN "1.1 1.2 1.3 2.0 2.1(2.0) 3.0" CACHE STRING "Specify 'real' GPU architectures to build binaries for, BIN(PTX) format is supported")
else()
set(CUDA_ARCH_BIN "1.1 1.2 1.3 2.0 2.1(2.0)" CACHE STRING "Specify 'real' GPU architectures to build binaries for, BIN(PTX) format is supported")
endif()
set(CUDA_ARCH_PTX "2.0" CACHE STRING "Specify 'virtual' PTX architectures to build PTX intermediate code for")
string(REGEX REPLACE "\\." "" ARCH_BIN_NO_POINTS "${CUDA_ARCH_BIN}")
+3 -3
View File
@@ -8,11 +8,11 @@ endif()
if(NOT APPLE)
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_COMPILER_IS_GNUCXX 1)
unset(ENABLE_PRECOMPILED_HEADERS CACHE)
set(ENABLE_PRECOMPILED_HEADERS OFF CACHE BOOL "" FORCE)
endif()
if(CMAKE_C_COMPILER_ID STREQUAL "Clang")
set(CMAKE_COMPILER_IS_GNUC 1)
unset(ENABLE_PRECOMPILED_HEADERS CACHE)
set(CMAKE_COMPILER_IS_GNUCC 1)
set(ENABLE_PRECOMPILED_HEADERS OFF CACHE BOOL "" FORCE)
endif()
endif()
+10 -12
View File
@@ -1,4 +1,4 @@
if(MSVC AND NOT PYTHON_EXECUTABLE)
if(WIN32 AND NOT PYTHON_EXECUTABLE)
# search for executable with the same bitness as resulting binaries
# standard FindPythonInterp always prefers executable from system path
# this is really important because we are using the interpreter for numpy search and for choosing the install location
@@ -12,16 +12,14 @@ if(MSVC AND NOT PYTHON_EXECUTABLE)
)
endforeach()
endif()
find_host_package(PythonInterp 2.0)
unset(PYTHON_USE_NUMPY CACHE)
unset(HAVE_SPHINX CACHE)
if(PYTHON_EXECUTABLE)
if(PYTHON_VERSION_STRING)
set(PYTHON_VERSION_FULL "${PYTHON_VERSION_STRING}")
set(PYTHON_VERSION_MAJOR_MINOR "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}")
string(REGEX MATCH "[0-9]+.[0-9]+.[0-9]+" PYTHON_VERSION_FULL "${PYTHON_VERSION_STRING}")
else()
execute_process(COMMAND ${PYTHON_EXECUTABLE} --version
ERROR_VARIABLE PYTHON_VERSION_FULL
@@ -46,16 +44,15 @@ if(PYTHON_EXECUTABLE)
OUTPUT_VARIABLE PYTHON_STD_PACKAGES_PATH
OUTPUT_STRIP_TRAILING_WHITESPACE)
if("${PYTHON_STD_PACKAGES_PATH}" MATCHES "site-packages")
set(PYTHON_PACKAGES_PATH "python${PYTHON_VERSION_MAJOR_MINOR}/site-packages")
set(_PYTHON_PACKAGES_PATH "python${PYTHON_VERSION_MAJOR_MINOR}/site-packages")
else() #debian based assumed, install to the dist-packages.
set(PYTHON_PACKAGES_PATH "python${PYTHON_VERSION_MAJOR_MINOR}/dist-packages")
set(_PYTHON_PACKAGES_PATH "python${PYTHON_VERSION_MAJOR_MINOR}/dist-packages")
endif()
if(EXISTS "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/${PYTHON_PACKAGES_PATH}")
set(PYTHON_PACKAGES_PATH "lib${LIB_SUFFIX}/${PYTHON_PACKAGES_PATH}")
set(_PYTHON_PACKAGES_PATH "lib${LIB_SUFFIX}/${_PYTHON_PACKAGES_PATH}")
else()
set(PYTHON_PACKAGES_PATH "lib/${PYTHON_PACKAGES_PATH}")
set(_PYTHON_PACKAGES_PATH "lib/${_PYTHON_PACKAGES_PATH}")
endif()
set(PYTHON_PACKAGES_PATH "${PYTHON_PACKAGES_PATH}" CACHE PATH "Where to install the python packages.")
elseif(CMAKE_HOST_WIN32)
get_filename_component(PYTHON_PATH "${PYTHON_EXECUTABLE}" PATH)
file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH)
@@ -67,8 +64,9 @@ if(PYTHON_EXECUTABLE)
endif()
file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH)
endif()
set(PYTHON_PACKAGES_PATH "${PYTHON_PATH}/Lib/site-packages")
set(_PYTHON_PACKAGES_PATH "${PYTHON_PATH}/Lib/site-packages")
endif()
SET(PYTHON_PACKAGES_PATH "${_PYTHON_PACKAGES_PATH}" CACHE PATH "Where to install the python packages.")
if(NOT PYTHON_NUMPY_INCLUDE_DIR)
# Attempt to discover the NumPy include directory. If this succeeds, then build python API with NumPy
@@ -78,8 +76,8 @@ if(PYTHON_EXECUTABLE)
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PYTHON_NUMPY_PROCESS EQUAL 0)
file(TO_CMAKE_PATH "${PYTHON_NUMPY_INCLUDE_DIR}" PYTHON_NUMPY_INCLUDE_DIR)
set(PYTHON_NUMPY_INCLUDE_DIR ${PYTHON_NUMPY_INCLUDE_DIR} CACHE PATH "Path to numpy headers")
file(TO_CMAKE_PATH "${PYTHON_NUMPY_INCLUDE_DIR}" _PYTHON_NUMPY_INCLUDE_DIR)
set(PYTHON_NUMPY_INCLUDE_DIR ${_PYTHON_NUMPY_INCLUDE_DIR} CACHE PATH "Path to numpy headers")
endif()
endif()
+60 -46
View File
@@ -220,45 +220,40 @@ function(set_ipp_variables _LATEST_VERSION)
endfunction()
# ------------------------------------------------------------------------
# This section will look for IPP through IPPROOT env variable
# Note, IPPROOT is not set by IPP installer, you may need to set it manually
# ------------------------------------------------------------------------
find_path(
IPP_H_PATH
NAMES ippversion.h
PATHS $ENV{IPPROOT}
PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH
NO_CMAKE_PATH)
# ------------------------------------------------------------------------
# This section will look for IPP through IPPROOT env variable
# Note, IPPROOT is not set by IPP installer, you may need to set it manually
# ------------------------------------------------------------------------
find_path(
IPP_H_PATH
NAMES ippversion.h
PATHS $ENV{IPPROOT}
PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH
NO_CMAKE_PATH)
if(IPP_H_PATH)
if(IPP_H_PATH)
set(IPP_FOUND 1)
set(IPP_FOUND 1)
# traverse up to IPPROOT level
get_filename_component(IPP_ROOT_DIR ${IPP_H_PATH} PATH)
# traverse up to IPPROOT level
get_filename_component(IPP_ROOT_DIR ${IPP_H_PATH} PATH)
# extract IPP version info
get_ipp_version(${IPP_ROOT_DIR})
# extract IPP version info
get_ipp_version(${IPP_ROOT_DIR})
# keep info in the same vars for auto search and search by IPPROOT
set(IPP_LATEST_VERSION_STR ${IPP_VERSION_STR})
set(IPP_LATEST_VERSION_MAJOR ${IPP_VERSION_MAJOR})
set(IPP_LATEST_VERSION_MINOR ${IPP_VERSION_MINOR})
set(IPP_LATEST_VERSION_BUILD ${IPP_VERSION_BUILD})
# keep info in the same vars for auto search and search by IPPROOT
set(IPP_LATEST_VERSION_STR ${IPP_VERSION_STR})
set(IPP_LATEST_VERSION_MAJOR ${IPP_VERSION_MAJOR})
set(IPP_LATEST_VERSION_MINOR ${IPP_VERSION_MINOR})
set(IPP_LATEST_VERSION_BUILD ${IPP_VERSION_BUILD})
# set IPP INCLUDE, LIB dirs and library names
set_ipp_variables(${IPP_LATEST_VERSION_STR})
endif()
# set IPP INCLUDE, LIB dirs and library names
set_ipp_variables(${IPP_LATEST_VERSION_STR})
endif()
if(IPP_FOUND)
return()
endif()
if(NOT IPP_FOUND)
# reset var from previous search
set(IPP_H_PATH)
@@ -304,19 +299,38 @@ endfunction()
endforeach()
endif()
endforeach()
endif()
if(IPP_FOUND)
# set IPP INCLUDE, LIB dirs and library names
set_ipp_variables(${IPP_LATEST_VERSION_STR})
if(IPP_FOUND)
# set IPP INCLUDE, LIB dirs and library names
set_ipp_variables(${IPP_LATEST_VERSION_STR})
# set CACHE variable IPP_H_PATH,
# path to IPP header files for the latest version
find_path(
IPP_H_PATH
NAMES ippversion.h
PATHS ${IPP_ROOT_DIR}
PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH
NO_CMAKE_PATH)
endif()
# set CACHE variable IPP_H_PATH,
# path to IPP header files for the latest version
find_path(
IPP_H_PATH
NAMES ippversion.h
PATHS ${IPP_ROOT_DIR}
PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH
NO_CMAKE_PATH)
endif()
if(WIN32 AND MINGW AND NOT IPP_LATEST_VERSION_MAJOR LESS 7)
# Since IPP built with Microsoft compiler and /GS option
# ======================================================
# From Windows SDK 7.1
# (usually in "C:\Program Files\Microsoft Visual Studio 10.0\VC\lib"),
# to avoid undefined reference to __security_cookie and _chkstk:
set(MSV_RUNTMCHK "RunTmChk")
set(IPP_LIBRARIES ${IPP_LIBRARIES} ${MSV_RUNTMCHK}${IPP_LIB_SUFFIX})
# To avoid undefined reference to _alldiv and _chkstk
# ===================================================
# NB: it may require a recompilation of w32api (after having modified
# the file ntdll.def) to export the required functions
# See http://code.opencv.org/issues/1906 for additional details
set(MSV_NTDLL "ntdll")
set(IPP_LIBRARIES ${IPP_LIBRARIES} ${MSV_NTDLL}${IPP_LIB_SUFFIX})
endif()
+41
View File
@@ -0,0 +1,41 @@
# ----------------------------------------------------------------------------
# Detect 3rd-party GUI libraries
# ----------------------------------------------------------------------------
# --- QT4 ---
ocv_clear_vars(HAVE_QT)
if(WITH_QT)
find_package(Qt4)
if(QT4_FOUND)
set(HAVE_QT TRUE)
add_definitions(-DHAVE_QT) # We need to define the macro this way, using cvconfig.h does not work
endif()
endif()
# --- GTK ---
ocv_clear_vars(HAVE_GTK HAVE_GTHREAD HAVE_GTKGLEXT)
if(WITH_GTK AND NOT HAVE_QT)
CHECK_MODULE(gtk+-2.0 HAVE_GTK)
CHECK_MODULE(gthread-2.0 HAVE_GTHREAD)
if(WITH_OPENGL)
CHECK_MODULE(gtkglext-1.0 HAVE_GTKGLEXT)
endif()
endif()
# --- OpenGl ---
ocv_clear_vars(HAVE_OPENGL HAVE_QT_OPENGL)
if(WITH_OPENGL)
if(WIN32 OR QT_QTOPENGL_FOUND OR HAVE_GTKGLEXT)
find_package (OpenGL QUIET)
if(OPENGL_FOUND)
set(HAVE_OPENGL TRUE)
list(APPEND OPENCV_LINKER_LIBS ${OPENGL_LIBRARIES})
if(QT_QTOPENGL_FOUND)
set(HAVE_QT_OPENGL TRUE)
add_definitions(-DHAVE_QT_OPENGL)
else()
ocv_include_directories(${OPENGL_INCLUDE_DIR})
endif()
endif()
endif()
endif(WITH_OPENGL)
@@ -1,15 +1,17 @@
macro(unset_all)
foreach(var ${ARGN})
unset(${var} CACHE)
endforeach()
endmacro()
# ----------------------------------------------------------------------------
# Detect 3rd-party image IO libraries
# ----------------------------------------------------------------------------
################### zlib - required
# --- zlib (required) ---
if(BUILD_ZLIB)
unset_all(ZLIB_FOUND)
ocv_clear_vars(ZLIB_FOUND)
else()
include(FindZLIB)
if(ZLIB_FOUND AND NOT ZLIB_VERSION_STRING)
if(ZLIB_FOUND)
if(ZLIB_VERSION_STRING)
#cmake 2.8.2 bug - it fails to determine zlib version
unset(ZLIB_VERSION_STRING CACHE)
endif()
ocv_parse_header2(ZLIB "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_VERSION "")
endif()
if(ZLIB_FOUND AND ANDROID)
@@ -21,7 +23,7 @@ else()
endif()
if(NOT ZLIB_FOUND)
unset_all(ZLIB_LIBRARY ZLIB_LIBRARIES ZLIB_INCLUDE_DIR)
ocv_clear_vars(ZLIB_LIBRARY ZLIB_LIBRARIES ZLIB_INCLUDE_DIR)
set(ZLIB_LIBRARY zlib)
set(ZLIB_LIBRARIES ${ZLIB_LIBRARY})
@@ -29,10 +31,10 @@ if(NOT ZLIB_FOUND)
set(ZLIB_INCLUDE_DIR "${${ZLIB_LIBRARY}_SOURCE_DIR}" "${${ZLIB_LIBRARY}_BINARY_DIR}")
endif()
################### libtiff - optional (should be searched after zlib)
# --- libtiff (optional, should be searched after zlib) ---
if(WITH_TIFF)
if(BUILD_TIFF)
unset_all(TIFF_FOUND)
ocv_clear_vars(TIFF_FOUND)
else()
include(FindTIFF)
if(TIFF_FOUND)
@@ -42,7 +44,7 @@ if(WITH_TIFF)
endif()
if(WITH_TIFF AND NOT TIFF_FOUND)
unset_all(TIFF_LIBRARY TIFF_LIBRARIES TIFF_INCLUDE_DIR)
ocv_clear_vars(TIFF_LIBRARY TIFF_LIBRARIES TIFF_INCLUDE_DIR)
set(TIFF_LIBRARY libtiff)
set(TIFF_LIBRARIES ${TIFF_LIBRARY})
@@ -59,17 +61,17 @@ if(TIFF_BIGTIFF_VERSION AND NOT TIFF_VERSION_BIG)
set(TIFF_VERSION_BIG ${TIFF_BIGTIFF_VERSION})
endif()
################### libjpeg - optional
# --- libjpeg (optional) ---
if(WITH_JPEG)
if(BUILD_JPEG)
unset_all(JPEG_FOUND)
ocv_clear_vars(JPEG_FOUND)
else()
include(FindJPEG)
endif()
endif()
if(WITH_JPEG AND NOT JPEG_FOUND)
unset_all(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR)
ocv_clear_vars(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR)
set(JPEG_LIBRARY libjpeg)
set(JPEG_LIBRARIES ${JPEG_LIBRARY})
@@ -80,17 +82,17 @@ endif()
ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION)
################### libjasper - optional (should be searched after libjpeg)
# --- libjasper (optional, should be searched after libjpeg) ---
if(WITH_JASPER)
if(BUILD_JASPER)
unset_all(JASPER_FOUND)
ocv_clear_vars(JASPER_FOUND)
else()
include(FindJasper)
endif()
endif()
if(WITH_JASPER AND NOT JASPER_FOUND)
unset_all(JASPER_LIBRARY JASPER_LIBRARIES JASPER_INCLUDE_DIR)
ocv_clear_vars(JASPER_LIBRARY JASPER_LIBRARIES JASPER_INCLUDE_DIR)
set(JASPER_LIBRARY libjasper)
set(JASPER_LIBRARIES ${JASPER_LIBRARY})
@@ -102,10 +104,10 @@ if(NOT JASPER_VERSION_STRING)
ocv_parse_header2(JASPER "${JASPER_INCLUDE_DIR}/jasper/jas_config.h" JAS_VERSION "")
endif()
################### libpng - optional (should be searched after zlib)
# --- libpng (optional, should be searched after zlib) ---
if(WITH_PNG)
if(BUILD_PNG)
unset_all(PNG_FOUND)
ocv_clear_vars(PNG_FOUND)
else()
include(FindPNG)
if(PNG_FOUND)
@@ -121,7 +123,7 @@ if(WITH_PNG)
endif()
if(WITH_PNG AND NOT PNG_FOUND)
unset_all(PNG_LIBRARY PNG_LIBRARIES PNG_INCLUDE_DIR PNG_PNG_INCLUDE_DIR HAVE_PNG_H HAVE_LIBPNG_PNG_H PNG_DEFINITIONS)
ocv_clear_vars(PNG_LIBRARY PNG_LIBRARIES PNG_INCLUDE_DIR PNG_PNG_INCLUDE_DIR HAVE_PNG_H HAVE_LIBPNG_PNG_H PNG_DEFINITIONS)
set(PNG_LIBRARY libpng)
set(PNG_LIBRARIES ${PNG_LIBRARY})
@@ -133,7 +135,7 @@ endif()
set(PNG_VERSION "${PNG_LIBPNG_VER_MAJOR}.${PNG_LIBPNG_VER_MINOR}.${PNG_LIBPNG_VER_RELEASE}")
################### OpenEXR - optional
# --- OpenEXR (optional) ---
if(WITH_OPENEXR)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindOpenEXR.cmake")
endif()
+39
View File
@@ -0,0 +1,39 @@
# ----------------------------------------------------------------------------
# Detect other 3rd-party performance and math libraries
# ----------------------------------------------------------------------------
# --- TBB ---
if(WITH_TBB)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVDetectTBB.cmake" REQUIRED)
endif(WITH_TBB)
# --- IPP ---
ocv_clear_vars(IPP_FOUND)
if(WITH_IPP)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindIPP.cmake")
if(IPP_FOUND)
add_definitions(-DHAVE_IPP)
ocv_include_directories(${IPP_INCLUDE_DIRS})
link_directories(${IPP_LIBRARY_DIRS})
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${IPP_LIBRARIES})
endif()
endif(WITH_IPP)
# --- CUDA ---
if(WITH_CUDA)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVDetectCUDA.cmake" REQUIRED)
endif(WITH_CUDA)
# --- Eigen ---
if(WITH_EIGEN)
find_path(EIGEN_INCLUDE_PATH "Eigen/Core"
PATHS /usr/local /opt /usr ENV ProgramFiles ENV ProgramW6432
PATH_SUFFIXES include/eigen3 include/eigen2 Eigen/include/eigen3 Eigen/include/eigen2
DOC "The path to Eigen3/Eigen2 headers")
if(EIGEN_INCLUDE_PATH)
ocv_include_directories(${EIGEN_INCLUDE_PATH})
ocv_parse_header("${EIGEN_INCLUDE_PATH}/Eigen/src/Core/util/Macros.h" EIGEN_VERSION_LINES EIGEN_WORLD_VERSION EIGEN_MAJOR_VERSION EIGEN_MINOR_VERSION)
set(HAVE_EIGEN 1)
endif()
endif(WITH_EIGEN)
+180
View File
@@ -0,0 +1,180 @@
# ----------------------------------------------------------------------------
# Detect 3rd-party video IO libraries
# ----------------------------------------------------------------------------
# --- GStreamer ---
ocv_clear_vars(HAVE_GSTREAMER)
if(WITH_GSTREAMER)
CHECK_MODULE(gstreamer-base-0.10 HAVE_GSTREAMER)
if(HAVE_GSTREAMER)
CHECK_MODULE(gstreamer-app-0.10 HAVE_GSTREAMER)
endif()
if(HAVE_GSTREAMER)
CHECK_MODULE(gstreamer-video-0.10 HAVE_GSTREAMER)
endif()
endif(WITH_GSTREAMER)
# --- unicap ---
ocv_clear_vars(HAVE_UNICAP)
if(WITH_UNICAP)
CHECK_MODULE(libunicap HAVE_UNICAP_)
CHECK_MODULE(libucil HAVE_UNICAP_UCIL)
if(HAVE_UNICAP_ AND HAVE_UNICAP_UCIL)
set(HAVE_UNICAP TRUE)
endif()
endif(WITH_UNICAP)
# --- PvApi ---
ocv_clear_vars(HAVE_PVAPI)
if(WITH_PVAPI)
find_path(PVAPI_INCLUDE_PATH "PvApi.h"
PATHS /usr/local /opt /usr ENV ProgramFiles ENV ProgramW6432
PATH_SUFFIXES include "Allied Vision Technologies/GigESDK/inc-pc" "AVT GigE SDK/inc-pc" "GigESDK/inc-pc"
DOC "The path to PvAPI header")
if(PVAPI_INCLUDE_PATH)
if(X86 AND NOT WIN32)
set(PVAPI_SDK_SUBDIR x86)
elseif(X86_64)
set(PVAPI_SDK_SUBDIR x64)
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES arm)
set(PVAPI_SDK_SUBDIR arm)
endif()
get_filename_component(_PVAPI_LIBRARY "${PVAPI_INCLUDE_PATH}/../lib-pc" ABSOLUTE)
if(PVAPI_SDK_SUBDIR)
set(_PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${PVAPI_SDK_SUBDIR}")
endif()
if(NOT WIN32 AND CMAKE_COMPILER_IS_GNUCXX)
set(_PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${CMAKE_OPENCV_GCC_VERSION_MAJOR}.${CMAKE_OPENCV_GCC_VERSION_MINOR}")
endif()
set(PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${CMAKE_STATIC_LIBRARY_PREFIX}PvAPI${CMAKE_STATIC_LIBRARY_SUFFIX}" CACHE PATH "The PvAPI library")
if(EXISTS "${PVAPI_LIBRARY}")
set(HAVE_PVAPI TRUE)
endif()
endif(PVAPI_INCLUDE_PATH)
endif(WITH_PVAPI)
# --- Dc1394 ---
ocv_clear_vars(HAVE_DC1394 HAVE_DC1394_2)
if(WITH_1394)
CHECK_MODULE(libdc1394-2 HAVE_DC1394_2)
if(NOT HAVE_DC1394_2)
CHECK_MODULE(libdc1394 HAVE_DC1394)
endif()
endif(WITH_1394)
# --- xine ---
ocv_clear_vars(HAVE_XINE)
if(WITH_XINE)
CHECK_MODULE(libxine HAVE_XINE)
endif(WITH_XINE)
# --- V4L ---
ocv_clear_vars(HAVE_LIBV4L HAVE_CAMV4L HAVE_CAMV4L2)
if(WITH_V4L)
CHECK_MODULE(libv4l1 HAVE_LIBV4L)
CHECK_INCLUDE_FILE(linux/videodev.h HAVE_CAMV4L)
CHECK_INCLUDE_FILE(linux/videodev2.h HAVE_CAMV4L2)
endif(WITH_V4L)
# --- OpenNI ---
ocv_clear_vars(HAVE_OPENNI HAVE_OPENNI_PRIME_SENSOR_MODULE)
if(WITH_OPENNI)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindOpenNI.cmake")
endif(WITH_OPENNI)
# --- XIMEA ---
ocv_clear_vars(HAVE_XIMEA)
if(WITH_XIMEA)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindXimea.cmake")
if(XIMEA_FOUND)
set(HAVE_XIMEA TRUE)
endif()
endif(WITH_XIMEA)
# --- FFMPEG ---
ocv_clear_vars(HAVE_FFMPEG HAVE_FFMPEG_CODEC HAVE_FFMPEG_FORMAT HAVE_FFMPEG_UTIL HAVE_FFMPEG_SWSCALE HAVE_GENTOO_FFMPEG HAVE_FFMPEG_FFMPEG)
if(WITH_FFMPEG)
if(WIN32)
include("${OpenCV_SOURCE_DIR}/3rdparty/ffmpeg/ffmpeg_version.cmake" REQUIRED)
elseif(UNIX)
CHECK_MODULE(libavcodec HAVE_FFMPEG_CODEC)
CHECK_MODULE(libavformat HAVE_FFMPEG_FORMAT)
CHECK_MODULE(libavutil HAVE_FFMPEG_UTIL)
CHECK_MODULE(libswscale HAVE_FFMPEG_SWSCALE)
CHECK_INCLUDE_FILE(libavformat/avformat.h HAVE_GENTOO_FFMPEG)
CHECK_INCLUDE_FILE(ffmpeg/avformat.h HAVE_FFMPEG_FFMPEG)
if(NOT HAVE_GENTOO_FFMPEG AND NOT HAVE_FFMPEG_FFMPEG)
if(EXISTS /usr/include/ffmpeg/libavformat/avformat.h OR HAVE_FFMPEG_SWSCALE)
set(HAVE_GENTOO_FFMPEG TRUE)
endif()
endif()
if(HAVE_FFMPEG_CODEC AND HAVE_FFMPEG_FORMAT AND HAVE_FFMPEG_UTIL AND HAVE_FFMPEG_SWSCALE)
set(HAVE_FFMPEG TRUE)
endif()
if(HAVE_FFMPEG)
# Find the bzip2 library because it is required on some systems
FIND_LIBRARY(BZIP2_LIBRARIES NAMES bz2 bzip2)
if(NOT BZIP2_LIBRARIES)
# Do an other trial
FIND_FILE(BZIP2_LIBRARIES NAMES libbz2.so.1 PATHS /lib)
endif()
endif(HAVE_FFMPEG)
endif()
if(APPLE)
find_path(FFMPEG_INCLUDE_DIR "libavformat/avformat.h"
PATHS /usr/local /usr /opt
PATH_SUFFIXES include
DOC "The path to FFMPEG headers")
if(FFMPEG_INCLUDE_DIR)
set(HAVE_GENTOO_FFMPEG TRUE)
set(FFMPEG_LIB_DIR "${FFMPEG_INCLUDE_DIR}/../lib" CACHE PATH "Full path of FFMPEG library directory")
if(EXISTS "${FFMPEG_LIB_DIR}/libavcodec.a")
set(HAVE_FFMPEG_CODEC 1)
set(ALIASOF_libavcodec_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libavformat.a")
set(HAVE_FFMPEG_FORMAT 1)
set(ALIASOF_libavformat_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libavutil.a")
set(HAVE_FFMPEG_UTIL 1)
set(ALIASOF_libavutil_VERSION "Unknown")
if(EXISTS "${FFMPEG_LIB_DIR}/libswscale.a")
set(HAVE_FFMPEG_SWSCALE 1)
set(ALIASOF_libswscale_VERSION "Unknown")
set(HAVE_FFMPEG 1)
endif()
endif()
endif()
endif()
endif(FFMPEG_INCLUDE_DIR)
if(HAVE_FFMPEG)
set(HIGHGUI_LIBRARIES ${HIGHGUI_LIBRARIES} "${FFMPEG_LIB_DIR}/libavcodec.a"
"${FFMPEG_LIB_DIR}/libavformat.a" "${FFMPEG_LIB_DIR}/libavutil.a"
"${FFMPEG_LIB_DIR}/libswscale.a")
ocv_include_directories(${FFMPEG_INCLUDE_DIR})
endif()
endif(APPLE)
endif(WITH_FFMPEG)
# --- VideoInput ---
if(WITH_VIDEOINPUT)
# always have VideoInput on Windows
set(HAVE_VIDEOINPUT 1)
endif(WITH_VIDEOINPUT)
# --- Extra HighGUI libs on Windows ---
if(WIN32)
list(APPEND HIGHGUI_LIBRARIES comctl32 gdi32 ole32)
if(MSVC)
list(APPEND HIGHGUI_LIBRARIES vfw32)
elseif(MINGW64)
list(APPEND HIGHGUI_LIBRARIES msvfw32 avifil32 avicap32 winmm)
elseif(MINGW)
list(APPEND HIGHGUI_LIBRARIES vfw32 winmm)
endif()
endif(WIN32)
+1 -1
View File
@@ -23,7 +23,7 @@ else()
set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE "${ANDROID_NATIVE_API_LEVEL}")
endif()
if(MSVC OR CMAKE_GENERATOR MATCHES Xcode)
if(CMAKE_GENERATOR MATCHES "Visual" OR CMAKE_GENERATOR MATCHES "Xcode")
set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE TRUE)
else()
set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE FALSE)
+25 -9
View File
@@ -7,6 +7,7 @@
#
# OPENCV_MODULE_${the_module}_LOCATION
# OPENCV_MODULE_${the_module}_DESCRIPTION
# OPENCV_MODULE_${the_module}_CLASS - PUBLIC|INTERNAL|BINDINGS
# OPENCV_MODULE_${the_module}_HEADERS
# OPENCV_MODULE_${the_module}_SOURCES
# OPENCV_MODULE_${the_module}_DEPS - final flattened set of module dependencies
@@ -18,6 +19,8 @@
# To control the setup of the module you could also set:
# the_description - text to be used as current module description
# OPENCV_MODULE_TYPE - STATIC|SHARED - set to force override global settings for current module
# OPENCV_MODULE_IS_PART_OF_WORLD - ON|OFF (default ON) - should the module be added to the opencv_world?
# BUILD_${the_module}_INIT - ON|OFF (default ON) - initial value for BUILD_${the_module}
# The verbose template for OpenCV module:
#
@@ -38,10 +41,12 @@
# clean flags for modules enabled on previous cmake run
# this is necessary to correctly handle modules removal
foreach(mod ${OPENCV_MODULES_BUILD})
foreach(mod ${OPENCV_MODULES_BUILD} ${OPENCV_MODULES_DISABLED_USER} ${OPENCV_MODULES_DISABLED_AUTO} ${OPENCV_MODULES_DISABLED_FORCE})
if(HAVE_${mod})
unset(HAVE_${mod} CACHE)
endif()
unset(OPENCV_MODULE_${mod}_REQ_DEPS CACHE)
unset(OPENCV_MODULE_${mod}_OPT_DEPS CACHE)
endforeach()
# clean modules info which needs to be recalculated
@@ -58,8 +63,8 @@ set(OPENCV_MODULES_DISABLED_FORCE "" CACHE INTERNAL "List of OpenCV modules whic
# * <list of dependencies> - can include full names of modules or full pathes to shared/static libraries or cmake targets
macro(ocv_add_dependencies full_modname)
#we don't clean the dependencies here to allow this macro several times for every module
foreach(d "REQIRED" ${ARGN})
if(d STREQUAL "REQIRED")
foreach(d "REQUIRED" ${ARGN})
if(d STREQUAL "REQUIRED")
set(__depsvar OPENCV_MODULE_${full_modname}_REQ_DEPS)
elseif(d STREQUAL "OPTIONAL")
set(__depsvar OPENCV_MODULE_${full_modname}_OPT_DEPS)
@@ -84,7 +89,7 @@ endmacro()
# Usage:
# ocv_add_module(<name> [INTERNAL|BINDINGS] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>])
# Example:
# ocv_add_module(yaom INTERNAL opencv_core opencv_highgui NOLINK opencv_flann OPTIONAL opencv_gpu)
# ocv_add_module(yaom INTERNAL opencv_core opencv_highgui opencv_flann OPTIONAL opencv_gpu)
macro(ocv_add_module _name)
string(TOLOWER "${_name}" name)
string(REGEX REPLACE "^opencv_" "" ${name} "${name}")
@@ -106,23 +111,31 @@ macro(ocv_add_module _name)
endif()
set(OPENCV_MODULE_${the_module}_DESCRIPTION "${the_description}" CACHE INTERNAL "Brief description of ${the_module} module")
set(OPENCV_MODULE_${the_module}_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "Location of ${the_module} module sources")
unset(OPENCV_MODULE_${the_module}_REQ_DEPS CACHE)
unset(OPENCV_MODULE_${the_module}_OPT_DEPS CACHE)
#create option to enable/disable this module
option(BUILD_${the_module} "Include ${the_module} module into the OpenCV build" ON)
if(NOT DEFINED BUILD_${the_module}_INIT)
set(BUILD_${the_module}_INIT ON)
endif()
option(BUILD_${the_module} "Include ${the_module} module into the OpenCV build" ${BUILD_${the_module}_INIT})
if("${ARGV1}" STREQUAL "INTERNAL" OR "${ARGV1}" STREQUAL "BINDINGS")
set(OPENCV_MODULE_${the_module}_CLASS "${ARGV1}" CACHE INTERNAL "The cathegory of the module")
set(__ocv_argn__ ${ARGN})
list(REMOVE_AT __ocv_argn__ 0)
ocv_add_dependencies(${the_module} ${__ocv_argn__})
unset(__ocv_argn__)
else()
set(OPENCV_MODULE_${the_module}_CLASS "PUBLIC" CACHE INTERNAL "The cathegory of the module")
ocv_add_dependencies(${the_module} ${ARGN})
if(BUILD_${the_module})
set(OPENCV_MODULES_PUBLIC ${OPENCV_MODULES_PUBLIC} "${the_module}" CACHE INTERNAL "List of OpenCV modules marked for export")
endif()
endif()
# add self to the world dependencies
if(NOT DEFINED OPENCV_MODULE_IS_PART_OF_WORLD AND NOT OPENCV_MODULE_${the_module}_CLASS STREQUAL "BINDINGS" OR OPENCV_MODULE_IS_PART_OF_WORLD)
ocv_add_dependencies(opencv_world OPTIONAL ${the_module})
endif()
if(BUILD_${the_module})
set(OPENCV_MODULES_BUILD ${OPENCV_MODULES_BUILD} "${the_module}" CACHE INTERNAL "List of OpenCV modules included into the build")
@@ -429,10 +442,13 @@ endmacro()
# creates OpenCV module in current folder
# creates new target, configures standard dependencies, compilers flags, install rules
# Usage:
# ocv_create_module(<extra link dependencies>)
# ocv_create_module(<extra link dependencies>)
# ocv_create_module(SKIP_LINK)
macro(ocv_create_module)
add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES})
target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
if(NOT "${ARGN}" STREQUAL "SKIP_LINK")
target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
endif()
add_dependencies(opencv_modules ${the_module})
if(ENABLE_SOLUTION_FOLDERS)
+13 -6
View File
@@ -11,7 +11,7 @@ if(NOT COMMAND find_host_program)
endmacro()
endif()
#added include directories in such way that directories from the OpenCV source tree go first
# adds include directories in such way that directories from the OpenCV source tree go first
function(ocv_include_directories)
set(__add_before "")
foreach(dir ${ARGN})
@@ -25,6 +25,12 @@ function(ocv_include_directories)
include_directories(BEFORE ${__add_before})
endfunction()
# clears all passed variables
macro(ocv_clear_vars)
foreach(_var ${ARGN})
unset(${_var} CACHE)
endforeach()
endmacro()
# Provides an option that the user can optionally select.
# Can accept condition to control when option is available for user.
@@ -352,10 +358,11 @@ macro(ocv_parse_header2 LIBNAME HDR_PATH VARNAME SCOPE)
set(${LIBNAME}_VERSION_STRING "${${LIBNAME}_VERSION_STRING}.${${LIBNAME}_VERSION_TWEAK}" ${SCOPE})
endif()
else()
unset(${LIBNAME}_VERSION_MAJOR CACHE)
unset(${LIBNAME}_VERSION_MINOR CACHE)
unset(${LIBNAME}_VERSION_PATCH CACHE)
unset(${LIBNAME}_VERSION_TWEAK CACHE)
unset(${LIBNAME}_VERSION_STRING CACHE)
ocv_clear_vars(${LIBNAME}_VERSION_MAJOR
${LIBNAME}_VERSION_MAJOR
${LIBNAME}_VERSION_MINOR
${LIBNAME}_VERSION_PATCH
${LIBNAME}_VERSION_TWEAK
${LIBNAME}_VERSION_STRING)
endif()
endmacro()
+39 -3
View File
@@ -11,8 +11,44 @@ if(BUILD_DOCS AND HAVE_SPHINX)
project(opencv_docs)
file(GLOB_RECURSE OPENCV_FILES_REF ../modules/*.rst)
file(GLOB_RECURSE OPENCV_FILES_REF_PICT ../modules/*.png ../modules/*.jpg)
set(OPENCV2_BASE_MODULES core imgproc highgui video calib3d features2d objdetect ml flann gpu photo stitching nonfree contrib legacy)
# build lists of modules to be documented
set(OPENCV2_MODULES "")
set(OPENCV_MODULES "")
foreach(mod ${OPENCV_MODULES_BUILD} ${OPENCV_MODULES_DISABLED_USER} ${OPENCV_MODULES_DISABLED_AUTO} ${OPENCV_MODULES_DISABLED_FORCE})
string(REGEX REPLACE "^opencv_" "" mod "${mod}")
if("${OPENCV_MODULE_opencv_${mod}_LOCATION}" STREQUAL "${OpenCV_SOURCE_DIR}/modules/${mod}")
list(APPEND OPENCV2_MODULES ${mod})
else()
list(APPEND OPENCV_MODULES ${mod})
endif()
endforeach()
list(REMOVE_ITEM OPENCV2_MODULES ${OPENCV2_BASE_MODULES})
ocv_list_sort(OPENCV2_MODULES)
ocv_list_sort(OPENCV_MODULES)
# build lists of documentation files and generate table of contents for reference manual
set(OPENCV_FILES_REF "")
set(OPENCV_FILES_REF_PICT "")
set(OPENCV_REFMAN_TOC "")
foreach(mod ${OPENCV2_BASE_MODULES} ${OPENCV2_MODULES} ${OPENCV_MODULES})
file(GLOB_RECURSE _OPENCV_FILES_REF "${OPENCV_MODULE_opencv_${mod}_LOCATION}/doc/*.rst")
file(GLOB_RECURSE _OPENCV_FILES_REF_PICT "${OPENCV_MODULE_opencv_${mod}_LOCATION}/doc/*.png" "${OPENCV_MODULE_opencv_${mod}_LOCATION}/doc/*.jpg")
list(APPEND OPENCV_FILES_REF ${_OPENCV_FILES_REF})
list(APPEND OPENCV_FILES_REF_PICT ${_OPENCV_FILES_REF_PICT})
set(toc_file "${OPENCV_MODULE_opencv_${mod}_LOCATION}/doc/${mod}.rst")
if(EXISTS "${toc_file}")
file(RELATIVE_PATH toc_file "${OpenCV_SOURCE_DIR}/modules" "${toc_file}")
set(OPENCV_REFMAN_TOC "${OPENCV_REFMAN_TOC} ${toc_file}\r\n")
endif()
endforeach()
configure_file("${OpenCV_SOURCE_DIR}/modules/refman.rst.in" "${OpenCV_SOURCE_DIR}/modules/refman.rst" IMMEDIATE @ONLY)
file(GLOB_RECURSE OPENCV_FILES_UG user_guide/*.rst)
file(GLOB_RECURSE OPENCV_FILES_TUT tutorials/*.rst)
file(GLOB_RECURSE OPENCV_FILES_TUT_PICT tutorials/*.png tutorials/*.jpg)
@@ -54,6 +90,6 @@ if(BUILD_DOCS AND HAVE_SPHINX)
set_target_properties(html_docs PROPERTIES FOLDER "documentation")
endif()
endif()
install(FILES ${FILES_DOC} DESTINATION "${OPENCV_DOC_INSTALL_PATH}" COMPONENT main)
install(FILES ${FILES_DOC_VS} DESTINATION "${OPENCV_DOC_INSTALL_PATH}/vidsurv" COMPONENT main)
+497
View File
@@ -0,0 +1,497 @@
import os, sys, glob, re
sys.path.append("../modules/python/src2/")
sys.path.append("../modules/java/")
import hdr_parser as hp
import rst_parser as rp
rp.show_warnings = False
rp.show_errors = False
allmodules = rp.allmodules
DOCUMENTED_MARKER = "verified"
ERROR_001_NOTACLASS = 1
ERROR_002_NOTASTRUCT = 2
ERROR_003_INCORRECTBASE = 3
ERROR_004_MISSEDNAMESPACE = 4
ERROR_005_MISSINGPYFUNC = 5
ERROR_006_INVALIDPYOLDDOC = 6
ERROR_007_INVALIDPYDOC = 7
ERROR_008_CFUNCISNOTGLOBAL = 8
ERROR_009_OVERLOADNOTFOUND = 9
ERROR_010_UNKNOWNCLASS = 10
ERROR_011_UNKNOWNFUNC = 11
do_python_crosscheck = True
errors_disabled = [ERROR_004_MISSEDNAMESPACE]
doc_signatures_whitelist = [
# templates
"Matx", "Vec", "SparseMat_", "Scalar_", "Mat_", "Ptr", "Size_", "Point_", "Rect_", "Point3_",
"DataType", "detail::RotationWarperBase", "flann::Index_", "CalonderDescriptorExtractor",
"gpu::DevMem2D_", "gpu::PtrStep_", "gpu::PtrElemStep_", "gpu::BruteForceMatcher_GPU",
# black boxes
"CvArr", "CvFileStorage",
# other
"InputArray", "OutputArray",
]
defines = ["cvGraphEdgeIdx", "cvFree", "CV_Assert", "cvSqrt", "cvGetGraphVtx", "cvGraphVtxIdx",
"cvCaptureFromFile", "cvCaptureFromCAM", "cvCalcBackProjectPatch", "cvCalcBackProject",
"cvGetHistValue_1D", "cvGetHistValue_2D", "cvGetHistValue_3D", "cvGetHistValue_nD",
"cvQueryHistValue_1D", "cvQueryHistValue_2D", "cvQueryHistValue_3D", "cvQueryHistValue_nD",
# not a real function but behaves as function
"Mat::size",
# ugly "virtual" functions from ml module
"CvStatModel::train", "CvStatModel::predict",
# TODO:
"cvExtractSURF"
]
synonims = {
"StarDetector" : ["StarFeatureDetector"],
"MSER" : ["MserFeatureDetector"],
"GFTTDetector" : ["GoodFeaturesToTrackDetector"],
"cvCaptureFromFile" : ["cvCreateFileCapture"],
"cvCaptureFromCAM" : ["cvCreateCameraCapture"],
"cvCalcArrBackProjectPatch" : ["cvCalcBackProjectPatch"],
"cvCalcArrBackProject" : ["cvCalcBackProject"],
"InputArray" : ["_InputArray"],
"OutputArray" : ["_OutputArray"],
}
if do_python_crosscheck:
try:
import cv2
except ImportError:
print "Could not load cv2"
do_python_crosscheck = False
def get_cv2_object(name):
if name.startswith("cv2."):
name = name[4:]
if name.startswith("cv."):
name = name[3:]
if name == "Algorithm":
return cv2.Algorithm__create("Feature2D.ORB"), name
elif name == "FeatureDetector":
return cv2.FeatureDetector_create("ORB"), name
elif name == "DescriptorExtractor":
return cv2.DescriptorExtractor_create("ORB"), name
elif name == "BackgroundSubtractor":
return cv2.BackgroundSubtractorMOG(), name
elif name == "StatModel":
return cv2.KNearest(), name
else:
return getattr(cv2, name)(), name
def compareSignatures(f, s):
# function names
if f[0] != s[0]:
return False, "name mismatch"
# return type
stype = (s[1] or "void")
ftype = f[1]
stype = re.sub(r"\b(cv|std)::", "", stype)
if ftype:
ftype = re.sub(r"\b(cv|std)::", "", ftype)
if ftype and ftype != stype:
return False, "return type mismatch"
if ("\C" in f[2]) ^ ("\C" in s[2]):
return False, "const qualifier mismatch"
if ("\S" in f[2]) ^ ("\S" in s[2]):
return False, "static qualifier mismatch"
if ("\V" in f[2]) ^ ("\V" in s[2]):
return False, "virtual qualifier mismatch"
if ("\A" in f[2]) ^ ("\A" in s[2]):
return False, "abstract qualifier mismatch"
if len(f[3]) != len(s[3]):
return False, "different number of arguments"
for idx, arg in enumerate(zip(f[3], s[3])):
farg = arg[0]
sarg = arg[1]
ftype = re.sub(r"\b(cv|std)::", "", (farg[0] or ""))
stype = re.sub(r"\b(cv|std)::", "", (sarg[0] or ""))
if ftype != stype:
return False, "type of argument #" + str(idx+1) + " mismatch"
fname = farg[1] or "arg" + str(idx)
sname = sarg[1] or "arg" + str(idx)
if fname != sname:
return False, "name of argument #" + str(idx+1) + " mismatch"
fdef = re.sub(r"\b(cv|std)::", "", (farg[2] or ""))
sdef = re.sub(r"\b(cv|std)::", "", (sarg[2] or ""))
if fdef != sdef:
return False, "default value of argument #" + str(idx+1) + " mismatch"
return True, "match"
def formatSignature(s):
_str = ""
if "/V" in s[2]:
_str += "virtual "
if "/S" in s[2]:
_str += "static "
if s[1]:
_str += s[1] + " "
else:
if not bool(re.match(r"(\w+\.)*(?P<cls>\w+)\.(?P=cls)", s[0])):
_str += "void "
if s[0].startswith("cv."):
_str += s[0][3:].replace(".", "::")
else:
_str += s[0].replace(".", "::")
if len(s[3]) == 0:
_str += "()"
else:
_str += "( "
for idx, arg in enumerate(s[3]):
if idx > 0:
_str += ", "
argtype = re.sub(r"\bcv::", "", arg[0])
bidx = argtype.find('[')
if bidx < 0:
_str += argtype + " "
else:
_srt += argtype[:bidx]
if arg[1]:
_str += arg[1]
else:
_str += "arg" + str(idx)
if bidx >= 0:
_str += argtype[bidx:]
if arg[2]:
_str += "=" + re.sub(r"\bcv::", "", arg[2])
_str += " )"
if "/C" in s[2]:
_str += " const"
if "/A" in s[2]:
_str += " = 0"
return _str
def logerror(code, message, doc = None):
if code in errors_disabled:
return
if doc:
print doc["file"] + ":" + str(doc["line"]),
print "error %03d: %s" % (code, message)
#print
def process_module(module, path):
hppparser = hp.CppHeaderParser()
rstparser = rp.RstParser(hppparser)
rstparser.parse(module, path)
rst = rstparser.definitions
hdrlist = glob.glob(os.path.join(path, "include", "opencv2", module, "*.h*"))
hdrlist.extend(glob.glob(os.path.join(path, "include", "opencv2", module, "detail", "*.h*")))
if module == "gpu":
hdrlist.append(os.path.join(path, "..", "core", "include", "opencv2", "core", "devmem2d.hpp"))
hdrlist.append(os.path.join(path, "..", "core", "include", "opencv2", "core", "gpumat.hpp"))
decls = []
for hname in hdrlist:
if not "ts_gtest.h" in hname:
decls += hppparser.parse(hname, wmode=False)
funcs = []
# not really needed to hardcode all the namespaces. Normally all they are collected automatically
namespaces = ['cv', 'cv.gpu', 'cvflann', 'cvflann.anyimpl', 'cvflann.lsh', 'cv.flann', 'cv.linemod', 'cv.detail', 'cvtest', 'perf', 'cv.videostab']
classes = []
structs = []
# collect namespaces and classes/structs
for decl in decls:
if decl[0].startswith("const"):
pass
elif decl[0].startswith("class") or decl[0].startswith("struct"):
if decl[0][0] == 'c':
classes.append(decl)
else:
structs.append(decl)
dotIdx = decl[0].rfind('.')
if dotIdx > 0:
namespace = decl[0][decl[0].find(' ')+1:dotIdx]
if not [c for c in classes if c[0].endswith(namespace)] and not [s for s in structs if s[0].endswith(namespace)]:
if namespace not in namespaces:
namespaces.append(namespace)
else:
funcs.append(decl)
clsnamespaces = []
# process classes
for cl in classes:
name = cl[0][cl[0].find(' ')+1:]
if name.find('.') < 0 and not name.startswith("Cv"):
logerror(ERROR_004_MISSEDNAMESPACE, "class " + name + " from opencv_" + module + " is placed in global namespace but violates C-style naming convention")
clsnamespaces.append(name)
if do_python_crosscheck and not name.startswith("cv.") and name.startswith("Cv"):
clsnamespaces.append("cv." + name[2:])
if name.startswith("cv."):
name = name[3:]
name = name.replace(".", "::")
sns = synonims.get(name, [])
sns.append(name)
for name in sns:
doc = rst.get(name)
if not doc:
#TODO: class is not documented
continue
doc[DOCUMENTED_MARKER] = True
# verify class marker
if not doc.get("isclass"):
logerror(ERROR_001_NOTACLASS, "class " + name + " is not marked as \"class\" in documentation", doc)
else:
# verify base
signature = doc.get("class", "")
signature = signature.replace(" public ", " ")
namespaceIdx = signature.rfind("::")
signature = ("class " + signature).strip()
hdrsignature = ("class " + name + " " + cl[1]).replace(".", "::").replace("cv::","").strip()
if signature != hdrsignature:
logerror(ERROR_003_INCORRECTBASE, "invalid base class documentation\ndocumented: " + signature + "\nactual: " + hdrsignature, doc)
# process structs
for st in structs:
name = st[0][st[0].find(' ')+1:]
if name.find('.') < 0 and not name.startswith("Cv"):
logerror(ERROR_004_MISSEDNAMESPACE, "struct " + name + " from opencv_" + module + " is placed in global namespace but violates C-style naming convention")
clsnamespaces.append(name)
if name.startswith("cv."):
name = name[3:]
name = name.replace(".", "::")
doc = rst.get(name)
if not doc:
#TODO: struct is not documented
continue
doc[DOCUMENTED_MARKER] = True
# verify struct marker
if not doc.get("isstruct"):
logerror(ERROR_002_NOTASTRUCT, "struct " + name + " is not marked as \"struct\" in documentation", doc)
else:
# verify base
signature = doc.get("class", "")
signature = signature.replace(", public ", " ").replace(" public ", " ")
signature = signature.replace(", protected ", " ").replace(" protected ", " ")
signature = signature.replace(", private ", " ").replace(" private ", " ")
signature = ("struct " + signature).strip()
hdrsignature = (st[0] + " " + st[1]).replace("struct cv.", "struct ").replace(".", "::").strip()
if signature != hdrsignature:
logerror(ERROR_003_INCORRECTBASE, "invalid base struct documentation\ndocumented: " + signature + "\nactual: " + hdrsignature, doc)
print st, doc
# process functions and methods
flookup = {}
for fn in funcs:
name = fn[0]
parent = None
namespace = None
for cl in clsnamespaces:
if name.startswith(cl + "."):
if cl.startswith(parent or ""):
parent = cl
if parent:
name = name[len(parent) + 1:]
for nm in namespaces:
if parent.startswith(nm + "."):
if nm.startswith(namespace or ""):
namespace = nm
if namespace:
parent = parent[len(namespace) + 1:]
else:
for nm in namespaces:
if name.startswith(nm + "."):
if nm.startswith(namespace or ""):
namespace = nm
if namespace:
name = name[len(namespace) + 1:]
#print namespace, parent, name, fn[0]
if not namespace and not parent and not name.startswith("cv") and not name.startswith("CV_"):
logerror(ERROR_004_MISSEDNAMESPACE, "function " + name + " from opencv_" + module + " is placed in global namespace but violates C-style naming convention")
else:
fdescr = (namespace, parent, name, fn)
flookup_entry = flookup.get(fn[0], [])
flookup_entry.append(fdescr)
flookup[fn[0]] = flookup_entry
if do_python_crosscheck:
for name, doc in rst.iteritems():
decls = doc.get("decls")
if not decls:
continue
for signature in decls:
if signature[0] == "Python1":
pname = signature[1][:signature[1].find('(')]
try:
fn = getattr(cv2.cv, pname[3:])
docstr = "cv." + fn.__doc__
except AttributeError:
logerror(ERROR_005_MISSINGPYFUNC, "could not load documented function: cv2." + pname, doc)
continue
docstring = docstr
sign = signature[1]
signature.append(DOCUMENTED_MARKER)
# convert old signature to pydoc style
if docstring.endswith("*"):
docstring = docstring[:-1]
s = None
while s != sign:
s = sign
sign = re.sub(r"^(.*\(.*)\(.*?\)(.*\) *->)", "\\1_\\2", sign)
s = None
while s != sign:
s = sign
sign = re.sub(r"\s*,\s*([^,]+)\s*=\s*[^,]+\s*(( \[.*\])?)\)", " [, \\1\\2])", sign)
sign = re.sub(r"\(\s*([^,]+)\s*=\s*[^,]+\s*(( \[.*\])?)\)", "([\\1\\2])", sign)
sign = re.sub(r"\)\s*->\s*", ") -> ", sign)
sign = sign.replace("-> convexHull", "-> CvSeq")
sign = sign.replace("-> lines", "-> CvSeq")
sign = sign.replace("-> boundingRects", "-> CvSeq")
sign = sign.replace("-> contours", "-> CvSeq")
sign = sign.replace("-> retval", "-> int")
sign = sign.replace("-> detectedObjects", "-> CvSeqOfCvAvgComp")
def retvalRplace(match):
m = match.group(1)
m = m.replace("CvScalar", "scalar")
m = m.replace("CvMemStorage", "memstorage")
m = m.replace("ROIplImage", "image")
m = m.replace("IplImage", "image")
m = m.replace("ROCvMat", "mat")
m = m.replace("CvMat", "mat")
m = m.replace("double", "float")
m = m.replace("CvSubdiv2DPoint", "point")
m = m.replace("CvBox2D", "Box2D")
m = m.replace("IplConvKernel", "kernel")
m = m.replace("CvHistogram", "hist")
m = m.replace("CvSize", "width,height")
m = m.replace("cvmatnd", "matND")
m = m.replace("CvSeqOfCvConvexityDefect", "convexityDefects")
mm = m.split(',')
if len(mm) > 1:
return "(" + ", ".join(mm) + ")"
else:
return m
docstring = re.sub(r"(?<=-> )(.*)$", retvalRplace, docstring)
docstring = docstring.replace("( [, ", "([")
if sign != docstring:
logerror(ERROR_006_INVALIDPYOLDDOC, "old-style documentation differs from pydoc\npydoc: " + docstring + "\nfixup: " + sign + "\ncvdoc: " + signature[1], doc)
elif signature[0] == "Python2":
pname = signature[1][4:signature[1].find('(')]
cvname = "cv." + pname
parent = None
for cl in clsnamespaces:
if cvname.startswith(cl + "."):
if cl.startswith(parent or ""):
parent = cl
try:
if parent:
instance, clsname = get_cv2_object(parent)
fn = getattr(instance, cvname[len(parent)+1:])
docstr = fn.__doc__
docprefix = "cv2." + clsname + "."
else:
fn = getattr(cv2, pname)
docstr = fn.__doc__
docprefix = "cv2."
except AttributeError:
if parent:
logerror(ERROR_005_MISSINGPYFUNC, "could not load documented member of " + parent + " class: cv2." + pname, doc)
else:
logerror(ERROR_005_MISSINGPYFUNC, "could not load documented function cv2." + pname, doc)
signature.append(DOCUMENTED_MARKER) # stop subsequent errors
continue
docstrings = [docprefix + s.replace("([, ", "([") for s in docstr.split(" or ")]
if not signature[1] in docstrings:
pydocs = "\npydoc: ".join(docstrings)
logerror(ERROR_007_INVALIDPYDOC, "documentation differs from pydoc\npydoc: " + pydocs + "\ncvdoc: " + signature[1], doc)
signature.append(DOCUMENTED_MARKER)
# verify C/C++ signatures
for name, doc in rst.iteritems():
decls = doc.get("decls")
if not decls:
continue
for signature in decls:
if signature[0] == "C" or signature[0] == "C++":
if "template" in (signature[2][1] or ""):
# TODO find a way to validate templates
signature.append(DOCUMENTED_MARKER)
continue
fd = flookup.get(signature[2][0])
if not fd:
if signature[2][0].startswith("cv."):
fd = flookup.get(signature[2][0][3:])
if not fd:
continue
else:
signature[2][0] = signature[2][0][3:]
if signature[0] == "C":
ffd = [f for f in fd if not f[0] and not f[1]] # filter out C++ stuff
if not ffd:
if fd[0][1]:
logerror(ERROR_008_CFUNCISNOTGLOBAL, "function " + fd[0][2] + " is documented as C function but is actually member of " + fd[0][1] + " class", doc)
elif fd[0][0]:
logerror(ERROR_008_CFUNCISNOTGLOBAL, "function " + fd[0][2] + " is documented as C function but is actually placed in " + fd[0][0] + " namespace", doc)
fd = ffd
error = None
for f in fd:
match, error = compareSignatures(signature[2], f[3])
if match:
signature.append(DOCUMENTED_MARKER)
break
if signature[-1] != DOCUMENTED_MARKER:
candidates = "\n\t".join([formatSignature(f[3]) for f in fd])
logerror(ERROR_009_OVERLOADNOTFOUND, signature[0] + " function " + signature[2][0].replace(".","::") + " is documented but misses in headers (" + error + ").\nDocumented as:\n\t" + signature[1] + "\nCandidates are:\n\t" + candidates, doc)
signature.append(DOCUMENTED_MARKER) # to stop subsequent error on this function
# verify that all signatures was found in the library headers
for name, doc in rst.iteritems():
# if doc.get(DOCUMENTED_MARKER, False):
# continue # this class/struct was found
if not doc.get(DOCUMENTED_MARKER, False) and (doc.get("isclass", False) or doc.get("isstruct", False)):
if name in doc_signatures_whitelist:
continue
logerror(ERROR_010_UNKNOWNCLASS, "class/struct " + name + " is mentioned in documentation but is not found in OpenCV headers", doc)
for d in doc.get("decls", []):
if d[-1] != DOCUMENTED_MARKER:
if d[0] == "C" or d[0] =="C++" or (do_python_crosscheck and d[0].startswith("Python")):
if d[0][0] == 'C':
sname = d[2][0][3:].replace(".", "::")
if sname in defines:
#TODO: need to find a way to verify #define's
continue
else:
sname = d[1][:d[1].find("(")]
prefixes = [x for x in doc_signatures_whitelist if sname.startswith(x)]
if prefixes:
# TODO: member of template class
continue
logerror(ERROR_011_UNKNOWNFUNC, d[0] + " function " + sname + " is documented but is not found in OpenCV headers. It is documented as:\n\t" + d[1], doc)
# end of process_module
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage:\n", os.path.basename(sys.argv[0]), " <module path>"
exit(0)
modules = sys.argv[1:]
if modules[0] == "all":
modules = allmodules
for module in modules:
selfpath = os.path.dirname(os.path.abspath(sys.argv[0]))
module_path = os.path.join(selfpath, "..", "modules", module)
if not os.path.isdir(module_path):
print "Module \"" + module + "\" could not be found."
exit(1)
process_module(module, module_path)
+3 -3
View File
@@ -231,9 +231,9 @@ latex_documents = [
('modules/refman', 'opencv2refman.tex', u'The OpenCV Reference Manual',
u'', 'manual'),
('doc/user_guide/user_guide', 'opencv_user.tex', u'The OpenCV User Guide',
u'', 'manual'),
u'', 'manual'),
('doc/tutorials/tutorials', 'opencv_tutorials.tex', u'The OpenCV Tutorials',
u'', 'manual'),
u'', 'manual'),
]
preamble ="""
@@ -303,7 +303,7 @@ extlinks = {
'calib3d' : ('http://opencv.itseez.com/trunk/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#%s', None ),
'feature2d' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/feature_detection.html#%s', None ),
'imgproc_geometric' : ('http://opencv.itseez.com/trunk/modules/imgproc/doc/geometric_transformations.html#%s', None ),
'opencv_group' : ('http://tech.groups.yahoo.com/group/OpenCV/%s', None),
'cvt_color': ('http://opencv.itseez.com/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor%s', None),
+74 -25
View File
@@ -25,7 +25,7 @@ from sphinx.util.nodes import make_refnode
from sphinx.util.compat import Directive
from sphinx.util.docfields import Field, GroupedField, TypedField
########################### Python Part ###########################
########################### Python Part ###########################
# REs for Python signatures
py_sig_re = re.compile(
@@ -292,9 +292,10 @@ class OCVPyXRefRole(XRefRole):
return title, target
########################### C/C++/Java Part ###########################
########################### C/C++/Java Part ###########################
_identifier_re = re.compile(r'(~?\b[a-zA-Z_][a-zA-Z0-9_]*)\b')
_identifier_re = re.compile(r'(~?\b[a-zA-Z_][a-zA-Z0-9_]*\b)')
_argument_name_re = re.compile(r'(~?\b[a-zA-Z_][a-zA-Z0-9_]*\b(?:\[\d*\])?|\.\.\.)')
_whitespace_re = re.compile(r'\s+(?u)')
_string_re = re.compile(r"[LuU8]?('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)
@@ -303,10 +304,10 @@ _operator_re = re.compile(r'''(?x)
\[\s*\]
| \(\s*\)
| (<<|>>)=?
| \+\+ | -- | ->\*?
| [!<>=/*%+|&^-]=?
| \+\+ | --
| ~ | && | \| | \|\|
| ->\*? | \,
| \,
''')
_id_shortwords = {
@@ -561,7 +562,7 @@ class ConstDefExpr(WrappingDefExpr):
def __unicode__(self):
return (self.prefix and u'const %s' or u'%s const') % self.typename
class ConstTemplateDefExpr(WrappingDefExpr):
def __init__(self, typename, prefix=False):
@@ -667,13 +668,14 @@ class MemberObjDefExpr(NamedDefExpr):
class FuncDefExpr(NamedDefExpr):
def __init__(self, name, visibility, static, explicit, rv,
signature, const, pure_virtual):
signature, const, pure_virtual, virtual):
NamedDefExpr.__init__(self, name, visibility, static)
self.rv = rv
self.signature = signature
self.explicit = explicit
self.const = const
self.pure_virtual = pure_virtual
self.virtual = virtual
def get_id(self):
return u'%s%s%s' % (
@@ -682,11 +684,13 @@ class FuncDefExpr(NamedDefExpr):
u'.'.join(x.get_id() for x in self.signature) or u'',
self.const and u'C' or u''
)
def __unicode__(self):
buf = self.get_modifiers()
if self.explicit:
buf.append(u'explicit')
if self.virtual:
buf.append(u'virtual')
if self.rv is not None:
buf.append(unicode(self.rv))
buf.append(u'%s(%s)' % (self.name, u', '.join(
@@ -700,8 +704,9 @@ class FuncDefExpr(NamedDefExpr):
class ClassDefExpr(NamedDefExpr):
def __init__(self, name, visibility, static):
def __init__(self, name, visibility, static, parents = None):
NamedDefExpr.__init__(self, name, visibility, static)
self.parents = parents
def get_id(self):
return self.name.get_id()
@@ -788,7 +793,6 @@ class DefinitionParser(object):
if self.match(_operator_re):
return NameDefExpr('operator' +
_whitespace_re.sub('', self.matched_text))
# new/delete operator?
for allocop in 'new', 'delete':
if not self.skip_word(allocop):
@@ -807,7 +811,7 @@ class DefinitionParser(object):
return CastOpDefExpr(type)
def _parse_name(self):
if not self.match(_identifier_re):
if not self.match(_argument_name_re):
self.fail('expected name')
identifier = self.matched_text
@@ -981,7 +985,7 @@ class DefinitionParser(object):
elif paren_stack_depth == 0:
break
self.pos = idx+1
rv = self.definition[rv_start:idx]
self.pos = idx
return rv
@@ -1004,8 +1008,13 @@ class DefinitionParser(object):
self.skip_ws()
argtype = self._parse_type()
argname = default = None
self.skip_ws()
if unicode(argtype) == u"...":
if not self.skip_string(')'):
self.fail("var arg must be the last argument")
args.append(ArgumentDefExpr(None, argtype, None))
break
argname = default = None
if self.skip_string('='):
self.pos += 1
default = self._parse_default_expr()
@@ -1072,6 +1081,11 @@ class DefinitionParser(object):
self.skip_ws()
else:
explicit = False
if self.skip_word('virtual'):
virtual = True
self.skip_ws()
else:
virtual = False
rv = self._parse_type()
self.skip_ws()
# some things just don't have return values
@@ -1080,12 +1094,27 @@ class DefinitionParser(object):
rv = None
else:
name = self._parse_type()
return FuncDefExpr(name, visibility, static, explicit, rv,
*self._parse_signature())
return FuncDefExpr(name, visibility, static, explicit, rv,
*self._parse_signature(), virtual = virtual)
def parse_class(self):
visibility, static = self._parse_visibility_static()
return ClassDefExpr(self._parse_type(), visibility, static)
typename = self._parse_type()
parent = None
self.skip_ws()
parents = []
if self.skip_string(':'):
while not self.eof:
self.skip_ws()
classname_pos = self.pos
pvisibility, pstatic = self._parse_visibility_static()
if pstatic:
self.fail('unsepected static keyword, got %r' %
self.definition[self.classname_pos:])
parents.append(ClassDefExpr(self._parse_type(), pvisibility, pstatic))
if not self.skip_string(','):
break
return ClassDefExpr(typename, visibility, static, parents)
def read_rest(self):
rv = self.definition[self.pos:]
@@ -1138,7 +1167,7 @@ class OCVObject(ObjectDescription):
lname = self.__class__.langname
node += nodes.strong(lname + ":", lname + ":")
node += addnodes.desc_name(" ", " ")
if obj.visibility != 'public':
node += addnodes.desc_annotation(obj.visibility,
obj.visibility)
@@ -1212,8 +1241,8 @@ class OCVClassObject(OCVObject):
object_annotation = "class "
object_long_name = "class"
def attach_modifiers(self, node, obj):
if obj.visibility != 'public':
def attach_modifiers(self, node, obj, skip_visibility = 'public'):
if obj.visibility != skip_visibility:
node += addnodes.desc_annotation(obj.visibility,
obj.visibility)
node += nodes.Text(' ')
@@ -1231,6 +1260,15 @@ class OCVClassObject(OCVObject):
self.attach_modifiers(signode, cls)
signode += addnodes.desc_annotation(self.__class__.object_annotation, self.__class__.object_annotation)
self.attach_name(signode, cls.name)
first_parent = True
for p in cls.parents:
if first_parent:
signode += nodes.Text(' : ')
first_parent = False
else:
signode += nodes.Text(', ')
self.attach_modifiers(signode, p, None)
self.attach_name(signode, p.name)
class OCVStructObject(OCVClassObject):
object_annotation = "struct "
@@ -1263,6 +1301,9 @@ class OCVMemberObject(OCVObject):
return ''
def parse_definition(self, parser):
parent_class = self.env.temp_data.get('ocv:parent')
if parent_class is None:
parser.fail("missing parent structure/class")
return parser.parse_member_object()
def describe_signature(self, signode, obj):
@@ -1298,7 +1339,12 @@ class OCVFunctionObject(OCVObject):
self.attach_type(param, arg.type)
param += nodes.Text(u' ')
#param += nodes.emphasis(unicode(arg.name), unicode(arg.name))
param += nodes.strong(unicode(arg.name), unicode(arg.name))
sbrIdx = unicode(arg.name).find("[")
if sbrIdx < 0:
param += nodes.strong(unicode(arg.name), unicode(arg.name))
else:
param += nodes.strong(unicode(arg.name)[:sbrIdx], unicode(arg.name)[:sbrIdx])
param += nodes.Text(unicode(arg.name)[sbrIdx:])
if arg.default is not None:
def_ = u'=' + unicode(arg.default)
#param += nodes.emphasis(def_, def_)
@@ -1325,6 +1371,9 @@ class OCVFunctionObject(OCVObject):
if func.explicit:
signode += addnodes.desc_annotation('explicit', 'explicit')
signode += nodes.Text(' ')
if func.virtual:
signode += addnodes.desc_annotation('virtual', 'virtual')
signode += nodes.Text(' ')
# return value is None for things with a reverse return value
# such as casting operator definitions or constructors
# and destructors.
@@ -1380,7 +1429,7 @@ class OCVXRefRole(XRefRole):
class OCVCFunctionObject(OCVFunctionObject):
langname = "C"
class OCVJavaFunctionObject(OCVFunctionObject):
langname = "Java"
@@ -1430,7 +1479,7 @@ class OCVDomain(Domain):
initial_data = {
'objects': {}, # fullname -> docname, objtype
}
def __init__(self, env):
Domain.__init__(self, env)
self.data['objects2'] = {}
@@ -1496,14 +1545,14 @@ class OCVDomain(Domain):
def get_objects(self):
for refname, (docname, type, theid) in self.data['objects'].iteritems():
yield (refname, refname, type, docname, refname, 1)
def get_type_name(self, type, primary=False):
"""
Return full name for given ObjType.
"""
if primary:
return type.lname
return {
'class': _('C++ class'),
'struct': _('C/C++ struct'),
@@ -1516,6 +1565,6 @@ class OCVDomain(Domain):
'type': _('C/C++ type'),
'namespace': _('C++ namespace'),
}.get(type.lname, _('%s %s') % (self.label, type.lname))
def setup(app):
app.add_domain(OCVDomain)
+44433 -44248
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
@@ -199,7 +199,7 @@ protected:
int is_supported(const char* supp_modes_key, const char* mode)
{
const char* supported_modes = params.get(supp_modes_key);
return strstr(supported_modes, mode) > 0;
return (supported_modes && mode && (strstr(supported_modes, mode) > 0));
}
float getFocusDistance(int focus_distance_type)
@@ -111,11 +111,11 @@ calibrateCamera
---------------
Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
.. ocv:function:: double calibrateCamera( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags=0, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON))
.. ocv:function:: double calibrateCamera( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags=0, TermCriteria criteria=TermCriteria( TermCriteria::COUNT+TermCriteria::EPS, 30, DBL_EPSILON) )
.. ocv:pyfunction:: cv2.calibrateCamera(objectPoints, imagePoints, imageSize[, cameraMatrix[, distCoeffs[, rvecs[, tvecs[, flags[, criteria]]]]]]) -> retval, cameraMatrix, distCoeffs, rvecs, tvecs
.. ocv:cfunction:: double cvCalibrateCamera2(const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* pointCounts, CvSize imageSize, CvMat* cameraMatrix, CvMat* distCoeffs, CvMat* rvecs=NULL, CvMat* tvecs=NULL, int flags=0, CvTermCriteria term_crit = cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON) )
.. ocv:cfunction:: double cvCalibrateCamera2( const CvMat* object_points, const CvMat* image_points, const CvMat* point_counts, CvSize image_size, CvMat* camera_matrix, CvMat* distortion_coeffs, CvMat* rotation_vectors=NULL, CvMat* translation_vectors=NULL, int flags=0, CvTermCriteria term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON) )
.. ocv:pyoldfunction:: cv.CalibrateCamera2(objectPoints, imagePoints, pointCounts, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags=0)-> None
@@ -127,7 +127,7 @@ Finds the camera intrinsic and extrinsic parameters from several views of a cali
In the old interface all the vectors of object points from different views are concatenated together.
:param pointCounts: In the old interface this is a vector of integers, containing as many elements, as the number of views of the calibration pattern. Each element is the number of points in each view. Usually, all the elements are the same and equal to the number of feature points on the calibration pattern.
:param point_counts: In the old interface this is a vector of integers, containing as many elements, as the number of views of the calibration pattern. Each element is the number of points in each view. Usually, all the elements are the same and equal to the number of feature points on the calibration pattern.
:param imageSize: Size of the image used only to initialize the intrinsic camera matrix.
@@ -268,7 +268,7 @@ For points in an image of a stereo pair, computes the corresponding epilines in
.. ocv:function:: void computeCorrespondEpilines( InputArray points, int whichImage, InputArray F, OutputArray lines )
.. ocv:cfunction:: void cvComputeCorrespondEpilines( const CvMat* points, int whichImage, const CvMat* F, CvMat* lines)
.. ocv:cfunction:: void cvComputeCorrespondEpilines( const CvMat* points, int which_image, const CvMat* fundamental_matrix, CvMat* correspondent_lines )
.. ocv:pyoldfunction:: cv.ComputeCorrespondEpilines(points, whichImage, F, lines) -> None
@@ -344,10 +344,8 @@ Converts points to/from homogeneous coordinates.
.. ocv:function:: void convertPointsHomogeneous( InputArray src, OutputArray dst )
.. ocv:pyfunction:: cv2.convertPointsHomogeneous(src[, dst]) -> dst
.. ocv:cfunction:: void cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst )
.. ocv:pyoldfunction:: cv.ConvertPointsHomogeneous( src, dst ) -> None
.. ocv:pyoldfunction:: cv.ConvertPointsHomogeneous(src, dst) -> None
:param src: Input array or vector of 2D, 3D, or 4D points.
@@ -391,7 +389,7 @@ Decomposes a projection matrix into a rotation matrix and a camera matrix.
.. ocv:pyfunction:: cv2.decomposeProjectionMatrix(projMatrix[, cameraMatrix[, rotMatrix[, transVect[, rotMatrixX[, rotMatrixY[, rotMatrixZ[, eulerAngles]]]]]]]) -> cameraMatrix, rotMatrix, transVect, rotMatrixX, rotMatrixY, rotMatrixZ, eulerAngles
.. ocv:cfunction:: void cvDecomposeProjectionMatrix( const CvMat *projMatrix, CvMat *cameraMatrix, CvMat *rotMatrix, CvMat *transVect, CvMat *rotMatrX=NULL, CvMat *rotMatrY=NULL, CvMat *rotMatrZ=NULL, CvPoint3D64f *eulerAngles=NULL)
.. ocv:cfunction:: void cvDecomposeProjectionMatrix( const CvMat * projMatr, CvMat * calibMatr, CvMat * rotMatr, CvMat * posVect, CvMat * rotMatrX=NULL, CvMat * rotMatrY=NULL, CvMat * rotMatrZ=NULL, CvPoint3D64f * eulerAngles=NULL )
.. ocv:pyoldfunction:: cv.DecomposeProjectionMatrix(projMatrix, cameraMatrix, rotMatrix, transVect, rotMatrX=None, rotMatrY=None, rotMatrZ=None) -> eulerAngles
@@ -428,7 +426,7 @@ Renders the detected chessboard corners.
.. ocv:pyfunction:: cv2.drawChessboardCorners(image, patternSize, corners, patternWasFound) -> None
.. ocv:cfunction:: void cvDrawChessboardCorners( CvArr* image, CvSize patternSize, CvPoint2D32f* corners, int count, int patternWasFound )
.. ocv:cfunction:: void cvDrawChessboardCorners( CvArr* image, CvSize pattern_size, CvPoint2D32f* corners, int count, int pattern_was_found )
.. ocv:pyoldfunction:: cv.DrawChessboardCorners(image, patternSize, corners, patternWasFound)-> None
:param image: Destination image. It must be an 8-bit color image.
@@ -447,11 +445,11 @@ findChessboardCorners
-------------------------
Finds the positions of internal corners of the chessboard.
.. ocv:function:: bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, int flags=CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE )
.. ocv:function:: bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE )
.. ocv:pyfunction:: cv2.findChessboardCorners(image, patternSize[, corners[, flags]]) -> retval, corners
.. ocv:cfunction:: int cvFindChessboardCorners( const void* image, CvSize patternSize, CvPoint2D32f* corners, int* cornerCount=NULL, int flags=CV_CALIB_CB_ADAPTIVE_THRESH )
.. ocv:cfunction:: int cvFindChessboardCorners( const void* image, CvSize pattern_size, CvPoint2D32f* corners, int* corner_count=NULL, int flags=CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE )
.. ocv:pyoldfunction:: cv.FindChessboardCorners(image, patternSize, flags=CV_CALIB_CB_ADAPTIVE_THRESH) -> corners
:param image: Source chessboard view. It must be an 8-bit grayscale or color image.
@@ -508,7 +506,7 @@ Finds the centers in the grid of circles.
.. ocv:function:: bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, const Ptr<FeatureDetector> &blobDetector = new SimpleBlobDetector() )
.. ocv:pyfunction:: cv2.findCirclesGridDefault(image, patternSize[, centers[, flags]]) -> centers
.. ocv:pyfunction:: cv2.findCirclesGridDefault(image, patternSize[, centers[, flags]]) -> retval, centers
:param image: Grid view of source circles. It must be an 8-bit grayscale or color image.
@@ -551,13 +549,13 @@ solvePnP
------------
Finds an object pose from 3D-2D point correspondences.
.. ocv:function:: void solvePnP( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false, int flags = CV_ITERATIVE )
.. ocv:function:: bool solvePnP( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false, int flags=ITERATIVE )
.. ocv:pyfunction:: cv2.solvePnP( objectPoints, imagePoints, cameraMatrix, distCoeffs[, rvec[, tvec[, useExtrinsicGuess[, flags]]]] ) -> rvec, tvec
.. ocv:pyfunction:: cv2.solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs[, rvec[, tvec[, useExtrinsicGuess[, flags]]]]) -> retval, rvec, tvec
.. ocv:cfunction:: void cvFindExtrinsicCameraParams2( const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* cameraMatrix, const CvMat* distCoeffs, CvMat* rvec, CvMat* tvec, int useExtrinsicGuess=0 )
.. ocv:cfunction:: void cvFindExtrinsicCameraParams2( const CvMat* object_points, const CvMat* image_points, const CvMat* camera_matrix, const CvMat* distortion_coeffs, CvMat* rotation_vector, CvMat* translation_vector, int use_extrinsic_guess=0 )
.. ocv:pyoldfunction:: cv.FindExtrinsicCameraParams2( objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, useExtrinsicGuess=0 )-> None
.. ocv:pyoldfunction:: cv.FindExtrinsicCameraParams2(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, useExtrinsicGuess=0 ) -> None
:param objectPoints: Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, where N is the number of points. ``vector<Point3f>`` can be also passed here.
@@ -587,7 +585,7 @@ solvePnPRansac
------------------
Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
.. ocv:function:: void solvePnPRansac( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, OutputArray inliers = noArray(), int flags = CV_ITERATIVE )
.. ocv:function:: void solvePnPRansac( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, OutputArray inliers = noArray(), int flags = ITERATIVE )
.. ocv:pyfunction:: cv2.solvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs[, rvec[, tvec[, useExtrinsicGuess[, iterationsCount[, reprojectionError[, minInliersCount[, inliers[, flags]]]]]]]]) -> rvec, tvec, inliers
@@ -628,8 +626,8 @@ Calculates a fundamental matrix from the corresponding points in two images.
.. ocv:pyfunction:: cv2.findFundamentalMat(points1, points2[, method[, param1[, param2[, mask]]]]) -> retval, mask
.. ocv:cfunction:: int cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, CvMat* fundamentalMatrix, int method=CV_FM_RANSAC, double param1=1., double param2=0.99, CvMat* status=NULL)
.. ocv:pyoldfunction:: cv.FindFundamentalMat(points1, points2, fundamentalMatrix, method=CV_FM_RANSAC, param1=1., param2=0.99, status=None) -> None
.. ocv:cfunction:: int cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, CvMat* fundamental_matrix, int method=CV_FM_RANSAC, double param1=3., double param2=0.99, CvMat* status=NULL )
.. ocv:pyoldfunction:: cv.FindFundamentalMat(points1, points2, fundamentalMatrix, method=CV_FM_RANSAC, param1=1., param2=0.99, status=None) -> retval
:param points1: Array of ``N`` points from the first image. The point coordinates should be floating-point (single or double precision).
@@ -693,9 +691,9 @@ Finds a perspective transformation between two planes.
.. ocv:pyfunction:: cv2.findHomography(srcPoints, dstPoints[, method[, ransacReprojThreshold[, mask]]]) -> retval, mask
.. ocv:cfunction:: void cvFindHomography( const CvMat* srcPoints, const CvMat* dstPoints, CvMat* H, int method=0, double ransacReprojThreshold=3, CvMat* status=NULL)
.. ocv:cfunction:: int cvFindHomography( const CvMat* src_points, const CvMat* dst_points, CvMat* homography, int method=0, double ransacReprojThreshold=3, CvMat* mask=0 )
.. ocv:pyoldfunction:: cv.FindHomography(srcPoints, dstPoints, H, method, ransacReprojThreshold=3.0, status=None)-> None
.. ocv:pyoldfunction:: cv.FindHomography(srcPoints, dstPoints, H, method=0, ransacReprojThreshold=3.0, status=None) -> None
:param srcPoints: Coordinates of the points in the original plane, a matrix of the type ``CV_32FC2`` or ``vector<Point2f>`` .
@@ -717,7 +715,7 @@ Finds a perspective transformation between two planes.
then the point :math:`i` is considered an outlier. If ``srcPoints`` and ``dstPoints`` are measured in pixels, it usually makes sense to set this parameter somewhere in the range of 1 to 10.
:param status: Optional output mask set by a robust method ( ``CV_RANSAC`` or ``CV_LMEDS`` ). Note that the input mask values are ignored.
:param mask: Optional output mask set by a robust method ( ``CV_RANSAC`` or ``CV_LMEDS`` ). Note that the input mask values are ignored.
The functions find and return the perspective transformation :math:`H` between the source and the destination planes:
@@ -773,13 +771,13 @@ estimateAffine3D
--------------------
Computes an optimal affine transformation between two 3D point sets.
.. ocv:function:: int estimateAffine3D(InputArray srcpt, InputArray dstpt, OutputArray out, OutputArray inliers, double ransacThreshold = 3.0, double confidence = 0.99)
.. ocv:function:: int estimateAffine3D(InputArray src, InputArray dst, OutputArray out, OutputArray inliers, double ransacThreshold = 3, double confidence = 0.99)
.. ocv:pyfunction:: cv2.estimateAffine3D(srcpt, dstpt[, out[, inliers[, ransacThreshold[, confidence]]]]) -> retval, out, inliers
.. ocv:pyfunction:: cv2.estimateAffine3D(src, dst[, out[, inliers[, ransacThreshold[, confidence]]]]) -> retval, out, inliers
:param srcpt: First input 3D point set.
:param src: First input 3D point set.
:param dstpt: Second input 3D point set.
:param dst: Second input 3D point set.
:param out: Output 3D affine transformation matrix :math:`3 \times 4` .
@@ -815,13 +813,13 @@ getOptimalNewCameraMatrix
-----------------------------
Returns the new camera matrix based on the free scaling parameter.
.. ocv:function:: Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, double alpha, Size newImageSize=Size(), Rect* validPixROI=0, bool centerPrincipalPoint=false)
.. ocv:function:: Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, double alpha, Size newImgSize=Size(), Rect* validPixROI=0, bool centerPrincipalPoint=false )
.. ocv:pyfunction:: cv2.getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha[, newImgSize[, centerPrincipalPoint]]) -> retval, validPixROI
.. ocv:cfunction:: void cvGetOptimalNewCameraMatrix( const CvMat* cameraMatrix, const CvMat* distCoeffs, CvSize imageSize, double alpha, CvMat* newCameraMatrix, CvSize newImageSize=cvSize(0, 0), CvRect* validPixROI=0, int centerPrincipalPoint=0)
.. ocv:cfunction:: void cvGetOptimalNewCameraMatrix( const CvMat* camera_matrix, const CvMat* dist_coeffs, CvSize image_size, double alpha, CvMat* new_camera_matrix, CvSize new_imag_size=cvSize(0,0), CvRect* valid_pixel_ROI=0, int center_principal_point=0 )
.. ocv:pyoldfunction:: cv.GetOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha, newCameraMatrix, newImageSize=(0, 0), validPixROI=0) -> None
.. ocv:pyoldfunction:: cv.GetOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha, newCameraMatrix, newImageSize=(0, 0), validPixROI=0, centerPrincipalPoint=0) -> None
:param cameraMatrix: Input camera matrix.
@@ -831,9 +829,9 @@ Returns the new camera matrix based on the free scaling parameter.
:param alpha: Free scaling parameter between 0 (when all the pixels in the undistorted image are valid) and 1 (when all the source image pixels are retained in the undistorted image). See :ocv:func:`stereoRectify` for details.
:param newCameraMatrix: Output new camera matrix.
:param new_camera_matrix: Output new camera matrix.
:param newImageSize: Image size after rectification. By default,it is set to ``imageSize`` .
:param new_imag_size: Image size after rectification. By default,it is set to ``imageSize`` .
:param validPixROI: Optional output rectangle that outlines all-good-pixels region in the undistorted image. See ``roi1, roi2`` description in :ocv:func:`stereoRectify` .
@@ -854,15 +852,15 @@ Finds an initial camera matrix from 3D-2D point correspondences.
.. ocv:pyfunction:: cv2.initCameraMatrix2D(objectPoints, imagePoints, imageSize[, aspectRatio]) -> retval
.. ocv:cfunction:: void cvInitIntrinsicParams2D( const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* pointCounts, CvSize imageSize, CvMat* cameraMatrix, double aspectRatio=1.)
.. ocv:cfunction:: void cvInitIntrinsicParams2D( const CvMat* object_points, const CvMat* image_points, const CvMat* npoints, CvSize image_size, CvMat* camera_matrix, double aspect_ratio=1. )
.. ocv:pyoldfunction:: cv.InitIntrinsicParams2D(objectPoints, imagePoints, pointCounts, imageSize, cameraMatrix, aspectRatio=1.) -> None
.. ocv:pyoldfunction:: cv.InitIntrinsicParams2D(objectPoints, imagePoints, npoints, imageSize, cameraMatrix, aspectRatio=1.) -> None
:param objectPoints: Vector of vectors of the calibration pattern points in the calibration pattern coordinate space. In the old interface all the per-view vectors are concatenated. See :ocv:func:`calibrateCamera` for details.
:param imagePoints: Vector of vectors of the projections of the calibration pattern points. In the old interface all the per-view vectors are concatenated.
:param pointCounts: The integer vector of point counters for each view.
:param npoints: The integer vector of point counters for each view.
:param imageSize: Image size in pixels used to initialize the principal point.
@@ -903,7 +901,8 @@ Projects 3D points to an image plane.
.. ocv:pyfunction:: cv2.projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs[, imagePoints[, jacobian[, aspectRatio]]]) -> imagePoints, jacobian
.. ocv:cfunction:: void cvProjectPoints2( const CvMat* objectPoints, const CvMat* rvec, const CvMat* tvec, const CvMat* cameraMatrix, const CvMat* distCoeffs, CvMat* imagePoints, CvMat* dpdrot=NULL, CvMat* dpdt=NULL, CvMat* dpdf=NULL, CvMat* dpdc=NULL, CvMat* dpddist=NULL )
.. ocv:cfunction:: void cvProjectPoints2( const CvMat* object_points, const CvMat* rotation_vector, const CvMat* translation_vector, const CvMat* camera_matrix, const CvMat* distortion_coeffs, CvMat* image_points, CvMat* dpdrot=NULL, CvMat* dpdt=NULL, CvMat* dpdf=NULL, CvMat* dpdc=NULL, CvMat* dpddist=NULL, double aspect_ratio=0 )
.. ocv:pyoldfunction:: cv.ProjectPoints2(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, dpdrot=None, dpdt=None, dpdf=None, dpdc=None, dpddist=None)-> None
:param objectPoints: Array of object points, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel (or ``vector<Point3f>`` ), where N is the number of points in the view.
@@ -943,11 +942,11 @@ reprojectImageTo3D
----------------------
Reprojects a disparity image to 3D space.
.. ocv:function:: void reprojectImageTo3D( InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues=false, int depth=-1 )
.. ocv:function:: void reprojectImageTo3D( InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues=false, int ddepth=-1 )
.. ocv:pyfunction:: cv2.reprojectImageTo3D(disparity, Q[, _3dImage[, handleMissingValues[, ddepth]]]) -> _3dImage
.. ocv:cfunction:: void cvReprojectImageTo3D( const CvArr* disparity, CvArr* _3dImage, const CvMat* Q, int handleMissingValues=0)
.. ocv:cfunction:: void cvReprojectImageTo3D( const CvArr* disparityImage, CvArr* _3dImage, const CvMat* Q, int handleMissingValues=0 )
.. ocv:pyoldfunction:: cv.ReprojectImageTo3D(disparity, _3dImage, Q, handleMissingValues=0) -> None
@@ -978,18 +977,18 @@ RQDecomp3x3
---------------
Computes an RQ decomposition of 3x3 matrices.
.. ocv:function:: Vec3d RQDecomp3x3( InputArray M, OutputArray R, OutputArray Q, OutputArray Qx=noArray(), OutputArray Qy=noArray(), OutputArray Qz=noArray() )
.. ocv:function:: Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, OutputArray Qx=noArray(), OutputArray Qy=noArray(), OutputArray Qz=noArray() )
.. ocv:pyfunction:: cv2.RQDecomp3x3(src[, mtxR[, mtxQ[, Qx[, Qy[, Qz]]]]]) -> retval, mtxR, mtxQ, Qx, Qy, Qz
.. ocv:cfunction:: void cvRQDecomp3x3( const CvMat *M, CvMat *R, CvMat *Q, CvMat *Qx=NULL, CvMat *Qy=NULL, CvMat *Qz=NULL, CvPoint3D64f *eulerAngles=NULL)
.. ocv:cfunction:: void cvRQDecomp3x3( const CvMat * matrixM, CvMat * matrixR, CvMat * matrixQ, CvMat * matrixQx=NULL, CvMat * matrixQy=NULL, CvMat * matrixQz=NULL, CvPoint3D64f * eulerAngles=NULL )
.. ocv:pyoldfunction:: cv.RQDecomp3x3(M, R, Q, Qx=None, Qy=None, Qz=None) -> eulerAngles
:param M: 3x3 input matrix.
:param src: 3x3 input matrix.
:param R: Output 3x3 upper-triangular matrix.
:param mtxR: Output 3x3 upper-triangular matrix.
:param Q: Output 3x3 orthogonal matrix.
:param mtxQ: Output 3x3 orthogonal matrix.
:param Qx: Optional output 3x3 rotation matrix around x-axis.
@@ -1083,11 +1082,11 @@ The constructors.
.. ocv:function:: StereoBM::StereoBM()
.. ocv:function:: StereoBM::StereoBM(int preset, int ndisparities=0, int SADWindowSize=21)
.. ocv:pyfunction:: cv2.StereoBM.StereoBM(preset[, ndisparities[, SADWindowSize]]) -> <StereoBM object>
.. ocv:pyfunction:: cv2.StereoBM([preset[, ndisparities[, SADWindowSize]]]) -> <StereoBM object>
.. ocv:cfunction:: CvStereoBMState* cvCreateStereoBMState( int preset=CV_STEREO_BM_BASIC, int ndisparities=0 )
.. ocv:cfunction:: CvStereoBMState* cvCreateStereoBMState( int preset=CV_STEREO_BM_BASIC, int numberOfDisparities=0 )
.. ocv:pyoldfunction:: cv.CreateStereoBMState(preset=CV_STEREO_BM_BASIC, ndisparities=0)-> StereoBMState
.. ocv:pyoldfunction:: cv.CreateStereoBMState(preset=CV_STEREO_BM_BASIC, numberOfDisparities=0)-> CvStereoBMState
:param preset: specifies the whole set of algorithm parameters, one of:
@@ -1109,7 +1108,7 @@ StereoBM::operator()
-----------------------
Computes disparity using the BM algorithm for a rectified stereo pair.
.. ocv:function:: void StereoBM::operator()(InputArray left, InputArray right, OutputArray disp, int disptype=CV_16S )
.. ocv:function:: void StereoBM::operator()( InputArray left, InputArray right, OutputArray disparity, int disptype=CV_16S )
.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity[, disptype]]) -> disparity
@@ -1121,7 +1120,7 @@ Computes disparity using the BM algorithm for a rectified stereo pair.
:param right: Right image of the same size and the same type as the left one.
:param disp: Output disparity map. It has the same size as the input images. When ``disptype==CV_16S``, the map is a 16-bit signed single-channel image, containing disparity values scaled by 16. To get the true disparity values from such fixed-point representation, you will need to divide each ``disp`` element by 16. If ``disptype==CV_32F``, the disparity map will already contain the real disparity values on output.
:param disparity: Output disparity map. It has the same size as the input images. When ``disptype==CV_16S``, the map is a 16-bit signed single-channel image, containing disparity values scaled by 16. To get the true disparity values from such fixed-point representation, you will need to divide each ``disp`` element by 16. If ``disptype==CV_32F``, the disparity map will already contain the real disparity values on output.
:param disptype: Type of the output disparity map, ``CV_16S`` (default) or ``CV_32F``.
@@ -1182,7 +1181,7 @@ StereoSGBM::StereoSGBM
.. ocv:function:: StereoSGBM::StereoSGBM( int minDisparity, int numDisparities, int SADWindowSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, bool fullDP=false)
.. ocv:pyfunction:: cv2.StereoSGBM.StereoSGBM(minDisparity, numDisparities, SADWindowSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, fullDP]]]]]]]]) -> <StereoSGBM object>
.. ocv:pyfunction:: cv2.StereoSGBM([minDisparity, numDisparities, SADWindowSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, fullDP]]]]]]]]]) -> <StereoSGBM object>
Initializes ``StereoSGBM`` and sets parameters to custom values.??
@@ -1232,129 +1231,17 @@ The method executes the SGBM algorithm on a rectified stereo pair. See ``stereo_
.. note:: The method is not constant, so you should not use the same ``StereoSGBM`` instance from different threads simultaneously.
StereoVar
----------
.. ocv:class:: StereoVar
Class for computing stereo correspondence using the variational matching algorithm ::
class StereoVar
{
StereoVar();
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);
virtual ~StereoVar();
virtual void operator()(InputArray left, InputArray right, OutputArray disp);
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 class implements the modified S. G. Kosov algorithm [Publication] that differs from the original one as follows:
* The automatic initialization of method's parameters is added.
* The method of Smart Iteration Distribution (SID) is implemented.
* The support of Multi-Level Adaptation Technique (MLAT) is not included.
* The method of dynamic adaptation of method's parameters is not included.
StereoVar::StereoVar
--------------------------
.. ocv:function:: StereoVar::StereoVar()
.. ocv:function:: StereoVar::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 constructor
:param levels: The number of pyramid layers, including the initial image. levels=1 means that no extra layers are created and only the original images are used. This parameter is ignored if flag USE_AUTO_PARAMS is set.
:param pyrScale: Specifies the image scale (<1) to build the pyramids for each image. pyrScale=0.5 means the classical pyramid, where each next layer is twice smaller than the previous. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param nIt: The number of iterations the algorithm does at each pyramid level. (If the flag USE_SMART_ID is set, the number of iterations will be redistributed in such a way, that more iterations will be done on more coarser levels.)
:param minDisp: Minimum possible disparity value. Could be negative in case the left and right input images change places.
:param maxDisp: Maximum possible disparity value.
:param poly_n: Size of the pixel neighbourhood used to find polynomial expansion in each pixel. The larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field. Typically, poly_n = 3, 5 or 7
:param poly_sigma: Standard deviation of the Gaussian that is used to smooth derivatives that are used as a basis for the polynomial expansion. For poly_n=5 you can set poly_sigma=1.1 , for poly_n=7 a good value would be poly_sigma=1.5
:param fi: The smoothness parameter, ot the weight coefficient for the smoothness term.
:param lambda: The threshold parameter for edge-preserving smoothness. (This parameter is ignored if PENALIZATION_CHARBONNIER or PENALIZATION_PERONA_MALIK is used.)
:param penalization: Possible values: PENALIZATION_TICHONOV - linear smoothness; PENALIZATION_CHARBONNIER - non-linear edge preserving smoothness; PENALIZATION_PERONA_MALIK - non-linear edge-enhancing smoothness. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param cycle: Type of the multigrid cycle. Possible values: CYCLE_O and CYCLE_V for null- and v-cycles respectively. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param flags: The operation flags; can be a combination of the following:
* USE_INITIAL_DISPARITY: Use the input flow as the initial flow approximation.
* USE_EQUALIZE_HIST: Use the histogram equalization in the pre-processing phase.
* USE_SMART_ID: Use the smart iteration distribution (SID).
* USE_AUTO_PARAMS: Allow the method to initialize the main parameters.
* USE_MEDIAN_FILTERING: Use the median filer of the solution in the post processing phase.
The first constructor initializes ``StereoVar`` with all the default parameters. So, you only have to set ``StereoVar::maxDisp`` and / or ``StereoVar::minDisp`` at minimum. The second constructor enables you to set each parameter to a custom value.
StereoVar::operator ()
-----------------------
.. ocv:function:: void StereoVar::operator()(InputArray left, InputArray right, OutputArray disp)
Computes disparity using the variational algorithm for a rectified stereo pair.
:param left: Left 8-bit single-channel or 3-channel image.
:param right: Right image of the same size and the same type as the left one.
:param disp: Output disparity map. It is a 8-bit signed single-channel image of the same size as the input image.
The method executes the variational algorithm on a rectified stereo pair. See ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method.
**Note**:
The method is not constant, so you should not use the same ``StereoVar`` instance from different threads simultaneously.
stereoCalibrate
-------------------
Calibrates the stereo camera.
.. ocv:function:: double stereoCalibrate( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, Size imageSize, OutputArray R, OutputArray T, OutputArray E, OutputArray F, TermCriteria term_crit = TermCriteria(TermCriteria::COUNT+ TermCriteria::EPS, 30, 1e-6), int flags=CALIB_FIX_INTRINSIC )
.. ocv:function:: double stereoCalibrate( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, Size imageSize, OutputArray R, OutputArray T, OutputArray E, OutputArray F, TermCriteria criteria=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6), int flags=CALIB_FIX_INTRINSIC )
.. ocv:pyfunction:: cv2.stereoCalibrate(objectPoints, imagePoints1, imagePoints2, imageSize[, cameraMatrix1[, distCoeffs1[, cameraMatrix2[, distCoeffs2[, R[, T[, E[, F[, criteria[, flags]]]]]]) -> retval, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, R, T, E, F
.. ocv:pyfunction:: cv2.stereoCalibrate(objectPoints, imagePoints1, imagePoints2, imageSize[, cameraMatrix1[, distCoeffs1[, cameraMatrix2[, distCoeffs2[, R[, T[, E[, F[, criteria[, flags]]]]]]]]]]) -> retval, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, R, T, E, F
.. ocv:cfunction:: double cvStereoCalibrate( const CvMat* objectPoints, const CvMat* imagePoints1, const CvMat* imagePoints2, const CvMat* pointCounts, CvMat* cameraMatrix1, CvMat* distCoeffs1, CvMat* cameraMatrix2, CvMat* distCoeffs2, CvSize imageSize, CvMat* R, CvMat* T, CvMat* E=0, CvMat* F=0, CvTermCriteria termCrit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), int flags=CV_CALIB_FIX_INTRINSIC )
.. ocv:pyoldfunction:: cv.StereoCalibrate( objectPoints, imagePoints1, imagePoints2, pointCounts, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E=None, F=None, termCrit=(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), flags=CV_CALIB_FIX_INTRINSIC)-> None
.. ocv:cfunction:: double cvStereoCalibrate( const CvMat* object_points, const CvMat* image_points1, const CvMat* image_points2, const CvMat* npoints, CvMat* camera_matrix1, CvMat* dist_coeffs1, CvMat* camera_matrix2, CvMat* dist_coeffs2, CvSize image_size, CvMat* R, CvMat* T, CvMat* E=0, CvMat* F=0, CvTermCriteria term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,1e-6), int flags=CV_CALIB_FIX_INTRINSIC )
.. ocv:pyoldfunction:: cv.StereoCalibrate(objectPoints, imagePoints1, imagePoints2, pointCounts, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E=None, F=None, term_crit=(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), flags=CV_CALIB_FIX_INTRINSIC)-> None
:param objectPoints: Vector of vectors of the calibration pattern points.
@@ -1439,10 +1326,11 @@ stereoRectify
-----------------
Computes rectification transforms for each head of a calibrated stereo camera.
.. ocv:function:: void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, Size imageSize, InputArray R, InputArray T, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags=CALIB_ZERO_DISPARITY, double alpha, Size newImageSize=Size(), Rect* roi1=0, Rect* roi2=0 )
.. ocv:function:: void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, InputArray cameraMatrix2, InputArray distCoeffs2, Size imageSize, InputArray R, InputArray T, OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags=CALIB_ZERO_DISPARITY, double alpha=-1, Size newImageSize=Size(), Rect* validPixROI1=0, Rect* validPixROI2=0 )
.. ocv:cfunction:: void cvStereoRectify( const CvMat* cameraMatrix1, const CvMat* cameraMatrix2, const CvMat* distCoeffs1, const CvMat* distCoeffs2, CvSize imageSize, const CvMat* R, const CvMat* T, CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2, CvMat* Q=0, int flags=CV_CALIB_ZERO_DISPARITY, double alpha=-1, CvSize newImageSize=cvSize(0, 0), CvRect* roi1=0, CvRect* roi2=0)
.. ocv:pyoldfunction:: cv.StereoRectify( cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q=None, flags=CV_CALIB_ZERO_DISPARITY, alpha=-1, newImageSize=(0, 0))-> (roi1, roi2)
.. ocv:cfunction:: void cvStereoRectify( const CvMat* camera_matrix1, const CvMat* camera_matrix2, const CvMat* dist_coeffs1, const CvMat* dist_coeffs2, CvSize image_size, const CvMat* R, const CvMat* T, CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2, CvMat* Q=0, int flags=CV_CALIB_ZERO_DISPARITY, double alpha=-1, CvSize new_image_size=cvSize(0,0), CvRect* valid_pix_ROI1=0, CvRect* valid_pix_ROI2=0 )
.. ocv:pyoldfunction:: cv.StereoRectify(cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q=None, flags=CV_CALIB_ZERO_DISPARITY, alpha=-1, newImageSize=(0, 0)) -> (roi1, roi2)
:param cameraMatrix1: First camera matrix.
@@ -1474,9 +1362,9 @@ Computes rectification transforms for each head of a calibrated stereo camera.
:param newImageSize: New image resolution after rectification. The same size should be passed to :ocv:func:`initUndistortRectifyMap` (see the ``stereo_calib.cpp`` sample in OpenCV samples directory). When (0,0) is passed (default), it is set to the original ``imageSize`` . Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion.
:param roi1:
:param validPixROI1: Optional output rectangles inside the rectified images where all the pixels are valid. If ``alpha=0`` , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below).
:param roi2: Optional output rectangles inside the rectified images where all the pixels are valid. If ``alpha=0`` , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below).
:param validPixROI2: Optional output rectangles inside the rectified images where all the pixels are valid. If ``alpha=0`` , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below).
The function computes the rotation matrices for each camera that (virtually) make both camera image planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies the dense stereo correspondence problem. The function takes the matrices computed by
:ocv:func:`stereoCalibrate` as input. As output, it provides two rotation matrices and also two projection matrices in the new coordinates. The function distinguishes the following two cases:
@@ -1529,7 +1417,7 @@ Computes a rectification transform for an uncalibrated stereo camera.
.. ocv:pyfunction:: cv2.stereoRectifyUncalibrated(points1, points2, F, imgSize[, H1[, H2[, threshold]]]) -> retval, H1, H2
.. ocv:cfunction:: void cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2, const CvMat* F, CvSize imageSize, CvMat* H1, CvMat* H2, double threshold=5 )
.. ocv:cfunction:: int cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2, const CvMat* F, CvSize img_size, CvMat* H1, CvMat* H2, double threshold=5 )
.. ocv:pyoldfunction:: cv.StereoRectifyUncalibrated(points1, points2, F, imageSize, H1, H2, threshold=5)-> None
@@ -1539,7 +1427,7 @@ Computes a rectification transform for an uncalibrated stereo camera.
:param F: Input fundamental matrix. It can be computed from the same set of point pairs using :ocv:func:`findFundamentalMat` .
:param imageSize: Size of the image.
:param imgSize: Size of the image.
:param H1: Output rectification homography matrix for the first image.
@@ -81,7 +81,7 @@ 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
@@ -93,7 +93,7 @@ enum
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),
@@ -117,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
@@ -203,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,
@@ -330,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;
@@ -353,13 +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) );
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,
@@ -384,11 +383,11 @@ public:
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<CvMat> mask;
cv::Ptr<CvMat> prevParam;
cv::Ptr<CvMat> param;
@@ -427,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(),
@@ -440,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,
@@ -467,14 +466,14 @@ CV_EXPORTS_W void projectPoints( InputArray objectPoints,
//! computes the camera pose from a few 3D points and the corresponding projections. The outliers are not handled.
enum
{
ITERATIVE=CV_ITERATIVE,
ITERATIVE=CV_ITERATIVE,
EPNP=CV_EPNP,
P3P=CV_P3P
P3P=CV_P3P
};
CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
InputArray cameraMatrix, InputArray distCoeffs,
OutputArray rvec, OutputArray tvec,
bool useExtrinsicGuess=false, int flags=0);
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,
@@ -483,12 +482,12 @@ CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints,
InputArray distCoeffs,
OutputArray rvec,
OutputArray tvec,
bool useExtrinsicGuess = false,
bool useExtrinsicGuess = false,
int iterationsCount = 100,
float reprojectionError = 8.0,
int minInliersCount = 100,
OutputArray inliers = noArray(),
int flags = 0);
int flags = ITERATIVE);
//! initializes camera matrix from a few 3D points and the corresponding projections.
CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
@@ -501,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
@@ -574,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,
@@ -606,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(),
@@ -614,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
@@ -642,7 +639,7 @@ 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 );
@@ -657,7 +654,7 @@ template<> CV_EXPORTS void Ptr<CvStereoBMState>::delete_obj();
/*!
Block Matching Stereo Correspondence Algorithm
The class implements BM stereo correspondence algorithm by K. Konolige.
*/
class CV_EXPORTS_W StereoBM
@@ -683,7 +680,7 @@ public:
/*!
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
@@ -693,7 +690,7 @@ public:
//! 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,
@@ -742,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
@@ -75,7 +75,6 @@ void CV_ChessboardDetectorTimingTest::run( int start_from )
sprintf( filepath, "%scameracalibration/", ts->get_data_path().c_str() );
sprintf( filename, "%schessboard_timing_list.dat", filepath );
printf("Reading file %s\n", filename);
CvFileStorage* fs = cvOpenFileStorage( filename, 0, CV_STORAGE_READ );
CvFileNode* board_list = fs ? cvGetFileNodeByName( fs, 0, "boards" ) : 0;
+5
View File
@@ -3,3 +3,8 @@ contrib. Contributed/Experimental Stuff
***************************************
The module contains some recently added functionality that has not been stabilized, or functionality that is considered optional.
.. toctree::
:maxdepth: 2
stereo
+117
View File
@@ -0,0 +1,117 @@
Stereo Correspondence
========================================
.. highlight:: cpp
StereoVar
----------
.. ocv:class:: StereoVar
Class for computing stereo correspondence using the variational matching algorithm ::
class StereoVar
{
StereoVar();
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);
virtual ~StereoVar();
virtual void operator()(InputArray left, InputArray right, OutputArray disp);
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 class implements the modified S. G. Kosov algorithm [Publication] that differs from the original one as follows:
* The automatic initialization of method's parameters is added.
* The method of Smart Iteration Distribution (SID) is implemented.
* The support of Multi-Level Adaptation Technique (MLAT) is not included.
* The method of dynamic adaptation of method's parameters is not included.
StereoVar::StereoVar
--------------------------
.. ocv:function:: StereoVar::StereoVar()
.. ocv:function:: StereoVar::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 constructor
:param levels: The number of pyramid layers, including the initial image. levels=1 means that no extra layers are created and only the original images are used. This parameter is ignored if flag USE_AUTO_PARAMS is set.
:param pyrScale: Specifies the image scale (<1) to build the pyramids for each image. pyrScale=0.5 means the classical pyramid, where each next layer is twice smaller than the previous. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param nIt: The number of iterations the algorithm does at each pyramid level. (If the flag USE_SMART_ID is set, the number of iterations will be redistributed in such a way, that more iterations will be done on more coarser levels.)
:param minDisp: Minimum possible disparity value. Could be negative in case the left and right input images change places.
:param maxDisp: Maximum possible disparity value.
:param poly_n: Size of the pixel neighbourhood used to find polynomial expansion in each pixel. The larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field. Typically, poly_n = 3, 5 or 7
:param poly_sigma: Standard deviation of the Gaussian that is used to smooth derivatives that are used as a basis for the polynomial expansion. For poly_n=5 you can set poly_sigma=1.1 , for poly_n=7 a good value would be poly_sigma=1.5
:param fi: The smoothness parameter, ot the weight coefficient for the smoothness term.
:param lambda: The threshold parameter for edge-preserving smoothness. (This parameter is ignored if PENALIZATION_CHARBONNIER or PENALIZATION_PERONA_MALIK is used.)
:param penalization: Possible values: PENALIZATION_TICHONOV - linear smoothness; PENALIZATION_CHARBONNIER - non-linear edge preserving smoothness; PENALIZATION_PERONA_MALIK - non-linear edge-enhancing smoothness. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param cycle: Type of the multigrid cycle. Possible values: CYCLE_O and CYCLE_V for null- and v-cycles respectively. (This parameter is ignored if flag USE_AUTO_PARAMS is set).
:param flags: The operation flags; can be a combination of the following:
* USE_INITIAL_DISPARITY: Use the input flow as the initial flow approximation.
* USE_EQUALIZE_HIST: Use the histogram equalization in the pre-processing phase.
* USE_SMART_ID: Use the smart iteration distribution (SID).
* USE_AUTO_PARAMS: Allow the method to initialize the main parameters.
* USE_MEDIAN_FILTERING: Use the median filer of the solution in the post processing phase.
The first constructor initializes ``StereoVar`` with all the default parameters. So, you only have to set ``StereoVar::maxDisp`` and / or ``StereoVar::minDisp`` at minimum. The second constructor enables you to set each parameter to a custom value.
StereoVar::operator ()
-----------------------
.. ocv:function:: void StereoVar::operator()( const Mat& left, const Mat& right, Mat& disp )
Computes disparity using the variational algorithm for a rectified stereo pair.
:param left: Left 8-bit single-channel or 3-channel image.
:param right: Right image of the same size and the same type as the left one.
:param disp: Output disparity map. It is a 8-bit signed single-channel image of the same size as the input image.
The method executes the variational algorithm on a rectified stereo pair. See ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method.
**Note**:
The method is not constant, so you should not use the same ``StereoVar`` instance from different threads simultaneously.
@@ -970,6 +970,8 @@ namespace cv
};
CV_EXPORTS void applyColorMap(InputArray src, OutputArray dst, int colormap);
CV_EXPORTS bool initModule_contrib();
}
@@ -107,12 +107,15 @@ class DetectionBasedTracker::SeparateDetectionWork
DetectionBasedTracker::SeparateDetectionWork::SeparateDetectionWork(DetectionBasedTracker& _detectionBasedTracker, const std::string& cascadeFilename)
:detectionBasedTracker(_detectionBasedTracker),
cascadeInThread(cascadeFilename),
cascadeInThread(),
isObjectDetectingReady(false),
shouldObjectDetectingResultsBeForgot(false),
stateThread(STATE_THREAD_STOPPED),
timeWhenDetectingThreadStartedWork(-1)
{
if(!cascadeInThread.load(cascadeFilename)) {
CV_Error(CV_StsBadArg, "DetectionBasedTracker::SeparateDetectionWork::SeparateDetectionWork: Cannot load a cascade from the file '"+cascadeFilename+"'");
}
int res=0;
res=pthread_mutex_init(&mutex, NULL);//TODO: should be attributes?
if (res) {
@@ -238,6 +241,11 @@ void DetectionBasedTracker::SeparateDetectionWork::workcycleObjectDetector()
CV_Assert(stateThread==STATE_THREAD_WORKING_SLEEPING);
pthread_mutex_lock(&mutex);
if (!isWorking()) {//it is a rare case, but may cause a crash
LOGD("DetectionBasedTracker::SeparateDetectionWork::workcycleObjectDetector() --- go out from the workcycle from inner part of lock just before waiting");
pthread_mutex_unlock(&mutex);
break;
}
CV_Assert(stateThread==STATE_THREAD_WORKING_SLEEPING);
pthread_cond_wait(&objectDetectorRun, &mutex);
if (isWorking()) {
@@ -439,14 +447,17 @@ DetectionBasedTracker::InnerParameters::InnerParameters()
DetectionBasedTracker::DetectionBasedTracker(const std::string& cascadeFilename, const Parameters& params)
:separateDetectionWork(),
innerParameters(),
numTrackedSteps(0),
cascadeForTracking(cascadeFilename)
numTrackedSteps(0)
{
CV_Assert( (params.minObjectSize > 0)
&& (params.maxObjectSize >= 0)
&& (params.scaleFactor > 1.0)
&& (params.maxTrackLifetime >= 0) );
if (!cascadeForTracking.load(cascadeFilename)) {
CV_Error(CV_StsBadArg, "DetectionBasedTracker::DetectionBasedTracker: Cannot load a cascade from the file '"+cascadeFilename+"'");
}
parameters=params;
separateDetectionWork=new SeparateDetectionWork(*this, cascadeFilename);
+5
View File
@@ -713,4 +713,9 @@ Ptr<FaceRecognizer> createLBPHFaceRecognizer(int radius, int neighbors,
return new LBPH(radius, neighbors, grid_x, grid_y);
}
bool initModule_contrib()
{
return true;
}
}
+4 -9
View File
@@ -185,21 +185,16 @@ Mat subspaceReconstruct(InputArray _W, InputArray _mean, InputArray _src)
Mat W = _W.getMat();
Mat mean = _mean.getMat();
Mat src = _src.getMat();
// get number of samples and dimension
// get number of samples
int n = src.rows;
int d = src.cols;
// initalize temporary matrices
Mat X, Y;
// copy data & make sure we are using the correct type
src.convertTo(Y, W.type());
// calculate the reconstruction
gemm(Y,
W,
1.0,
((size_t)d == mean.total()) ? repeat(mean.reshape(1,1), n, 1) : Mat(),
((size_t)d == mean.total()) ? 1.0 : 0.0,
X,
GEMM_2_T);
gemm(Y, W, 1.0, Mat(), 0.0, X, GEMM_2_T);
if(mean.total() == (size_t) X.cols)
add(X, repeat(mean.reshape(1,1), n, 1), X);
return X;
}
+138 -154
View File
@@ -115,7 +115,7 @@ Rect\_
Template class for 2D rectangles, described by the following parameters:
* Coordinates of the top-left corner. This is a default interpretation of ``Rect_::x`` and ``Rect_::y`` in OpenCV. Though, in your algorithms you may count ``x`` and ``y`` from the bottom-left corner.
* Coordinates of the top-left corner. This is a default interpretation of ``Rect_::x`` and ``Rect_::y`` in OpenCV. Though, in your algorithms you may count ``x`` and ``y`` from the bottom-left corner.
* Rectangle width and height.
OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not. For example, the method ``Rect_::contains`` returns ``true`` if
@@ -182,7 +182,7 @@ The class represents rotated (i.e. not up-right) rectangles on a plane. Each rec
:param angle: The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.
:param box: The rotated rectangle parameters as the obsolete CvBox2D structure.
.. ocv:function:: void RotatedRect::points(Point2f* pts) const
.. ocv:function:: void RotatedRect::points( Point2f pts[] ) const
.. ocv:function:: Rect RotatedRect::boundingRect() const
.. ocv:function:: RotatedRect::operator CvBox2D() const
@@ -228,7 +228,7 @@ Matx
Template class for small matrices whose type and size are known at compilation time: ::
template<typename _Tp, int m, int n> class Matx {...};
typedef Matx<float, 1, 2> Matx12f;
typedef Matx<double, 1, 2> Matx12d;
...
@@ -246,7 +246,7 @@ Template class for small matrices whose type and size are known at compilation t
...
typedef Matx<float, 6, 6> Matx66f;
typedef Matx<double, 6, 6> Matx66d;
If you need a more flexible type, use :ocv:class:`Mat` . The elements of the matrix ``M`` are accessible using the ``M(i,j)`` notation. Most of the common matrix operations (see also
:ref:`MatrixExpressions` ) are available. To do an operation on ``Matx`` that is not implemented, you can easily convert the matrix to
``Mat`` and backwards. ::
@@ -256,7 +256,7 @@ If you need a more flexible type, use :ocv:class:`Mat` . The elements of the mat
7, 8, 9);
cout << sum(Mat(m*m.t())) << endl;
Vec
---
.. ocv:class:: Vec
@@ -264,7 +264,7 @@ Vec
Template class for short numerical vectors, a partial case of :ocv:class:`Matx`: ::
template<typename _Tp, int n> class Vec : public Matx<_Tp, n, 1> {...};
typedef Vec<uchar, 2> Vec2b;
typedef Vec<uchar, 3> Vec3b;
typedef Vec<uchar, 4> Vec4b;
@@ -286,8 +286,8 @@ Template class for short numerical vectors, a partial case of :ocv:class:`Matx`:
typedef Vec<double, 3> Vec3d;
typedef Vec<double, 4> Vec4d;
typedef Vec<double, 6> Vec6d;
It is possible to convert ``Vec<T,2>`` to/from ``Point_``, ``Vec<T,3>`` to/from ``Point3_`` , and ``Vec<T,4>`` to :ocv:struct:`CvScalar` or :ocv:class:`Scalar_`. Use ``operator[]`` to access the elements of ``Vec``.
It is possible to convert ``Vec<T,2>`` to/from ``Point_``, ``Vec<T,3>`` to/from ``Point3_`` , and ``Vec<T,4>`` to :ocv:struct:`CvScalar` or :ocv:class:`Scalar_`. Use ``operator[]`` to access the elements of ``Vec``.
All the expected vector operations are also implemented:
@@ -309,7 +309,7 @@ Scalar\_
Template class for a 4-element vector derived from Vec. ::
template<typename _Tp> class Scalar_ : public Vec<_Tp, 4> { ... };
typedef Scalar_<double> Scalar;
Being derived from ``Vec<_Tp, 4>`` , ``Scalar_`` and ``Scalar`` can be used just as typical 4-element vectors. In addition, they can be converted to/from ``CvScalar`` . The type ``Scalar`` is widely used in OpenCV to pass pixel values.
@@ -344,7 +344,7 @@ The static method ``Range::all()`` returns a special variable that means "the wh
}
.. _Ptr:
.. _Ptr:
Ptr
---
@@ -491,7 +491,7 @@ So, the data layout in ``Mat`` is fully compatible with ``CvMat``, ``IplImage``,
There are many different ways to create a ``Mat`` object. The most popular options are listed below:
*
Use the ``create(nrows, ncols, type)`` method or the similar ``Mat(nrows, ncols, type[, fillValue])`` constructor. A new array of the specified size and type is allocated. ``type`` has the same meaning as in the ``cvCreateMat`` method.
For example, ``CV_8UC1`` means a 8-bit single-channel array, ``CV_32FC2`` means a 2-channel (complex) floating-point array, and so on.
@@ -508,7 +508,7 @@ There are many different ways to create a ``Mat`` object. The most popular optio
As noted in the introduction to this chapter, ``create()`` allocates only a new array when the shape or type of the current array are different from the specified ones.
*
Create a multi-dimensional array:
::
@@ -522,11 +522,11 @@ There are many different ways to create a ``Mat`` object. The most popular optio
It passes the number of dimensions =1 to the ``Mat`` constructor but the created array will be 2-dimensional with the number of columns set to 1. So, ``Mat::dims`` is always >= 2 (can also be 0 when the array is empty).
*
Use a copy constructor or assignment operator where there can be an array or expression on the right side (see below). As noted in the introduction, the array assignment is an O(1) operation because it only copies the header and increases the reference counter. The ``Mat::clone()`` method can be used to get a full (deep) copy of the array when you need it.
*
Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (called a *minor* in algebra) or a diagonal. Such operations are also O(1) because the new header references the same data. You can actually modify a part of the array using this feature, for example:
::
@@ -568,7 +568,7 @@ There are many different ways to create a ``Mat`` object. The most popular optio
As in case of whole matrices, if you need a deep copy, use the ``clone()`` method of the extracted sub-matrices.
*
Make a header for user-allocated data. It can be useful to do the following:
#.
@@ -610,7 +610,7 @@ There are many different ways to create a ``Mat`` object. The most popular optio
..
*
Use MATLAB-style array initializers, ``zeros(), ones(), eye()``, for example:
::
@@ -621,7 +621,7 @@ There are many different ways to create a ``Mat`` object. The most popular optio
..
*
Use a comma-separated initializer:
::
@@ -701,48 +701,48 @@ This is a list of implemented matrix operations that can be combined in arbitrar
*
Addition, subtraction, negation:
``A+B, A-B, A+s, A-s, s+A, s-A, -A``
*
*
Scaling:
``A*alpha``
*
Per-element multiplication and division:
``A.mul(B), A/B, alpha/A``
*
Matrix multiplication:
``A*B``
*
Transposition:
``A.t()`` (means ``A``\ :sup:`T`)
*
Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
``A.inv([method])`` (~ ``A``\ :sup:`-1`) ``, A.inv([method])*B`` (~ ``X: AX=B``)
*
Comparison:
``A cmpop B, A cmpop alpha, alpha cmpop A``, where ``cmpop`` is one of ``: >, >=, ==, !=, <=, <``. The result of comparison is an 8-bit single channel mask whose elements are set to 255 (if the particular element or pair of elements satisfy the condition) or 0.
*
Bitwise logical operations: ``A logicop B, A logicop s, s logicop A, ~A``, where ``logicop`` is one of ``: &, |, ^``.
*
Element-wise minimum and maximum:
``min(A, B), min(A, alpha), max(A, B), max(A, alpha)``
*
Element-wise absolute value:
``abs(A)``
*
Cross-product, dot-product:
``A.cross(B)``
``A.dot(B)``
*
Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as ``norm``, ``mean``, ``sum``, ``countNonZero``, ``trace``, ``determinant``, ``repeat``, and others.
@@ -761,17 +761,17 @@ Here are examples of matrix expressions:
// compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
SVD svd(A);
Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
// compute the new vector of parameters in the Levenberg-Marquardt algorithm
x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
// sharpen image using "unsharp mask" algorithm
Mat blurred; double sigma = 1, threshold = 5, amount = 1;
GaussianBlur(img, blurred, Size(), sigma, sigma);
Mat lowConstrastMask = abs(img - blurred) < threshold;
Mat sharpened = img*(1+amount) + blurred*(-amount);
img.copyTo(sharpened, lowContrastMask);
..
@@ -782,43 +782,41 @@ Mat::Mat
Various Mat constructors
.. ocv:function:: Mat::Mat()
.. ocv:function:: Mat::Mat(int rows, int cols, int type)
.. ocv:function:: Mat::Mat(Size size, int type)
.. ocv:function:: Mat::Mat(int rows, int cols, int type, const Scalar& s)
.. ocv:function:: Mat::Mat(Size size, int type, const Scalar& s)
.. ocv:function:: Mat::Mat(const Mat& m)
.. ocv:function:: Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
.. ocv:function:: Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
.. ocv:function:: Mat::Mat(const Mat& m, const Range& rowRange, const Range& colRange)
.. ocv:function:: Mat::Mat( const Mat& m, const Range& rowRange, const Range& colRange=Range::all() )
.. ocv:function:: Mat::Mat(const Mat& m, const Rect& roi)
.. ocv:function:: Mat::Mat(const CvMat* m, bool copyData=false)
.. ocv:function:: Mat::Mat(const IplImage* img, bool copyData=false)
.. ocv:function:: template<typename T, int n> explicit Mat::Mat(const Vec<T, n>& vec, bool copyData=true)
.. ocv:function:: template<typename T, int m, int n> explicit Mat::Mat(const Matx<T, m, n>& vec, bool copyData=true)
.. ocv:function:: template<typename T> explicit Mat::Mat(const vector<T>& vec, bool copyData=false)
.. ocv:function:: Mat::Mat(const MatExpr& expr)
.. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type)
.. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type, const Scalar& s)
.. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0)
.. ocv:function:: Mat::Mat(const Mat& m, const Range* ranges)
:param ndims: Array dimensionality.
@@ -857,8 +855,6 @@ Various Mat constructors
:param ranges: Array of selected ranges of ``m`` along each dimensionality.
:param expr: Matrix expression. See :ref:`MatrixExpressions`.
These are various constructors that form a matrix. As noted in the :ref:`AutomaticAllocation`,
often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression or can be allocated with
:ocv:func:`Mat::create` . In the former case, the old content is de-referenced.
@@ -879,7 +875,7 @@ Provides matrix assignment operators.
.. ocv:function:: Mat& Mat::operator = (const Mat& m)
.. ocv:function:: Mat& Mat::operator = (const MatExpr_Base& expr)
.. ocv:function:: Mat& Mat::operator =( const MatExpr& expr )
.. ocv:function:: Mat& Mat::operator = (const Scalar& s)
@@ -891,23 +887,13 @@ Provides matrix assignment operators.
These are available assignment operators. Since they all are very different, make sure to read the operator parameters description.
Mat::operator MatExpr
-------------------------
Provides a ``Mat`` -to- ``MatExpr`` cast operator.
.. ocv:function:: Mat::operator MatExpr_<Mat, Mat>() const
The cast operator should not be called explicitly. It is used internally by the
:ref:`MatrixExpressions` engine.
Mat::row
------------
Creates a matrix header for the specified matrix row.
.. ocv:function:: Mat Mat::row(int i) const
.. ocv:function:: Mat Mat::row(int y) const
:param i: A 0-based row index.
:param y: A 0-based row index.
The method makes a new header for the specified matrix row and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, ``axpy``, used by LU and many other algorithms: ::
@@ -940,9 +926,9 @@ Mat::col
------------
Creates a matrix header for the specified matrix column.
.. ocv:function:: Mat Mat::col(int j) const
.. ocv:function:: Mat Mat::col(int x) const
:param j: A 0-based column index.
:param x: A 0-based column index.
The method makes a new header for the specified matrix column and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. See also the
:ocv:func:`Mat::row` description.
@@ -988,11 +974,11 @@ Mat::diag
-------------
Extracts a diagonal from a matrix, or creates a diagonal matrix.
.. ocv:function:: Mat Mat::diag(int d) const
.. ocv:function:: Mat Mat::diag( int d=0 ) const
.. ocv:function:: static Mat Mat::diag(const Mat& matD)
.. ocv:function:: static Mat Mat::diag( const Mat& d )
:param d: Index of the diagonal, with the following values:
:param d: Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values:
* **d=0** is the main diagonal.
@@ -1000,8 +986,6 @@ Extracts a diagonal from a matrix, or creates a diagonal matrix.
* **d<0** is a diagonal from the upper half. For example, ``d=1`` means the diagonal is set immediately above the main one.
:param matD: Single-column matrix that forms a diagonal matrix.
The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to
:ocv:func:`Mat::row` and
:ocv:func:`Mat::col` , this is an O(1) operation.
@@ -1075,9 +1059,9 @@ Mat::setTo
--------------
Sets all or some of the array elements to the specified value.
.. ocv:function:: Mat& Mat::setTo(const Scalar& s, InputArray mask=noArray())
.. ocv:function:: Mat& Mat::setTo( InputArray value, InputArray mask=noArray() )
:param s: Assigned scalar converted to the actual array type.
:param value: Assigned scalar converted to the actual array type.
:param mask: Operation mask of the same size as ``*this``. This is an advanced variant of the ``Mat::operator=(const Scalar& s)`` operator.
@@ -1189,7 +1173,7 @@ Returns a zero array of the specified size and type.
.. ocv:function:: static MatExpr Mat::zeros(int rows, int cols, int type)
.. ocv:function:: static MatExpr Mat::zeros(Size size, int type)
.. ocv:function:: static MatExpr Mat::zeros(int ndims, const int* sizes, int type)
.. ocv:function:: static MatExpr Mat::zeros( int ndims, const int* sz, int type )
:param ndims: Array dimensionality.
@@ -1197,9 +1181,9 @@ Returns a zero array of the specified size and type.
:param cols: Number of columns.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sizes: Array of integers specifying the array shape.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sz: Array of integers specifying the array shape.
:param type: Created matrix type.
@@ -1218,7 +1202,7 @@ Returns an array of all 1's of the specified size and type.
.. ocv:function:: static MatExpr Mat::ones(int rows, int cols, int type)
.. ocv:function:: static MatExpr Mat::ones(Size size, int type)
.. ocv:function:: static MatExpr Mat::ones(int ndims, const int* sizes, int type)
.. ocv:function:: static MatExpr Mat::ones( int ndims, const int* sz, int type )
:param ndims: Array dimensionality.
@@ -1226,9 +1210,9 @@ Returns an array of all 1's of the specified size and type.
:param cols: Number of columns.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sizes: Array of integers specifying the array shape.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sz: Array of integers specifying the array shape.
:param type: Created matrix type.
@@ -1252,12 +1236,12 @@ Returns an identity matrix of the specified size and type.
:param cols: Number of columns.
:param size: Alternative matrix size specification as ``Size(cols, rows)`` .
:param size: Alternative matrix size specification as ``Size(cols, rows)`` .
:param type: Created matrix type.
The method returns a Matlab-style identity matrix initializer, similarly to
:ocv:func:`Mat::zeros`. Similarly to
:ocv:func:`Mat::zeros`. Similarly to
:ocv:func:`Mat::ones`, you can use a scale operation to create a scaled identity matrix efficiently: ::
// make a 4x4 diagonal matrix with 0.1's on the diagonal.
@@ -1278,8 +1262,8 @@ Allocates new array data if needed.
:param cols: New number of columns.
:param size: Alternative new matrix size specification: ``Size(cols, rows)``
:param size: Alternative new matrix size specification: ``Size(cols, rows)``
:param sizes: Array of integers specifying a new array shape.
:param type: New matrix type.
@@ -1288,8 +1272,8 @@ This is one of the key ``Mat`` methods. Most new-style OpenCV functions and meth
#.
If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling
:ocv:func:`Mat::release`.
:ocv:func:`Mat::release`.
#.
Initialize the new header.
@@ -1367,7 +1351,8 @@ Mat::push_back
Adds elements to the bottom of the matrix.
.. ocv:function:: template<typename T> void Mat::push_back(const T& elem)
.. ocv:function:: void Mat::push_back(const Mat& elem)
.. ocv:function:: void Mat::push_back( const Mat& m )
:param elem: Added element(s).
@@ -1415,7 +1400,7 @@ Adjusts a submatrix size and position within the parent matrix.
:param dright: Shift of the right submatrix boundary to the right.
The method is complimentary to
The method is complimentary to
:ocv:func:`Mat::locateROI` . The typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically, it can be required for filtering operations when pixels outside of the ROI should be taken into account. When all the method parameters are positive, the ROI needs to grow in all directions by the specified amount, for example: ::
A.adjustROI(2, 2, 2, 2);
@@ -1428,7 +1413,7 @@ In this example, the matrix size is increased by 4 elements in each direction. T
The function is used internally by the OpenCV filtering functions, like
:ocv:func:`filter2D` , morphological operations, and so on.
.. seealso:: :ocv:func:`copyMakeBorder`
.. seealso:: :ocv:func:`copyMakeBorder`
Mat::operator()
@@ -1439,13 +1424,13 @@ Extracts a rectangular submatrix.
.. ocv:function:: Mat Mat::operator()( const Rect& roi ) const
.. ocv:function:: Mat Mat::operator()( const Ranges* ranges ) const
.. ocv:function:: Mat Mat::operator()( const Range* ranges ) const
:param rowRange: Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use ``Range::all()``.
:param colRange: Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use ``Range::all()``.
:param rowRange: Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use ``Range::all()``.
:param colRange: Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use ``Range::all()``.
:param roi: Extracted submatrix specified as a rectangle.
:param ranges: Array of selected ranges along each array dimension.
@@ -1626,7 +1611,7 @@ Mat::step1
--------------
Returns a normalized step.
.. ocv:function:: size_t Mat::step1() const
.. ocv:function:: size_t Mat::step1( int i=0 ) const
The method returns a matrix step divided by
:ocv:func:`Mat::elemSize1()` . It can be useful to quickly access an arbitrary matrix element.
@@ -1654,15 +1639,15 @@ Mat::ptr
------------
Returns a pointer to the specified matrix row.
.. ocv:function:: uchar* Mat::ptr(int i=0)
.. ocv:function:: uchar* Mat::ptr(int i0=0)
.. ocv:function:: const uchar* Mat::ptr(int i=0) const
.. ocv:function:: const uchar* Mat::ptr(int i0=0) const
.. ocv:function:: template<typename _Tp> _Tp* Mat::ptr(int i=0)
.. ocv:function:: template<typename _Tp> _Tp* Mat::ptr(int i0=0)
.. ocv:function:: template<typename _Tp> const _Tp* Mat::ptr(int i=0) const
.. ocv:function:: template<typename _Tp> const _Tp* Mat::ptr(int i0=0) const
:param i: A 0-based row index.
:param i0: A 0-based row index.
The methods return ``uchar*`` or typed pointer to the specified matrix row. See the sample in
:ocv:func:`Mat::isContinuous` to know how to use these methods.
@@ -1696,7 +1681,7 @@ Returns a reference to the specified array element.
:param j: Index along the dimension 1
:param k: Index along the dimension 2
:param pt: Element position specified as ``Point(j,i)`` .
:param pt: Element position specified as ``Point(j,i)`` .
:param idx: Array of ``Mat::dims`` indices.
@@ -1816,23 +1801,24 @@ To use ``Mat_`` for multi-channel images/matrices, pass ``Vec`` as a ``Mat_`` pa
InputArray
----------
.. ocv:class:: InputArray
This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as ::
typedef const _InputArray& InputArray;
where ``_InputArray`` is a class that can be constructed from ``Mat``, ``Mat_<T>``, ``Matx<T, m, n>``, ``std::vector<T>``, ``std::vector<std::vector<T> >`` or ``std::vector<Mat>``. It can also be constructed from a matrix expression.
Since this is mostly implementation-level class, and its interface may change in future versions, we do not describe it in details. There are a few key things, though, that should be kept in mind:
* When you see in the reference manual or in OpenCV source code a function that takes ``InputArray``, it means that you can actually pass ``Mat``, ``Matx``, ``vector<T>`` etc. (see above the complete list).
* Optional input arguments: If some of the input arrays may be empty, pass ``cv::noArray()`` (or simply ``cv::Mat()`` as you probably did before).
* The class is designed solely for passing parameters. That is, normally you *should not* declare class members, local and global variables of this type.
* If you want to design your own function or a class method that can operate of arrays of multiple types, you can use ``InputArray`` (or ``OutputArray``) for the respective parameters. Inside a function you should use ``_InputArray::getMat()`` method to construct a matrix header for the array (without copying data). ``_InputArray::kind()`` can be used to distinguish ``Mat`` from ``vector<>`` etc., but normally it is not needed.
Here is how you can use a function that takes ``InputArray`` ::
std::vector<Point2f> vec;
@@ -1852,12 +1838,12 @@ Here is how such a function can be implemented (for simplicity, we implement a v
// unless _src and/or _m are matrix expressions.
Mat src = _src.getMat(), m = _m.getMat();
CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
// [re]create the output array so that it has the proper size and type.
// In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
_dst.create(src.size(), src.type());
Mat dst = _dst.getMat();
for( int i = 0; i < src.rows; i++ )
for( int j = 0; j < src.cols; j++ )
{
@@ -1874,12 +1860,13 @@ Here is how such a function can be implemented (for simplicity, we implement a v
There is another related type, ``InputArrayOfArrays``, which is currently defined as a synonym for ``InputArray``: ::
typedef InputArray InputArrayOfArrays;
It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation level their use is similar, but ``_InputArray::getMat(idx)`` should be used to get header for the idx-th component of the outer vector and ``_InputArray::size().area()`` should be used to find the number of components (vectors/matrices) of the outer vector.
OutputArray
-----------
.. ocv:class:: OutputArray : public InputArray
This type is very similar to ``InputArray`` except that it is used for input/output and output function parameters. Just like with ``InputArray``, OpenCV users should not care about ``OutputArray``, they just pass ``Mat``, ``vector<T>`` etc. to the functions. The same limitation as for ``InputArray``: **Do not explicitly create OutputArray instances** applies here too.
@@ -2298,7 +2285,7 @@ Template sparse n-dimensional array class derived from
SparseMatIterator_<_Tp> end();
SparseMatConstIterator_<_Tp> end() const;
};
``SparseMat_`` is a thin wrapper on top of :ocv:class:`SparseMat` created in the same way as ``Mat_`` .
It simplifies notation of some operations. ::
@@ -2310,53 +2297,55 @@ It simplifies notation of some operations. ::
Algorithm
---------
.. ocv:class:: Algorithm
This is a base class for all more or less complex algorithms in OpenCV, especially for classes of algorithms, for which there can be multiple implementations. The examples are stereo correspondence (for which there are algorithms like block matching, semi-global block matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck etc.).
The class provides the following features for all derived classes:
* so called "virtual constructor". That is, each Algorithm derivative is registered at program start and you can get the list of registered algorithms and create instance of a particular algorithm by its name (see ``Algorithm::create``). If you plan to add your own algorithms, it is good practice to add a unique prefix to your algorithms to distinguish them from other algorithms.
* setting/retrieving algorithm parameters by name. If you used video capturing functionality from OpenCV highgui module, you are probably familar with ``cvSetCaptureProperty()``, ``cvGetCaptureProperty()``, ``VideoCapture::set()`` and ``VideoCapture::get()``. ``Algorithm`` provides similar method where instead of integer id's you specify the parameter names as text strings. See ``Algorithm::set`` and ``Algorithm::get`` for details.
* reading and writing parameters from/to XML or YAML files. Every Algorithm derivative can store all its parameters and then read them back. There is no need to re-implement it each time.
Here is example of SIFT use in your application via Algorithm interface: ::
#include "opencv2/opencv.hpp"
#include "opencv2/nonfree/nonfree.hpp"
...
initModule_nonfree(); // to load SURF/SIFT etc.
Ptr<Feature2D> sift = Algorithm::create<Feature2D>("Feature2D.SIFT");
FileStorage fs("sift_params.xml", FileStorage::READ);
if( fs.isOpened() ) // if we have file with parameters, read them
{
sift.read(fs["sift_params"]);
sift->read(fs["sift_params"]);
fs.release();
}
else // else modify the parameters and store them; user can later edit the file to use different parameters
{
sift.set("contrastThreshold", 0.01f); // lower the contrast threshold, compared to the default value
sift->set("contrastThreshold", 0.01f); // lower the contrast threshold, compared to the default value
{
WriteStructContext ws(fs, "sift_params", CV_NODE_MAP);
sift.write(fs);
sift->write(fs);
}
}
Mat image = imread("myimage.png", 0), descriptors;
vector<KeyPoint> keypoints;
sift(image, noArray(), keypoints, descriptors);
(*sift)(image, noArray(), keypoints, descriptors);
Algorithm::get
--------------
Returns the algorithm parameter
.. ocv:function:: template<typename _Tp> typename ParamType<_Tp>::member_type get(const string& name) const
.. ocv:function:: template<typename _Tp> typename ParamType<_Tp>::member_type Algorithm::get(const string& name) const
:param name: The parameter name.
@@ -2377,13 +2366,13 @@ Algorithm::set
--------------
Sets the algorithm parameter
.. ocv:function:: void set(const string& name, int value)
.. ocv:function:: void set(const string& name, double value)
.. ocv:function:: void set(const string& name, bool value)
.. ocv:function:: void set(const string& name, const string& value)
.. ocv:function:: void set(const string& name, const Mat& value)
.. ocv:function:: void set(const string& name, const vector<Mat>& value)
.. ocv:function:: void set(const string& name, const Ptr<Algorithm>& value)
.. ocv:function:: void Algorithm::set(const string& name, int value)
.. ocv:function:: void Algorithm::set(const string& name, double value)
.. ocv:function:: void Algorithm::set(const string& name, bool value)
.. ocv:function:: void Algorithm::set(const string& name, const string& value)
.. ocv:function:: void Algorithm::set(const string& name, const Mat& value)
.. ocv:function:: void Algorithm::set(const string& name, const vector<Mat>& value)
.. ocv:function:: void Algorithm::set(const string& name, const Ptr<Algorithm>& value)
:param name: The parameter name.
:param value: The parameter value.
@@ -2395,65 +2384,60 @@ Algorithm::write
----------------
Stores algorithm parameters in a file storage
.. ocv:function:: void write(FileStorage& fs) const
.. ocv:function:: void Algorithm::write(FileStorage& fs) const
:param fs: File storage.
The method stores all the algorithm parameters (in alphabetic order) to the file storage. The method is virtual. If you define your own Algorithm derivative, your can override the method and store some extra information. However, it's rarely needed. Here are some examples:
* SIFT feature detector (from nonfree module). The class only stores algorithm parameters and no keypoints or their descriptors. Therefore, it's enough to store the algorithm parameters, which is what ``Algorithm::write()`` does. Therefore, there is no dedicated ``SIFT::write()``.
* Background subtractor (from video module). It has the algorithm parameters and also it has the current background model. However, the background model is not stored. First, it's rather big. Then, if you have stored the background model, it would likely become irrelevant on the next run (because of shifted camera, changed background, different lighting etc.). Therefore, ``BackgroundSubtractorMOG`` and ``BackgroundSubtractorMOG2`` also rely on the standard ``Algorithm::write()`` to store just the algorithm parameters.
* Expectation Maximization (from ml module). The algorithm finds mixture of gaussians that approximates user data best of all. In this case the model may be re-used on the next run to test new data against the trained statistical model. So EM needs to store the model. However, since the model is described by a few parameters that are available as read-only algorithm parameters (i.e. they are available via ``EM::get()``), EM also relies on ``Algorithm::write()`` to store both EM parameters and the model (represented by read-only algorithm parameters).
Algorithm::read
---------------
Reads algorithm parameters from a file storage
.. ocv:function:: void read(const FileNode& fn)
.. ocv:function:: void Algorithm::read(const FileNode& fn)
:param fn: File node of the file storage.
The method reads all the algorithm parameters from the specified node of a file storage. Similarly to ``Algorithm::write()``, if you implement an algorithm that needs to read some extra data and/or re-compute some internal data, you may override the method.
Algorithm::getList
------------------
Returns the list of registered algorithms
.. ocv:function:: void read(vector<string>& algorithms)
.. ocv:function:: void Algorithm::getList(vector<string>& algorithms)
:param algorithms: The output vector of algorithm names.
This static method returns the list of registered algorithms in alphabetical order.
This static method returns the list of registered algorithms in alphabetical order. Here is how to use it ::
Algorithm::getList
------------------
Returns the list of registered algorithms
.. ocv:function:: void read(vector<string>& algorithms)
:param algorithms: The output vector of algorithm names.
This static method returns the list of registered algorithms in alphabetical order.
vector<string> algorithms;
Algorithm::getList(algorithms);
cout << "Algorithms: " << algorithms.size() << endl;
for (size_t i=0; i < algorithms.size(); i++)
cout << algorithms[i] << endl;
Algorithm::create
-----------------
Creates algorithm instance by name
.. ocv:function:: template<typename _Tp> Ptr<_Tp> create(const string& name)
.. ocv:function:: template<typename _Tp> Ptr<_Tp> Algorithm::create(const string& name)
:param name: The algorithm name, one of the names returned by ``Algorithm::getList()``.
This static method creates a new instance of the specified algorithm. If there is no such algorithm, the method will silently return null pointer (that can be checked by ``Ptr::empty()`` method). Also, you should specify the particular ``Algorithm`` subclass as ``_Tp`` (or simply ``Algorithm`` if you do not know it at that point). ::
Ptr<BackgroundSubtractor> bgfg = Algorithm::create<BackgroundSubtractor>("BackgroundSubtractor.MOG2");
.. note:: This is important note about seemingly mysterious behavior of ``Algorithm::create()`` when it returns NULL while it should not. The reason is simple - ``Algorithm::create()`` resides in OpenCV`s core module and the algorithms are implemented in other modules. If you create algorithms dynamically, C++ linker may decide to throw away the modules where the actual algorithms are implemented, since you do not call any functions from the modules. To avoid this problem, you need to call ``initModule_<modulename>();`` somewhere in the beginning of the program before ``Algorithm::create()``. For example, call ``initModule_nonfree()`` in order to use SURF/SIFT, call ``initModule_ml()`` to use expectation maximization etc.
Creating Own Algorithms
-----------------------
@@ -2464,4 +2448,4 @@ The above methods are usually enough for users. If you want to make your own alg
* Add public virtual method ``AlgorithmInfo* info() const;`` to your class.
* Add constructor function, ``AlgorithmInfo`` instance and implement the ``info()`` method. The simplest way is to take http://code.opencv.org/svn/opencv/trunk/opencv/modules/ml/src/ml_init.cpp as the reference and modify it according to the list of your parameters.
* Add some public function (e.g. ``initModule_<mymodule>()``) that calls info() of your algorithm and put it into the same source file as ``info()`` implementation. This is to force C++ linker to include this object file into the target application. See ``Algorithm::create()`` for details.
+5 -5
View File
@@ -7,17 +7,17 @@ kmeans
------
Finds centers of clusters and groups input samples around the clusters.
.. ocv:function:: double kmeans( InputArray samples, int clusterCount, InputOutputArray labels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray() )
.. ocv:function:: double kmeans( InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray() )
.. ocv:pyfunction:: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) -> retval, bestLabels, centers
.. ocv:cfunction:: int cvKMeans2(const CvArr* samples, int clusterCount, CvArr* labels, CvTermCriteria criteria, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* centers=0, double* compactness=0)
.. ocv:cfunction:: int cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, CvTermCriteria termcrit, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* _centers=0, double* compactness=0 )
.. ocv:pyoldfunction:: cv.KMeans2(samples, clusterCount, labels, criteria)-> None
.. ocv:pyoldfunction:: cv.KMeans2(samples, nclusters, labels, termcrit, attempts=1, flags=0, centers=None) -> float
:param samples: Floating-point matrix of input samples, one row per sample.
:param clusterCount: Number of clusters to split the set by.
:param cluster_count: Number of clusters to split the set by.
:param labels: Input/output integer array that stores the cluster indices for every sample.
@@ -40,7 +40,7 @@ Finds centers of clusters and groups input samples around the clusters.
:param compactness: The returned value that is described below.
The function ``kmeans`` implements a k-means algorithm that finds the
centers of ``clusterCount`` clusters and groups the input samples
centers of ``cluster_count`` clusters and groups the input samples
around the clusters. As an output,
:math:`\texttt{labels}_i` contains a 0-based cluster index for
the sample stored in the
+141 -50
View File
@@ -30,11 +30,12 @@ circle
----------
Draws a circle.
.. ocv:function:: void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:pyfunction:: cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image where the circle is drawn.
@@ -63,10 +64,11 @@ Clips the line against the image rectangle.
.. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2
.. ocv:cfunction:: int cvClipLine( CvSize imgSize, CvPoint* pt1, CvPoint* pt2 )
.. ocv:pyoldfunction:: cv.ClipLine(imgSize, pt1, pt2) -> (clippedPt1, clippedPt2)
.. ocv:cfunction:: int cvClipLine( CvSize img_size, CvPoint* pt1, CvPoint* pt2 )
:param imgSize: Image size. The image rectangle is ``Rect(0, 0, imgSize.width, imgSize.height)`` .
.. ocv:pyoldfunction:: cv.ClipLine(imgSize, pt1, pt2) -> (point1, point2)
:param imgSize: Image size. The image rectangle is ``Rect(0, 0, imgSize.width, imgSize.height)`` .
:param imgRect: Image rectangle.
@@ -88,10 +90,12 @@ Draws a simple or thick elliptic arc or fills an ellipse sector.
.. ocv:pyfunction:: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:pyfunction:: cv2.ellipse(img, box, color[, thickness[, lineType]]) -> None
.. ocv:cfunction:: void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double startAngle, double endAngle, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=1, lineType=8, shift=0)-> None
.. ocv:cfunction:: void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double start_angle, double end_angle, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Ellipse(img, center, axes, angle, start_angle, end_angle, color, thickness=1, lineType=8, shift=0)-> None
.. ocv:cfunction:: void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:cfunction:: void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.EllipseBox(img, box, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -130,19 +134,19 @@ ellipse2Poly
----------------
Approximates an elliptic arc with a polyline.
.. ocv:function:: void ellipse2Poly( Point center, Size axes, int angle, int startAngle, int endAngle, int delta, vector<Point>& pts )
.. ocv:function:: void ellipse2Poly( Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, vector<Point>& pts )
.. ocv:pyfunction:: cv2.ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta) -> pts
:param center: Center of the arc.
:param axes: Half-sizes of the arc. See the :ocv:func:`ellipse` for details.
:param angle: Rotation angle of the ellipse in degrees. See the :ocv:func:`ellipse` for details.
:param startAngle: Starting angle of the elliptic arc in degrees.
:param axes: Half-sizes of the arc. See the :ocv:func:`ellipse` for details.
:param endAngle: Ending angle of the elliptic arc in degrees.
:param angle: Rotation angle of the ellipse in degrees. See the :ocv:func:`ellipse` for details.
:param arcStart: Starting angle of the elliptic arc in degrees.
:param arcEnd: Ending angle of the elliptic arc in degrees.
:param delta: Angle between the subsequent polyline vertices. It defines the approximation accuracy.
@@ -157,11 +161,12 @@ fillConvexPoly
------------------
Fills a convex polygon.
.. ocv:function:: void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8, int shift=0)
.. ocv:function:: void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8, int shift=0)
.. ocv:pyfunction:: cv2.fillConvexPoly(img, points, color[, lineType[, shift]]) -> None
.. ocv:cfunction:: void cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts, CvScalar color, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.FillConvexPoly(img, pn, color, lineType=8, shift=0)-> None
:param img: Image.
@@ -190,7 +195,8 @@ Fills the area bounded by one or more polygons.
.. ocv:pyfunction:: cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]) -> None
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int ncontours, CvScalar color, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, int contours, CvScalar color, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.FillPoly(img, polys, color, lineType=8, shift=0)-> None
:param img: Image.
@@ -218,20 +224,21 @@ getTextSize
---------------
Calculates the width and height of a text string.
.. ocv:function:: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)
.. ocv:function:: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)
.. ocv:pyfunction:: cv2.getTextSize(text, fontFace, fontScale, thickness) -> retval, baseLine
.. ocv:cfunction:: void cvGetTextSize( const char* textString, const CvFont* font, CvSize* textSize, int* baseline )
.. ocv:cfunction:: void cvGetTextSize( const char* text_string, const CvFont* font, CvSize* text_size, int* baseline )
.. ocv:pyoldfunction:: cv.GetTextSize(textString, font)-> (textSize, baseline)
:param text: Input text string.
:param fontFace: Font to use. See the :ocv:func:`putText` for details.
:param fontFace: Font to use. See the :ocv:func:`putText` for details.
:param fontScale: Font scale. See the :ocv:func:`putText` for details.
:param fontScale: Font scale. See the :ocv:func:`putText` for details.
:param thickness: Thickness of lines used to render the text. See :ocv:func:`putText` for details.
:param thickness: Thickness of lines used to render the text. See :ocv:func:`putText` for details.
:param baseLine: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
@@ -273,51 +280,51 @@ InitFont
--------
Initializes font structure (OpenCV 1.x API).
.. ocv:cfunction:: void cvInitFont( CvFont* font, int fontFace, double hscale, double vscale, double shear=0, int thickness=1, int lineType=8 )
.. ocv:cfunction:: void cvInitFont( CvFont* font, int font_face, double hscale, double vscale, double shear=0, int thickness=1, int line_type=8 )
:param font: Pointer to the font structure initialized by the function
:param font: Pointer to the font structure initialized by the function
:param fontFace: Font name identifier. Only a subset of Hershey fonts http://sources.isc.org/utils/misc/hershey-font.txt are supported now:
:param font_face: Font name identifier. Only a subset of Hershey fonts http://sources.isc.org/utils/misc/hershey-font.txt are supported now:
* **CV_FONT_HERSHEY_SIMPLEX** normal size sans-serif font
* **CV_FONT_HERSHEY_SIMPLEX** normal size sans-serif font
* **CV_FONT_HERSHEY_PLAIN** small size sans-serif font
* **CV_FONT_HERSHEY_PLAIN** small size sans-serif font
* **CV_FONT_HERSHEY_DUPLEX** normal size sans-serif font (more complex than ``CV_FONT_HERSHEY_SIMPLEX`` )
* **CV_FONT_HERSHEY_DUPLEX** normal size sans-serif font (more complex than ``CV_FONT_HERSHEY_SIMPLEX`` )
* **CV_FONT_HERSHEY_COMPLEX** normal size serif font
* **CV_FONT_HERSHEY_COMPLEX** normal size serif font
* **CV_FONT_HERSHEY_TRIPLEX** normal size serif font (more complex than ``CV_FONT_HERSHEY_COMPLEX`` )
* **CV_FONT_HERSHEY_TRIPLEX** normal size serif font (more complex than ``CV_FONT_HERSHEY_COMPLEX`` )
* **CV_FONT_HERSHEY_COMPLEX_SMALL** smaller version of ``CV_FONT_HERSHEY_COMPLEX``
* **CV_FONT_HERSHEY_COMPLEX_SMALL** smaller version of ``CV_FONT_HERSHEY_COMPLEX``
* **CV_FONT_HERSHEY_SCRIPT_SIMPLEX** hand-writing style font
* **CV_FONT_HERSHEY_SCRIPT_SIMPLEX** hand-writing style font
* **CV_FONT_HERSHEY_SCRIPT_COMPLEX** more complex variant of ``CV_FONT_HERSHEY_SCRIPT_SIMPLEX``
* **CV_FONT_HERSHEY_SCRIPT_COMPLEX** more complex variant of ``CV_FONT_HERSHEY_SCRIPT_SIMPLEX``
The parameter can be composited from one of the values above and an optional ``CV_FONT_ITALIC`` flag, which indicates italic or oblique font.
The parameter can be composited from one of the values above and an optional ``CV_FONT_ITALIC`` flag, which indicates italic or oblique font.
:param hscale: Horizontal scale. If equal to ``1.0f`` , the characters have the original width depending on the font type. If equal to ``0.5f`` , the characters are of half the original width.
:param hscale: Horizontal scale. If equal to ``1.0f`` , the characters have the original width depending on the font type. If equal to ``0.5f`` , the characters are of half the original width.
:param vscale: Vertical scale. If equal to ``1.0f`` , the characters have the original height depending on the font type. If equal to ``0.5f`` , the characters are of half the original height.
:param vscale: Vertical scale. If equal to ``1.0f`` , the characters have the original height depending on the font type. If equal to ``0.5f`` , the characters are of half the original height.
:param shear: Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, ``1.0f`` means about a 45 degree slope, etc.
:param shear: Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, ``1.0f`` means about a 45 degree slope, etc.
:param thickness: Thickness of the text strokes
:param thickness: Thickness of the text strokes
:param lineType: Type of the strokes, see :ocv:func:`line` description
:param line_type: Type of the strokes, see :ocv:func:`line` description
The function initializes the font structure that can be passed to text rendering functions.
.. seealso:: :ocv:cfunc:`PutText`
.. _Line:
.. _Line:
line
--------
@@ -327,7 +334,8 @@ Draws a line segment connecting two points.
.. ocv:pyfunction:: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Line(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -402,13 +410,14 @@ rectangle
-------------
Draws a simple, thick, or filled up-right rectangle.
.. ocv:function:: void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void rectangle(Mat& img, Rect r, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void rectangle( Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyfunction:: cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -416,8 +425,8 @@ Draws a simple, thick, or filled up-right rectangle.
:param pt1: Vertex of the rectangle.
:param pt2: Vertex of the rectangle opposite to ``pt1`` .
:param r: Alternative specification of the drawn rectangle.
:param rec: Alternative specification of the drawn rectangle.
:param color: Rectangle color or brightness (grayscale image).
@@ -439,9 +448,9 @@ Draws several polygonal curves.
.. ocv:pyfunction:: cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours, int isClosed, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:cfunction:: void cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, int is_closed, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
.. ocv:pyoldfunction:: cv.PolyLine(img, polys, isClosed, color, thickness=1, lineType=8, shift=0)-> None
.. ocv:pyoldfunction:: cv.PolyLine(img, polys, is_closed, color, thickness=1, lineType=8, shift=0) -> None
:param img: Image.
@@ -464,6 +473,88 @@ Draws several polygonal curves.
The function ``polylines`` draws one or more polygonal curves.
drawContours
----------------
Draws contours outlines or filled contours.
.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None
.. ocv:cfunction:: void cvDrawContours( CvArr * img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness=1, int line_type=8, CvPoint offset=cvPoint(0,0) )
.. ocv:pyoldfunction:: cv.DrawContours(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0))-> None
:param image: Destination image.
:param contours: All the input contours. Each contour is stored as a point vector.
:param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
:param color: Color of the contours.
:param thickness: Thickness of lines the contours are drawn with. If it is negative (for example, ``thickness=CV_FILLED`` ), the contour interiors are
drawn.
:param lineType: Line connectivity. See :ocv:func:`line` for details.
:param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see ``maxLevel`` ).
:param maxLevel: Maximal level for drawn contours. If it is 0, only
the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is ``hierarchy`` available.
:param offset: Optional contour shift parameter. Shift all the drawn contours by the specified :math:`\texttt{offset}=(dx,dy)` .
:param contour: Pointer to the first contour.
:param external_color: Color of external contours.
:param hole_color: Color of internal contours (holes).
The function draws contour outlines in the image if
:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main( int argc, char** argv )
{
Mat src;
// the first command-line parameter must be a filename of the binary
// (black-n-white) image
if( argc != 2 || !(src=imread(argv[1], 0)).data)
return -1;
Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
src = src > 1;
namedWindow( "Source", 1 );
imshow( "Source", src );
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( src, contours, hierarchy,
CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( rand()&255, rand()&255, rand()&255 );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
namedWindow( "Components", 1 );
imshow( "Components", dst );
waitKey(0);
}
putText
-----------
@@ -471,7 +562,7 @@ Draws a text string.
.. ocv:function:: void putText( Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false )
.. ocv:pyfunction:: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, linetype[, bottomLeftOrigin]]]) -> None
.. ocv:pyfunction:: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) -> None
.. ocv:cfunction:: void cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color )
.. ocv:pyoldfunction:: cv.PutText(img, text, org, font, color)-> None
+67 -66
View File
@@ -10,27 +10,27 @@ CvMemStorage
.. ocv:struct:: CvMemStorage
A storage for various OpenCV dynamic data structures, such as ``CvSeq``, ``CvSet`` etc.
A storage for various OpenCV dynamic data structures, such as ``CvSeq``, ``CvSet`` etc.
.. ocv:member:: CvMemBlock* bottom
.. ocv:member:: CvMemBlock* bottom
the first memory block in the double-linked list of blocks
the first memory block in the double-linked list of blocks
.. ocv:member:: CvMemBlock* top
.. ocv:member:: CvMemBlock* top
the current partially allocated memory block in the list of blocks
the current partially allocated memory block in the list of blocks
.. ocv:member:: CvMemStorage* parent
.. ocv:member:: CvMemStorage* parent
the parent storage (if any) from which the new memory blocks are borrowed.
the parent storage (if any) from which the new memory blocks are borrowed.
.. ocv:member:: int free_space
.. ocv:member:: int free_space
number of free bytes in the ``top`` block
number of free bytes in the ``top`` block
.. ocv:member:: int block_size
.. ocv:member:: int block_size
the total size of the memory blocks
the total size of the memory blocks
Memory storage is a low-level structure used to store dynamically growing data structures such as sequences, contours, graphs, subdivisions, etc. It is organized as a list of memory blocks of equal size -
``bottom`` field is the beginning of the list of blocks and ``top`` is the currently used block, but not necessarily the last block of the list. All blocks between ``bottom`` and ``top``, not including the
@@ -64,38 +64,38 @@ CvSeq
.. ocv:struct:: CvSeq
Dynamically growing sequence.
Dynamically growing sequence.
.. ocv:member:: int flags
.. ocv:member:: int flags
sequence flags, including the sequence signature (CV_SEQ_MAGIC_VAL or CV_SET_MAGIC_VAL), type of the elements and some other information about the sequence.
sequence flags, including the sequence signature (CV_SEQ_MAGIC_VAL or CV_SET_MAGIC_VAL), type of the elements and some other information about the sequence.
.. ocv:member:: int header_size
.. ocv:member:: int header_size
size of the sequence header. It should be sizeof(CvSeq) at minimum. See :ocv:cfunc:`CreateSeq`.
size of the sequence header. It should be sizeof(CvSeq) at minimum. See :ocv:cfunc:`CreateSeq`.
.. ocv:member:: CvSeq* h_prev
.. ocv:member:: CvSeq* h_next
.. ocv:member:: CvSeq* v_prev
.. ocv:member:: CvSeq* v_next
.. ocv:member:: CvSeq* h_prev
.. ocv:member:: CvSeq* h_next
.. ocv:member:: CvSeq* v_prev
.. ocv:member:: CvSeq* v_next
pointers to another sequences in a sequence tree. Sequence trees are used to store hierarchical contour structures, retrieved by :ocv:cfunc:`FindContours`
pointers to another sequences in a sequence tree. Sequence trees are used to store hierarchical contour structures, retrieved by :ocv:cfunc:`FindContours`
.. ocv:member:: int total
.. ocv:member:: int total
the number of sequence elements
the number of sequence elements
.. ocv:member:: int elem_size
.. ocv:member:: int elem_size
size of each sequence element in bytes
size of each sequence element in bytes
.. ocv:member:: CvMemStorage* storage
.. ocv:member:: CvMemStorage* storage
memory storage where the sequence resides. It can be a NULL pointer.
memory storage where the sequence resides. It can be a NULL pointer.
.. ocv:member:: CvSeqBlock* first
.. ocv:member:: CvSeqBlock* first
pointer to the first data block
pointer to the first data block
The structure ``CvSeq`` is a base for all of OpenCV dynamic data structures.
There are two types of sequences - dense and sparse. The base type for dense
@@ -228,9 +228,9 @@ ClearSet
--------
Clears a set.
.. ocv:cfunction:: void cvClearSet( CvSet* setHeader )
.. ocv:cfunction:: void cvClearSet( CvSet* set_header )
:param setHeader: Cleared set
:param set_header: Cleared set
The function removes all elements from set. It has O(1) time complexity.
@@ -362,11 +362,12 @@ CreateMemStorage
----------------
Creates memory storage.
.. ocv:cfunction:: CvMemStorage* cvCreateMemStorage( int blockSize=0 )
.. ocv:cfunction:: CvMemStorage* cvCreateMemStorage( int block_size=0 )
.. ocv:pyoldfunction:: cv.CreateMemStorage(blockSize=0) -> memstorage
:param blockSize: Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is about 64K.
:param block_size: Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is about 64K.
The function creates an empty memory storage. See
:ocv:struct:`CvMemStorage`
@@ -376,14 +377,14 @@ CreateSeq
---------
Creates a sequence.
.. ocv:cfunction:: CvSeq* cvCreateSeq( int seqFlags, int headerSize, int elemSize, CvMemStorage* storage)
.. ocv:cfunction:: CvSeq* cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage* storage )
:param seqFlags: Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.
:param seq_flags: Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.
:param headerSize: Size of the sequence header; must be greater than or equal to ``sizeof(CvSeq)`` . If a specific type or its extension is indicated, this type must fit the base type header.
:param header_size: Size of the sequence header; must be greater than or equal to ``sizeof(CvSeq)`` . If a specific type or its extension is indicated, this type must fit the base type header.
:param elemSize: Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type ``CV_SEQ_ELTYPE_POINT`` should be specified and the parameter ``elemSize`` must be equal to ``sizeof(CvPoint)`` .
:param elem_size: Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type ``CV_SEQ_ELTYPE_POINT`` should be specified and the parameter ``elem_size`` must be equal to ``sizeof(CvPoint)`` .
:param storage: Sequence location
@@ -480,13 +481,13 @@ FindGraphEdgeByPtr
------------------
Finds an edge in a graph by using its pointer.
.. ocv:cfunction:: CvGraphEdge* cvFindGraphEdgeByPtr( const CvGraph* graph, const CvGraphVtx* startVtx, const CvGraphVtx* endVtx )
.. ocv:cfunction:: CvGraphEdge* cvFindGraphEdgeByPtr( const CvGraph* graph, const CvGraphVtx* start_vtx, const CvGraphVtx* end_vtx )
:param graph: Graph
:param startVtx: Pointer to the starting vertex of the edge
:param start_vtx: Pointer to the starting vertex of the edge
:param endVtx: Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
:param end_vtx: Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
::
@@ -529,7 +530,7 @@ GetSeqElem
----------
Returns a pointer to a sequence element according to its index.
.. ocv:cfunction:: char* cvGetSeqElem( const CvSeq* seq, int index )
.. ocv:cfunction:: schar* cvGetSeqElem( const CvSeq* seq, int index )
:param seq: Sequence
@@ -587,9 +588,9 @@ GetSetElem
----------
Finds a set element by its index.
.. ocv:cfunction:: CvSetElem* cvGetSetElem( const CvSet* setHeader, int index )
.. ocv:cfunction:: CvSetElem* cvGetSetElem( const CvSet* set_header, int index )
:param setHeader: Set
:param set_header: Set
:param index: Index of the set element within a sequence
@@ -723,11 +724,11 @@ GraphVtxDegree
--------------
Counts the number of edges incident to the vertex.
.. ocv:cfunction:: int cvGraphVtxDegree( const CvGraph* graph, int vtxIdx )
.. ocv:cfunction:: int cvGraphVtxDegree( const CvGraph* graph, int vtx_idx )
:param graph: Graph
:param vtxIdx: Index of the graph vertex
:param vtx_idx: Index of the graph vertex
The function returns the number of edges incident to the specified vertex, both incoming and outgoing. To count the edges, the following code is used:
@@ -1021,11 +1022,11 @@ SeqInsert
---------
Inserts an element in the middle of a sequence.
.. ocv:cfunction:: char* cvSeqInsert( CvSeq* seq, int beforeIndex, void* element=NULL )
.. ocv:cfunction:: schar* cvSeqInsert( CvSeq* seq, int before_index, const void* element=NULL )
:param seq: Sequence
:param beforeIndex: Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPushFront` and inserting before ``seq->total`` (the maximal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPush` .
:param before_index: Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPushFront` and inserting before ``seq->total`` (the maximal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPush` .
:param element: Inserted element
@@ -1037,13 +1038,13 @@ SeqInsertSlice
--------------
Inserts an array in the middle of a sequence.
.. ocv:cfunction:: void cvSeqInsertSlice( CvSeq* seq, int beforeIndex, const CvArr* fromArr )
.. ocv:cfunction:: void cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr )
:param seq: Sequence
:param beforeIndex: Index before which the array is inserted
:param before_index: Index before which the array is inserted
:param fromArr: The array to take elements from
:param from_arr: The array to take elements from
The function inserts all
``fromArr``
@@ -1109,7 +1110,7 @@ SeqPush
-------
Adds an element to the end of a sequence.
.. ocv:cfunction:: char* cvSeqPush( CvSeq* seq, void* element=NULL )
.. ocv:cfunction:: schar* cvSeqPush( CvSeq* seq, const void* element=NULL )
:param seq: Sequence
@@ -1149,7 +1150,7 @@ SeqPushFront
------------
Adds an element to the beginning of a sequence.
.. ocv:cfunction:: char* cvSeqPushFront( CvSeq* seq, void* element=NULL )
.. ocv:cfunction:: schar* cvSeqPushFront( CvSeq* seq, const void* element=NULL )
:param seq: Sequence
@@ -1163,7 +1164,7 @@ SeqPushMulti
------------
Pushes several elements to either end of a sequence.
.. ocv:cfunction:: void cvSeqPushMulti( CvSeq* seq, void* elements, int count, int in_front=0 )
.. ocv:cfunction:: void cvSeqPushMulti( CvSeq* seq, const void* elements, int count, int in_front=0 )
:param seq: Sequence
@@ -1216,7 +1217,7 @@ SeqSearch
---------
Searches for an element in a sequence.
.. ocv:cfunction:: char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, int is_sorted, int* elem_idx, void* userdata=NULL )
.. ocv:cfunction:: schar* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, int is_sorted, int* elem_idx, void* userdata=NULL )
:param seq: The sequence
@@ -1325,9 +1326,9 @@ SetAdd
------
Occupies a node in the set.
.. ocv:cfunction:: int cvSetAdd( CvSet* setHeader, CvSetElem* elem=NULL, CvSetElem** inserted_elem=NULL )
.. ocv:cfunction:: int cvSetAdd( CvSet* set_header, CvSetElem* elem=NULL, CvSetElem** inserted_elem=NULL )
:param setHeader: Set
:param set_header: Set
:param elem: Optional input argument, an inserted element. If not NULL, the function copies the data to the allocated node (the MSB of the first integer field is cleared after copying).
@@ -1346,9 +1347,9 @@ SetNew
------
Adds an element to a set (fast variant).
.. ocv:cfunction:: CvSetElem* cvSetNew( CvSet* setHeader )
.. ocv:cfunction:: CvSetElem* cvSetNew( CvSet* set_header )
:param setHeader: Set
:param set_header: Set
The function is an inline lightweight variant of
:ocv:cfunc:`SetAdd`
@@ -1358,9 +1359,9 @@ SetRemove
---------
Removes an element from a set.
.. ocv:cfunction:: void cvSetRemove( CvSet* setHeader, int index )
.. ocv:cfunction:: void cvSetRemove( CvSet* set_header, int index )
:param setHeader: Set
:param set_header: Set
:param index: Index of the removed element
@@ -1375,9 +1376,9 @@ SetRemoveByPtr
--------------
Removes a set element based on its pointer.
.. ocv:cfunction:: void cvSetRemoveByPtr( CvSet* setHeader, void* elem )
.. ocv:cfunction:: void cvSetRemoveByPtr( CvSet* set_header, void* elem )
:param setHeader: Set
:param set_header: Set
:param elem: Removed element
@@ -1389,23 +1390,23 @@ SetSeqBlockSize
---------------
Sets up sequence block size.
.. ocv:cfunction:: void cvSetSeqBlockSize( CvSeq* seq, int deltaElems )
.. ocv:cfunction:: void cvSetSeqBlockSize( CvSeq* seq, int delta_elems )
:param seq: Sequence
:param deltaElems: Desirable sequence block size for elements
:param delta_elems: Desirable sequence block size for elements
The function affects memory allocation
granularity. When the free space in the sequence buffers has run out,
the function allocates the space for
``deltaElems``
``delta_elems``
sequence
elements. If this block immediately follows the one previously allocated,
the two blocks are concatenated; otherwise, a new sequence block is
created. Therefore, the bigger the parameter is, the lower the possible
sequence fragmentation, but the more space in the storage block is wasted. When
the sequence is created, the parameter
``deltaElems``
``delta_elems``
is set to
the default value of about 1K. The function can be called any time after
the sequence is created and affects future allocations. The function
File diff suppressed because it is too large Load Diff
+227 -225
View File
@@ -48,41 +48,41 @@ CvFileNode
.. ocv:struct:: CvFileNode
File storage node. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a "leaf", that is, contain a single number or a string, or be a collection of other nodes. Collections are also referenced to as "structures" in the data writing functions. There can be named collections (mappings), where each element has a name and is accessed by a name, and ordered collections (sequences), where elements do not have names, but rather accessed by index.
File storage node. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a "leaf", that is, contain a single number or a string, or be a collection of other nodes. Collections are also referenced to as "structures" in the data writing functions. There can be named collections (mappings), where each element has a name and is accessed by a name, and ordered collections (sequences), where elements do not have names, but rather accessed by index.
.. ocv:member:: int tag
type of the file node:
* CV_NODE_NONE - empty node
* CV_NODE_INT - an integer
* CV_NODE_REAL - a floating-point number
* CV_NODE_STR - text string
* CV_NODE_SEQ - a sequence
* CV_NODE_MAP - a mapping
.. ocv:member:: int tag
type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro.
type of the file node:
.. ocv:member:: CvTypeInfo* info
optional pointer to the user type information. If you look at the matrix representation in XML and YAML, shown above, you may notice ``type_id="opencv-matrix"`` or ``!!opencv-matrix`` strings. They are used to specify that the certain element of a file is a representation of a data structure of certain type ("opencv-matrix" corresponds to :ocv:struct:`CvMat`). When a file is parsed, such type identifiers are passed to :ocv:cfunc:`FindType` to find type information and the pointer to it is stored in the file node. See :ocv:struct:`CvTypeInfo` for more details.
.. ocv:member:: union data
the node data, declared as: ::
union
{
double f; /* scalar floating-point number */
int i; /* scalar integer number */
CvString str; /* text string */
CvSeq* seq; /* sequence (ordered collection of file nodes) */
struct CvMap* map; /* map (collection of named file nodes) */
} data;
* CV_NODE_NONE - empty node
* CV_NODE_INT - an integer
* CV_NODE_REAL - a floating-point number
* CV_NODE_STR - text string
* CV_NODE_SEQ - a sequence
* CV_NODE_MAP - a mapping
..
Primitive nodes are read using :ocv:cfunc:`ReadInt`, :ocv:cfunc:`ReadReal` and :ocv:cfunc:`ReadString`. Sequences are read by iterating through ``node->data.seq`` (see "Dynamic Data Structures" section). Mappings are read using :ocv:cfunc:`GetFileNodeByName`. Nodes with the specified type (so that ``node->info != NULL``) can be read using :ocv:cfunc:`Read`.
type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro.
.. ocv:member:: CvTypeInfo* info
optional pointer to the user type information. If you look at the matrix representation in XML and YAML, shown above, you may notice ``type_id="opencv-matrix"`` or ``!!opencv-matrix`` strings. They are used to specify that the certain element of a file is a representation of a data structure of certain type ("opencv-matrix" corresponds to :ocv:struct:`CvMat`). When a file is parsed, such type identifiers are passed to :ocv:cfunc:`FindType` to find type information and the pointer to it is stored in the file node. See :ocv:struct:`CvTypeInfo` for more details.
.. ocv:member:: union data
the node data, declared as: ::
union
{
double f; /* scalar floating-point number */
int i; /* scalar integer number */
CvString str; /* text string */
CvSeq* seq; /* sequence (ordered collection of file nodes) */
struct CvMap* map; /* map (collection of named file nodes) */
} data;
..
Primitive nodes are read using :ocv:cfunc:`ReadInt`, :ocv:cfunc:`ReadReal` and :ocv:cfunc:`ReadString`. Sequences are read by iterating through ``node->data.seq`` (see "Dynamic Data Structures" section). Mappings are read using :ocv:cfunc:`GetFileNodeByName`. Nodes with the specified type (so that ``node->info != NULL``) can be read using :ocv:cfunc:`Read`.
CvAttrList
----------
@@ -97,16 +97,16 @@ List of attributes. ::
struct CvAttrList* next; /* pointer to next chunk of the attributes list */
}
CvAttrList;
/* initializes CvAttrList structure */
inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
/* returns attribute value or 0 (NULL) if there is no such attribute */
const char* cvAttrValue( const CvAttrList* attr, const char* attr_name );
..
In the current implementation, attributes are used to pass extra parameters when writing user objects (see
In the current implementation, attributes are used to pass extra parameters when writing user objects (see
:ocv:cfunc:`Write`). XML attributes inside tags are not supported, aside from the object type specification (``type_id`` attribute).
CvTypeInfo
@@ -124,7 +124,7 @@ Type information. ::
const void* structPtr,
CvAttrList attributes );
typedef void* (CV_CDECL *CvCloneFunc)( const void* structPtr );
typedef struct CvTypeInfo
{
int flags; /* not used */
@@ -132,7 +132,7 @@ Type information. ::
struct CvTypeInfo* prev; /* previous registered type in the list */
struct CvTypeInfo* next; /* next registered type in the list */
const char* type_name; /* type name, written to file storage */
/* methods */
CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
CvReleaseFunc release; /* releases object (memory etc.) */
@@ -151,11 +151,11 @@ Clone
-----
Makes a clone of an object.
.. ocv:cfunction:: void* cvClone( const void* structPtr )
:param structPtr: The object to clone
.. ocv:cfunction:: void* cvClone( const void* struct_ptr )
The function finds the type of a given object and calls ``clone`` with the passed object. Of course, if you know the object type, for example, ``structPtr`` is ``CvMat*``, it is faster to call the specific function, like :ocv:cfunc:`CloneMat`.
:param struct_ptr: The object to clone
The function finds the type of a given object and calls ``clone`` with the passed object. Of course, if you know the object type, for example, ``struct_ptr`` is ``CvMat*``, it is faster to call the specific function, like :ocv:cfunc:`CloneMat`.
EndWriteStruct
--------------
@@ -163,7 +163,7 @@ Finishes writing to a file node collection.
.. ocv:cfunction:: void cvEndWriteStruct(CvFileStorage* fs)
:param fs: File storage
:param fs: File storage
.. seealso:: :ocv:cfunc:`StartWriteStruct`.
@@ -171,9 +171,9 @@ FindType
--------
Finds a type by its name.
.. ocv:cfunction:: CvTypeInfo* cvFindType(const char* typeName)
:param typeName: Type name
.. ocv:cfunction:: CvTypeInfo* cvFindType( const char* type_name )
:param type_name: Type name
The function finds a registered type by its name. It returns NULL if there is no type with the specified name.
@@ -189,15 +189,15 @@ GetFileNode
-----------
Finds a node in a map or file storage.
.. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int createMissing=0 )
:param fs: File storage
.. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int create_missing=0 )
:param map: The parent map. If it is NULL, the function searches a top-level node. If both ``map`` and ``key`` are NULLs, the function returns the root file node - a map that contains top-level nodes.
:param fs: File storage
:param key: Unique pointer to the node name, retrieved with :ocv:cfunc:`GetHashedKey`
:param map: The parent map. If it is NULL, the function searches a top-level node. If both ``map`` and ``key`` are NULLs, the function returns the root file node - a map that contains top-level nodes.
:param createMissing: Flag that specifies whether an absent node should be added to the map
:param key: Unique pointer to the node name, retrieved with :ocv:cfunc:`GetHashedKey`
:param create_missing: Flag that specifies whether an absent node should be added to the map
The function finds a file node. It is a faster version of :ocv:cfunc:`GetFileNodeByName`
(see :ocv:cfunc:`GetHashedKey` discussion). Also, the function can insert a new node, if it is not in the map yet.
@@ -207,12 +207,12 @@ GetFileNodeByName
Finds a node in a map or file storage.
.. ocv:cfunction:: CvFileNode* cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name)
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one.
:param fs: File storage
:param name: The file node name
:param map: The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one.
:param name: The file node name
The function finds a file node by ``name``. The node is searched either in ``map`` or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and :ocv:cfunc:`GetSeqElem`
(or sequence reader) for sequences, it is possible to navigate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of :ocv:cfunc:`GetHashedKey` and :ocv:cfunc:`GetFileNode`.
@@ -223,7 +223,7 @@ Returns the name of a file node.
.. ocv:cfunction:: const char* cvGetFileNodeName( const CvFileNode* node )
:param node: File node
:param node: File node
The function returns the name of a file node or NULL, if the file node does not have a name or if ``node`` is ``NULL``.
@@ -231,21 +231,21 @@ GetHashedKey
------------
Returns a unique pointer for a given name.
.. ocv:cfunction:: CvStringHashNode* cvGetHashedKey( CvFileStorage* fs, const char* name, int len=-1, int createMissing=0 )
.. ocv:cfunction:: CvStringHashNode* cvGetHashedKey( CvFileStorage* fs, const char* name, int len=-1, int create_missing=0 )
:param fs: File storage
:param fs: File storage
:param name: Literal node name
:param name: Literal node name
:param len: Length of the name (if it is known apriori), or -1 if it needs to be calculated
:param len: Length of the name (if it is known apriori), or -1 if it needs to be calculated
:param createMissing: Flag that specifies, whether an absent key should be added into the hash table
:param create_missing: Flag that specifies, whether an absent key should be added into the hash table
The function returns a unique pointer for each particular file node name. This pointer can be then passed to the :ocv:cfunc:`GetFileNode` function that is faster than :ocv:cfunc:`GetFileNodeByName`
because it compares text strings by comparing pointers rather than the strings' content.
Consider the following example where an array of points is encoded as a sequence of 2-entry maps: ::
points:
- { x: 10, y: 10 }
- { x: 20, y: 20 }
@@ -257,14 +257,14 @@ Consider the following example where an array of points is encoded as a sequence
Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. ::
#include "cxcore.h"
int main( int argc, char** argv )
{
CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
if( CV_NODE_IS_SEQ(points->tag) )
{
CvSeq* seq = points->data.seq;
@@ -312,10 +312,10 @@ GetRootFileNode
Retrieves one of the top-level nodes of the file storage.
.. ocv:cfunction:: CvFileNode* cvGetRootFileNode( const CvFileStorage* fs, int stream_index=0 )
:param fs: File storage
:param stream_index: Zero-based index of the stream. See :ocv:cfunc:`StartNextStream` . In most cases, there is only one stream in the file; however, there can be several.
:param fs: File storage
:param stream_index: Zero-based index of the stream. See :ocv:cfunc:`StartNextStream` . In most cases, there is only one stream in the file; however, there can be several.
The function returns one of the top-level file nodes. The top-level nodes do not have a name, they correspond to the streams that are stored one after another in the file storage. If the index is out of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by subsequent calls to the function with ``stream_index=0,1,...``, until the NULL pointer is returned. This function
can be used as a base for recursive traversal of the file storage.
@@ -325,16 +325,17 @@ Load
----
Loads an object from a file.
.. ocv:cfunction:: void* cvLoad( const char* filename, CvMemStorage* storage=NULL, const char* name=NULL, const char** realName=NULL )
.. ocv:cfunction:: void* cvLoad( const char* filename, CvMemStorage* memstorage=NULL, const char* name=NULL, const char** real_name=NULL )
.. ocv:pyoldfunction:: cv.Load(filename, storage=None, name=None)-> generic
:param filename: File name
:param storage: Memory storage for dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` . It is not used for matrices or images.
:param filename: File name
:param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded.
:param memstorage: Memory storage for dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` . It is not used for matrices or images.
:param realName: Optional output parameter that will contain the name of the loaded object (useful if ``name=NULL`` )
:param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded.
:param real_name: Optional output parameter that will contain the name of the loaded object (useful if ``name=NULL`` )
The function loads an object from a file. It basically reads the specified file, find the first top-level node and calls :ocv:cfunc:`Read` for that node. If the file node does not have type information or the type information can not be found by the type name, the function returns NULL. After the object is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage destination to the function.
@@ -342,19 +343,19 @@ OpenFileStorage
---------------
Opens file storage for reading or writing data.
.. ocv:cfunction:: CvFileStorage* cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags)
.. ocv:cfunction:: CvFileStorage* cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags, const char* encoding=NULL )
:param filename: Name of the file associated with the storage
:param filename: Name of the file associated with the storage
:param memstorage: Memory storage used for temporary data and for
storing dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` .
If it is NULL, a temporary memory storage is created and used.
If it is NULL, a temporary memory storage is created and used.
:param flags: Can be one of the following:
* **CV_STORAGE_READ** the storage is open for reading
* **CV_STORAGE_READ** the storage is open for reading
* **CV_STORAGE_WRITE** the storage is open for writing
* **CV_STORAGE_WRITE** the storage is open for writing
The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: ``.xml`` for ``XML`` and ``.yml`` or ``.yaml`` for ``YAML``. The function returns a pointer to the :ocv:struct:`CvFileStorage` structure. If the file cannot be opened then the function returns ``NULL``.
@@ -363,12 +364,12 @@ Read
Decodes an object and returns a pointer to it.
.. ocv:cfunction:: void* cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes=NULL )
:param fs: File storage
:param node: The root object node
:param fs: File storage
:param attributes: Unused parameter
:param node: The root object node
:param attributes: Unused parameter
The function decodes a user object (creates an object in a native representation from the file storage subtree) and returns it. The object to be decoded must be an instance of a registered type that supports the ``read`` method (see :ocv:struct:`CvTypeInfo`). The type of the object is determined by the type name that is encoded in the file. If the object is a dynamic structure, it is created either in memory storage and passed to :ocv:cfunc:`OpenFileStorage` or, if a NULL pointer was passed, in temporary
memory storage, which is released when :ocv:cfunc:`ReleaseFileStorage` is called. Otherwise, if the object is not a dynamic structure, it is created in a heap and should be released with a specialized function or by using the generic :ocv:cfunc:`Release`.
@@ -378,14 +379,14 @@ ReadByName
Finds an object by name and decodes it.
.. ocv:cfunction:: void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes=NULL )
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param fs: File storage
:param name: The node name
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param attributes: Unused parameter
:param name: The node name
:param attributes: Unused parameter
The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and :ocv:cfunc:`Read`.
@@ -393,29 +394,29 @@ ReadInt
-------
Retrieves an integer value from a file node.
.. ocv:cfunction:: int cvReadInt( const CvFileNode* node, int defaultValue=0 )
.. ocv:cfunction:: int cvReadInt( const CvFileNode* node, int default_value=0 )
:param node: File node
:param node: File node
:param defaultValue: The value that is returned if ``node`` is NULL
:param default_value: The value that is returned if ``node`` is NULL
The function returns an integer that is represented by the file node. If the file node is NULL, the
``defaultValue`` is returned (thus, it is convenient to call the function right after :ocv:cfunc:`GetFileNode` without checking for a NULL pointer). If the file node has type ``CV_NODE_INT``, then ``node->data.i`` is returned. If the file node has type ``CV_NODE_REAL``, then ``node->data.f``
The function returns an integer that is represented by the file node. If the file node is NULL, the
``default_value`` is returned (thus, it is convenient to call the function right after :ocv:cfunc:`GetFileNode` without checking for a NULL pointer). If the file node has type ``CV_NODE_INT``, then ``node->data.i`` is returned. If the file node has type ``CV_NODE_REAL``, then ``node->data.f``
is converted to an integer and returned. Otherwise the error is reported.
ReadIntByName
-------------
Finds a file node and returns its value.
.. ocv:cfunction:: int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int defaultValue=0 )
.. ocv:cfunction:: int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int default_value=0 )
:param fs: File storage
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param name: The node name
:param name: The node name
:param defaultValue: The value that is returned if the file node is not found
:param default_value: The value that is returned if the file node is not found
The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and :ocv:cfunc:`ReadInt`.
@@ -425,13 +426,13 @@ Reads multiple numbers.
.. ocv:cfunction:: void cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt)
:param fs: File storage
:param fs: File storage
:param src: The file node (a sequence) to read numbers from
:param src: The file node (a sequence) to read numbers from
:param dst: Pointer to the destination array
:param dst: Pointer to the destination array
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
The function reads elements from a file node that represents a sequence of scalars.
@@ -441,16 +442,16 @@ ReadRawDataSlice
Initializes file node sequence reader.
.. ocv:cfunction:: void cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt )
:param fs: File storage
:param reader: The sequence reader. Initialize it with :ocv:cfunc:`StartReadRawData` .
:param fs: File storage
:param count: The number of elements to read
:param reader: The sequence reader. Initialize it with :ocv:cfunc:`StartReadRawData` .
:param dst: Pointer to the destination array
:param count: The number of elements to read
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
:param dst: Pointer to the destination array
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
The function reads one or more elements from the file node, representing a sequence, to a user-specified array. The total number of read sequence elements is a product of ``total``
and the number of components in each array element. For example, if ``dt=2if``, the function will read ``total*3`` sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read repeatedly by repositioning the reader using :ocv:cfunc:`SetSeqReaderPos`.
@@ -459,27 +460,27 @@ ReadReal
--------
Retrieves a floating-point value from a file node.
.. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double defaultValue=0. )
:param node: File node
.. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double default_value=0. )
:param defaultValue: The value that is returned if ``node`` is NULL
:param node: File node
:param default_value: The value that is returned if ``node`` is NULL
The function returns a floating-point value
that is represented by the file node. If the file node is NULL, the
``defaultValue``
``default_value``
is returned (thus, it is convenient to call
the function right after
the function right after
:ocv:cfunc:`GetFileNode`
without checking for a NULL
pointer). If the file node has type
pointer). If the file node has type
``CV_NODE_REAL``
,
then
then
``node->data.f``
is returned. If the file node has type
``CV_NODE_INT``
, then
, then
``node-:math:`>`data.f``
is converted to floating-point
and returned. Otherwise the result is not determined.
@@ -489,19 +490,19 @@ ReadRealByName
--------------
Finds a file node and returns its value.
.. ocv:cfunction:: double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double defaultValue=0.)
:param fs: File storage
.. ocv:cfunction:: double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double default_value=0. )
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param fs: File storage
:param name: The node name
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param defaultValue: The value that is returned if the file node is not found
:param name: The node name
The function is a simple superposition of
:param default_value: The value that is returned if the file node is not found
The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName`
and
and
:ocv:cfunc:`ReadReal`
.
@@ -510,21 +511,21 @@ ReadString
----------
Retrieves a text string from a file node.
.. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* defaultValue=NULL )
:param node: File node
.. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* default_value=NULL )
:param defaultValue: The value that is returned if ``node`` is NULL
:param node: File node
:param default_value: The value that is returned if ``node`` is NULL
The function returns a text string that is represented
by the file node. If the file node is NULL, the
``defaultValue``
by the file node. If the file node is NULL, the
``default_value``
is returned (thus, it is convenient to call the function right after
:ocv:cfunc:`GetFileNode`
without checking for a NULL pointer). If
the file node has type
the file node has type
``CV_NODE_STR``
, then
, then
``node-:math:`>`data.str.ptr``
is returned. Otherwise the result is not determined.
@@ -533,19 +534,19 @@ ReadStringByName
----------------
Finds a file node by its name and returns its value.
.. ocv:cfunction:: const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* defaultValue=NULL )
:param fs: File storage
.. ocv:cfunction:: const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* default_value=NULL )
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param fs: File storage
:param name: The node name
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param defaultValue: The value that is returned if the file node is not found
:param name: The node name
The function is a simple superposition of
:param default_value: The value that is returned if the file node is not found
The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName`
and
and
:ocv:cfunc:`ReadString`
.
@@ -556,10 +557,10 @@ Registers a new type.
.. ocv:cfunction:: void cvRegisterType(const CvTypeInfo* info)
:param info: Type info structure
:param info: Type info structure
The function registers a new type, which is
described by
described by
``info``
. The function creates a copy of the structure,
so the user should delete it after calling the function.
@@ -569,11 +570,11 @@ Release
-------
Releases an object.
.. ocv:cfunction:: void cvRelease( void** structPtr )
.. ocv:cfunction:: void cvRelease( void** struct_ptr )
:param structPtr: Double pointer to the object
:param struct_ptr: Double pointer to the object
The function finds the type of a given object and calls
The function finds the type of a given object and calls
``release``
with the double pointer.
@@ -583,8 +584,8 @@ ReleaseFileStorage
Releases file storage.
.. ocv:cfunction:: void cvReleaseFileStorage(CvFileStorage** fs)
:param fs: Double pointer to the released file storage
:param fs: Double pointer to the released file storage
The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
@@ -593,20 +594,21 @@ Save
----
Saves an object to a file.
.. ocv:cfunction:: void cvSave( const char* filename, const void* structPtr, const char* name=NULL, const char* comment=NULL, CvAttrList attributes=cvAttrList())
.. ocv:cfunction:: void cvSave( const char* filename, const void* struct_ptr, const char* name=NULL, const char* comment=NULL, CvAttrList attributes=cvAttrList() )
.. ocv:pyoldfunction:: cv.Save(filename, structPtr, name=None, comment=None)-> None
:param filename: File name
:param structPtr: Object to save
:param filename: File name
:param name: Optional object name. If it is NULL, the name will be formed from ``filename`` .
:param struct_ptr: Object to save
:param comment: Optional comment to put in the beginning of the file
:param name: Optional object name. If it is NULL, the name will be formed from ``filename`` .
:param attributes: Optional attributes passed to :ocv:cfunc:`Write`
:param comment: Optional comment to put in the beginning of the file
The function saves an object to a file. It provides a simple interface to
:param attributes: Optional attributes passed to :ocv:cfunc:`Write`
The function saves an object to a file. It provides a simple interface to
:ocv:cfunc:`Write`
.
@@ -617,7 +619,7 @@ Starts the next stream.
.. ocv:cfunction:: void cvStartNextStream(CvFileStorage* fs)
:param fs: File storage
:param fs: File storage
The function finishes the currently written stream and starts the next stream. In the case of XML the file with multiple streams looks like this: ::
@@ -646,11 +648,11 @@ Initializes the file node sequence reader.
.. ocv:cfunction:: void cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader)
:param fs: File storage
:param fs: File storage
:param src: The file node (a sequence) to read numbers from
:param src: The file node (a sequence) to read numbers from
:param reader: Pointer to the sequence reader
:param reader: Pointer to the sequence reader
The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to :ocv:cfunc:`ReadRawDataSlice`.
@@ -659,31 +661,31 @@ StartWriteStruct
----------------
Starts writing a new structure.
.. ocv:cfunction:: void cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* typeName=NULL, CvAttrList attributes=cvAttrList())
:param fs: File storage
.. ocv:cfunction:: void cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* type_name=NULL, CvAttrList attributes=cvAttrList() )
:param name: Name of the written structure. The structure can be accessed by this name when the storage is read.
:param fs: File storage
:param struct_flags: A combination one of the following values:
* **CV_NODE_SEQ** the written structure is a sequence (see discussion of :ocv:struct:`CvFileStorage` ), that is, its elements do not have a name.
* **CV_NODE_MAP** the written structure is a map (see discussion of :ocv:struct:`CvFileStorage` ), that is, all its elements have names.
:param name: Name of the written structure. The structure can be accessed by this name when the storage is read.
One and only one of the two above flags must be specified
:param struct_flags: A combination one of the following values:
* **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.
* **CV_NODE_SEQ** the written structure is a sequence (see discussion of :ocv:struct:`CvFileStorage` ), that is, its elements do not have a name.
:param typeName: Optional parameter - the object type name. In
* **CV_NODE_MAP** the written structure is a map (see discussion of :ocv:struct:`CvFileStorage` ), that is, all its elements have names.
One and only one of the two above flags must be specified
* **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.
:param type_name: Optional parameter - the object type name. In
case of XML it is written as a ``type_id`` attribute of the
structure opening tag. In the case of YAML it is written after a colon
following the structure name (see the example in :ocv:struct:`CvFileStorage`
following the structure name (see the example in :ocv:struct:`CvFileStorage`
description). Mainly it is used with user objects. When the storage
is read, the encoded type name is used to determine the object type
(see :ocv:struct:`CvTypeInfo` and :ocv:cfunc:`FindType` ).
(see :ocv:struct:`CvTypeInfo` and :ocv:cfunc:`FindType` ).
:param attributes: This parameter is not used in the current implementation
:param attributes: This parameter is not used in the current implementation
The function starts writing a compound structure (collection) that can be a sequence or a map. After all the structure fields, which can be scalars or structures, are written, :ocv:cfunc:`EndWriteStruct` should be called. The function can be used to group some objects or to implement the ``write`` function for a some user object (see :ocv:struct:`CvTypeInfo`).
@@ -692,9 +694,9 @@ TypeOf
------
Returns the type of an object.
.. ocv:cfunction:: CvTypeInfo* cvTypeOf( const void* structPtr )
.. ocv:cfunction:: CvTypeInfo* cvTypeOf( const void* struct_ptr )
:param structPtr: The object pointer
:param struct_ptr: The object pointer
The function finds the type of a given object. It iterates through the list of registered types and calls the ``is_instance`` function/method for every type info structure with that object until one of them returns non-zero or until the whole list has been traversed. In the latter case, the function returns NULL.
@@ -703,9 +705,9 @@ UnregisterType
--------------
Unregisters the type.
.. ocv:cfunction:: void cvUnregisterType( const char* typeName )
:param typeName: Name of an unregistered type
.. ocv:cfunction:: void cvUnregisterType( const char* type_name )
:param type_name: Name of an unregistered type
The function unregisters a type with a specified name. If the name is unknown, it is possible to locate the type info by an instance of the type using :ocv:cfunc:`TypeOf` or by iterating the type list, starting from :ocv:cfunc:`FirstType`, and then calling ``cvUnregisterType(info->typeName)``.
@@ -715,12 +717,12 @@ Write
Writes an object to file storage.
.. ocv:cfunction:: void cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes=cvAttrList() )
:param fs: File storage
:param name: Name of the written object. Should be NULL if and only if the parent structure is a sequence.
:param fs: File storage
:param ptr: Pointer to the object
:param name: Name of the written object. Should be NULL if and only if the parent structure is a sequence.
:param ptr: Pointer to the object
:param attributes: The attributes of the object. They are specific for each particular type (see the discussion below).
@@ -731,37 +733,37 @@ Attributes are used to customize the writing procedure. The standard types suppo
#.
CvSeq
* **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence)
* **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence)
* **dt** description of the sequence elements.
* **dt** description of the sequence elements.
* **recursive** if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.
#.
CvGraph
* **header_dt** description of user fields of the graph header that follows CvGraph;
* **header_dt** description of user fields of the graph header that follows CvGraph;
* **vertex_dt** description of user fields of graph vertices
* **vertex_dt** description of user fields of graph vertices
* **edge_dt** description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly)
Below is the code that creates the YAML file shown in the
Below is the code that creates the YAML file shown in the
``CvFileStorage``
description:
::
#include "cxcore.h"
int main( int argc, char** argv )
{
CvMat* mat = cvCreateMat( 3, 3, CV_32F );
CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );
cvSetIdentity( mat );
cvWrite( fs, "A", mat, cvAttrList(0,0) );
cvReleaseFileStorage( &fs );
cvReleaseMat( &mat );
return 0;
@@ -774,13 +776,13 @@ WriteComment
------------
Writes a comment.
.. ocv:cfunction:: void cvWriteComment( CvFileStorage* fs, const char* comment, int eolComment)
.. ocv:cfunction:: void cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment )
:param fs: File storage
:param fs: File storage
:param comment: The written comment, single-line or multi-line
:param comment: The written comment, single-line or multi-line
:param eolComment: If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line.
:param eol_comment: If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line.
The function writes a comment into file storage. The comments are skipped when the storage is read.
@@ -789,14 +791,14 @@ WriteFileNode
Writes a file node to another file storage.
.. ocv:cfunction:: void cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed )
:param fs: Destination file storage
:param new_node_name: New name of the file node in the destination file storage. To keep the existing name, use :ocv:cfunc:`cvGetFileNodeName`
:param fs: Destination file storage
:param node: The written node
:param new_node_name: New name of the file node in the destination file storage. To keep the existing name, use :ocv:cfunc:`cvGetFileNodeName`
:param embed: If the written node is a collection and this parameter is not zero, no extra level of hierarchy is created. Instead, all the elements of ``node`` are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence.
:param node: The written node
:param embed: If the written node is a collection and this parameter is not zero, no extra level of hierarchy is created. Instead, all the elements of ``node`` are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence.
The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
@@ -806,11 +808,11 @@ Writes an integer value.
.. ocv:cfunction:: void cvWriteInt( CvFileStorage* fs, const char* name, int value)
:param fs: File storage
:param fs: File storage
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param value: The written value
:param value: The written value
The function writes a single integer value (with or without a name) to the file storage.
@@ -820,29 +822,29 @@ WriteRawData
Writes multiple numbers.
.. ocv:cfunction:: void cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt )
:param fs: File storage
:param src: Pointer to the written array
:param fs: File storage
:param len: Number of the array elements to write
:param src: Pointer to the written array
:param dt: Specification of each array element that has the following format ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...``
where the characters correspond to fundamental C types:
:param len: Number of the array elements to write
* **u** 8-bit unsigned number
:param dt: Specification of each array element that has the following format ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...``
where the characters correspond to fundamental C types:
* **c** 8-bit signed number
* **u** 8-bit unsigned number
* **w** 16-bit unsigned number
* **c** 8-bit signed number
* **s** 16-bit signed number
* **w** 16-bit unsigned number
* **i** 32-bit signed number
* **s** 16-bit signed number
* **f** single precision floating-point number
* **i** 32-bit signed number
* **d** double precision floating-point number
* **f** single precision floating-point number
* **d** double precision floating-point number
* **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements. ``count`` is the optional counter of values of a given type. For
example, ``2if`` means that each array element is a structure
@@ -854,9 +856,9 @@ Writes multiple numbers.
The function writes an array, whose elements consist
of single or multiple numbers. The function call can be replaced with
a loop containing a few
a loop containing a few
:ocv:cfunc:`WriteInt`
and
and
:ocv:cfunc:`WriteReal`
calls, but
a single call is more efficient. Note that because none of the elements
@@ -868,12 +870,12 @@ WriteReal
Writes a floating-point value.
.. ocv:cfunction:: void cvWriteReal( CvFileStorage* fs, const char* name, double value )
:param fs: File storage
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param fs: File storage
:param value: The written value
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param value: The written value
The function writes a single floating-point value (with or without a name) to file storage. Special values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf.
@@ -900,12 +902,12 @@ Writes a text string.
.. ocv:cfunction:: void cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote=0 )
:param fs: File storage
:param fs: File storage
:param name: Name of the written string . Should be NULL if and only if the parent structure is a sequence.
:param name: Name of the written string . Should be NULL if and only if the parent structure is a sequence.
:param str: The written text string
:param str: The written text string
:param quote: If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).
:param quote: If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).
The function writes a text string to file storage.
File diff suppressed because it is too large Load Diff
@@ -93,9 +93,9 @@ Computes the cube root of an argument.
.. ocv:pyfunction:: cv2.cubeRoot(val) -> retval
.. ocv:cfunction:: float cvCbrt(float val)
.. ocv:cfunction:: float cvCbrt( float value )
.. ocv:pyoldfunction:: cv.Cbrt(val)-> float
.. ocv:pyoldfunction:: cv.Cbrt(value)-> float
:param val: A function argument.
@@ -151,7 +151,7 @@ Determines if the argument is Infinity.
.. ocv:cfunction:: int cvIsInf(double value)
.. ocv:pyoldfunction:: cv.IsInf(value)-> int
:param value: The input floating-point value
:param value: The input floating-point value
The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) and 0 otherwise.
@@ -162,7 +162,7 @@ Determines if the argument is Not A Number.
.. ocv:cfunction:: int cvIsNaN(double value)
.. ocv:pyoldfunction:: cv.IsNaN(value)-> int
:param value: The input floating-point value
:param value: The input floating-point value
The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
@@ -182,12 +182,12 @@ Signals an error and raises an exception.
.. ocv:function:: void error( const Exception& exc )
.. ocv:cfunction:: int cvError( int status, const char* funcName, const char* err_msg, const char* filename, int line )
.. ocv:cfunction:: void cvError( int status, const char* func_name, const char* err_msg, const char* file_name, int line )
:param exc: Exception to throw.
:param status: Error code. Normally, it is a negative value. The list of pre-defined error codes can be found in ``cxerror.h`` .
:param status: Error code. Normally, it is a negative value. The list of pre-defined error codes can be found in ``cxerror.h`` .
:param err_msg: Text of the error message.
:param args: ``printf`` -like formatted error message in parentheses.
@@ -209,7 +209,7 @@ The macro ``CV_Error_`` can be used to construct an error message on-fly to incl
Exception
---------
.. ocv:class:: Exception
.. ocv:class:: Exception : public std::exception
Exception class passed to an error. ::
@@ -244,7 +244,8 @@ fastMalloc
--------------
Allocates an aligned memory buffer.
.. ocv:function:: void* fastMalloc(size_t size)
.. ocv:function:: void* fastMalloc( size_t bufSize )
.. ocv:cfunction:: void* cvAlloc( size_t size )
:param size: Allocated buffer size.
@@ -261,7 +262,7 @@ Deallocates a memory buffer.
.. ocv:cfunction:: void cvFree( void** pptr )
:param ptr: Pointer to the allocated buffer.
:param pptr: Double pointer to the allocated buffer
The function deallocates the buffer allocated with :ocv:func:`fastMalloc` . If NULL pointer is passed, the function does nothing. C version of the function clears the pointer ``*pptr`` to avoid problems with double memory deallocation.
@@ -276,7 +277,7 @@ Returns a text string formatted using the ``printf``\ -like expression.
:param fmt: ``printf`` -compatible formatting specifiers.
The function acts like ``sprintf`` but forms and returns an STL string. It can be used to form an error message in the
:ocv:func:`Exception` constructor.
:ocv:class:`Exception` constructor.
@@ -286,10 +287,10 @@ Returns true if the specified feature is supported by the host hardware.
.. ocv:function:: bool checkHardwareSupport(int feature)
.. ocv:cfunction:: int cvCheckHardwareSupport(int feature)
.. ocv:pyfunction:: checkHardwareSupport(feature) -> Bool
.. ocv:pyfunction:: cv2.checkHardwareSupport(feature) -> retval
:param feature: The feature of interest, one of:
* ``CV_CPU_MMX`` - MMX
* ``CV_CPU_SSE`` - SSE
* ``CV_CPU_SSE2`` - SSE 2
@@ -312,7 +313,7 @@ The function returns the number of threads that is used by OpenCV.
.. seealso::
:ocv:func:`setNumThreads`,
:ocv:func:`getThreadNum`
:ocv:func:`getThreadNum`
@@ -411,7 +412,7 @@ The function sets the number of threads used by OpenCV in parallel OpenMP region
.. seealso::
:ocv:func:`getNumThreads`,
:ocv:func:`getThreadNum`
:ocv:func:`getThreadNum`
@@ -419,13 +420,13 @@ setUseOptimized
-----------------
Enables or disables the optimized code.
.. ocv:function:: void setUseOptimized(bool onoff)
.. ocv:function:: int cvUseOptimized( int on_off )
.. ocv:pyfunction:: cv2.setUseOptimized(onoff) -> None
.. ocv:cfunction:: int cvUseOptimized( int onoff )
.. ocv:cfunction:: int cvUseOptimized( int on_off )
:param onoff: The boolean flag specifying whether the optimized code should be used (``onoff=true``) or not (``onoff=false``).
:param on_off: The boolean flag specifying whether the optimized code should be used (``on_off=true``) or not (``on_off=false``).
The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX, and other instructions on the platforms that support it). It sets a global flag that is further checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only safe to call the function on the very top level in your application where you can be sure that no other OpenCV function is currently executed.
+45 -34
View File
@@ -18,9 +18,9 @@ Here is an example: ::
#include "opencv2/opencv.hpp"
#include <time.h>
using namespace cv;
int main(int, char** argv)
{
FileStorage fs("test.yml", FileStorage::WRITE);
@@ -76,18 +76,18 @@ As an exercise, you can replace ".yml" with ".xml" in the sample above and see,
Several things can be noted by looking at the sample code and the output:
*
The produced YAML (and XML) consists of heterogeneous collections that can be nested. There are 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings each element has a name and is accessed by name. This is similar to structures and ``std::map`` in C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by indices. This is similar to arrays and ``std::vector`` in C/C++ and lists, tuples in Python. "Heterogeneous" means that elements of each single collection can have different types.
Top-level collection in YAML/XML is a mapping. Each matrix is stored as a mapping, and the matrix elements are stored as a sequence. Then, there is a sequence of features, where each feature is represented a mapping, and lbp value in a nested sequence.
*
When you write to a mapping (a structure), you write element name followed by its value. When you write to a sequence, you simply write the elements one by one. OpenCV data structures (such as cv::Mat) are written in absolutely the same way as simple C data structures - using **``<<``** operator.
*
To write a mapping, you first write the special string **"{"** to the storage, then write the elements as pairs (``fs << <element_name> << <element_value>``) and then write the closing **"}"**.
*
To write a sequence, you first write the special string **"["**, then write the elements, then write the closing **"]"**.
*
In YAML (but not XML), mappings and sequences can be written in a compact Python-like inline form. In the sample above matrix elements, as well as each feature, including its lbp value, is stored in such inline form. To store a mapping/sequence in a compact form, put ":" after the opening character, e.g. use **"{:"** instead of **"{"** and **"[:"** instead of **"["**. When the data is written to XML, those extra ":" are ignored.
@@ -99,38 +99,38 @@ To read the previously written XML or YAML file, do the following:
#.
Open the file storage using :ocv:func:`FileStorage::FileStorage` constructor or :ocv:func:`FileStorage::open` method. In the current implementation the whole file is parsed and the whole representation of file storage is built in memory as a hierarchy of file nodes (see :ocv:class:`FileNode`)
#.
Read the data you are interested in. Use :ocv:func:`FileStorage::operator []`, :ocv:func:`FileNode::operator []` and/or :ocv:class:`FileNodeIterator`.
#.
Close the storage using :ocv:func:`FileStorage::release`.
Close the storage using :ocv:func:`FileStorage::release`.
Here is how to read the file created by the code sample above: ::
FileStorage fs2("test.yml", FileStorage::READ);
// first method: use (type) operator on FileNode.
int frameCount = (int)fs2["frameCount"];
std::string date;
// second method: use FileNode::operator >>
fs2["calibrationDate"] >> date;
Mat cameraMatrix2, distCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["distCoeffs"] >> distCoeffs2;
cout << "frameCount: " << frameCount << endl
<< "calibration date: " << date << endl
<< "camera matrix: " << cameraMatrix2 << endl
<< "distortion coeffs: " << distCoeffs2 << endl;
FileNode features = fs2["features"];
FileNodeIterator it = features.begin(), it_end = features.end();
int idx = 0;
std::vector<uchar> lbpval;
// iterate through a sequence using FileNodeIterator
for( ; it != it_end; ++it, idx++ )
{
@@ -156,9 +156,9 @@ The constructors.
.. ocv:function:: FileStorage::FileStorage()
.. ocv:function:: FileStorage::FileStorage(const string& filename, int flags, const string& encoding=string())
.. ocv:function:: FileStorage::FileStorage(const string& source, int flags, const string& encoding=string())
:param filename: Name of the file to open. Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively). Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``.
:param source: Name of the file to open or the text string to read the data from. Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively). Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``. If both ``FileStorage::WRITE`` and ``FileStorage::MEMORY`` flags are specified, ``source`` is used just to specify the output file format (e.g. ``mydata.xml``, ``.yml`` etc.).
:param flags: Mode of operation. Possible values are:
@@ -167,6 +167,8 @@ The constructors.
* **FileStorage::WRITE** Open the file for writing.
* **FileStorage::APPEND** Open the file for appending.
* **FileStorage::MEMORY** Read data from ``source`` or write data to the internal buffer (which is returned by ``FileStorage::release``)
:param encoding: Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it.
@@ -189,7 +191,7 @@ Checks whether the file is opened.
.. ocv:function:: bool FileStorage::isOpened() const
:returns: ``true`` if the object is associated with the current file and ``false`` otherwise.
It is a good practice to call this method after you tried to open a file.
@@ -202,6 +204,15 @@ Closes the file and releases all the memory buffers.
Call this method after all I/O operations with the storage are finished.
FileStorage::releaseAndGetString
--------------------------------
Closes the file and releases all the memory buffers.
.. ocv:function:: string FileStorage::releaseAndGetString()
Call this method after all I/O operations with the storage are finished. If the storage was opened for writing data and ``FileStorage::WRITE`` was specified
FileStorage::getFirstTopLevelNode
---------------------------------
Returns the first element of the top-level mapping.
@@ -254,22 +265,22 @@ Writes multiple numbers.
:param fmt: Specification of each array element that has the following format ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...`` where the characters correspond to fundamental C++ types:
* **u** 8-bit unsigned number
* **u** 8-bit unsigned number
* **c** 8-bit signed number
* **c** 8-bit signed number
* **w** 16-bit unsigned number
* **w** 16-bit unsigned number
* **s** 16-bit signed number
* **s** 16-bit signed number
* **i** 32-bit signed number
* **i** 32-bit signed number
* **f** single precision floating-point number
* **f** single precision floating-point number
* **d** double precision floating-point number
* **d** double precision floating-point number
* **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements.
* **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements.
``count`` is the optional counter of values of a given type. For example, ``2if`` means that each array element is a structure of 2 integers, followed by a single-precision floating-point number. The equivalent notations of the above specification are ' ``iif`` ', ' ``2i1f`` ' and so forth. Other examples: ``u`` means that the array consists of bytes, and ``2d`` means the array consists of pairs of doubles.
:param vec: Pointer to the written array.
@@ -431,7 +442,7 @@ Checks whether the node is empty.
FileNode::isNone
----------------
Checks whether the node is a "none" object
Checks whether the node is a "none" object
.. ocv:function:: bool FileNode::isNone() const
@@ -459,7 +470,7 @@ Checks whether the node is a mapping.
FileNode::isInt
---------------
Checks whether the node is an integer.
.. ocv:function:: bool FileNode::isInt() const
:returns: ``true`` if the node is an integer.
@@ -544,7 +555,7 @@ Returns the node content as text string.
.. ocv:function:: FileNode::operator string() const
:returns: The node content as a text string.
FileNode::operator*
-------------------
@@ -663,7 +674,7 @@ FileNodeIterator::operator +=
-----------------------------
Moves iterator forward by the specified offset.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator += (int ofs)
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator +=( int ofs )
:param ofs: Offset (possibly negative) to move the iterator.
@@ -672,7 +683,7 @@ FileNodeIterator::operator -=
-----------------------------
Moves iterator backward by the specified offset (possibly negative).
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -= (int ofs)
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -=( int ofs )
:param ofs: Offset (possibly negative) to move the iterator.
File diff suppressed because it is too large Load Diff
@@ -233,6 +233,34 @@ CV_INLINE IppiSize ippiSize(int width, int height)
}
#endif
#define CV_INIT_ALGORITHM(classname, algname, memberinit) \
static Algorithm* create##classname() \
{ \
return new classname; \
} \
\
static AlgorithmInfo& classname##_info() \
{ \
static AlgorithmInfo classname##_info_var(algname, create##classname); \
return classname##_info_var; \
} \
\
static AlgorithmInfo& classname##_info_auto = classname##_info(); \
\
AlgorithmInfo* classname::info() const \
{ \
static volatile bool initialized = false; \
\
if( !initialized ) \
{ \
initialized = true; \
classname obj; \
memberinit; \
} \
return &classname##_info(); \
}
#endif
/* maximal size of vector to run matrix operations on it inline (i.e. w/o ipp calls) */
+32 -12
View File
@@ -322,7 +322,10 @@ inline Mat Mat::diag(const Mat& d)
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();
d.copyTo(md);
if( d.cols == 1 )
d.copyTo(md);
else
transpose(d, md);
return m;
}
@@ -1118,6 +1121,9 @@ template<typename _Tp> inline _InputArray::_InputArray(const vector<_Tp>& vec)
template<typename _Tp> inline _InputArray::_InputArray(const vector<vector<_Tp> >& vec)
: flags(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec) {}
template<typename _Tp> inline _InputArray::_InputArray(const vector<Mat_<_Tp> >& vec)
: flags(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type), obj((void*)&vec) {}
template<typename _Tp, int m, int n> inline _InputArray::_InputArray(const Matx<_Tp, m, n>& mtx)
: flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m) {}
@@ -1130,18 +1136,32 @@ inline _InputArray::_InputArray(const Scalar& s)
template<typename _Tp> inline _InputArray::_InputArray(const Mat_<_Tp>& m)
: flags(FIXED_TYPE + MAT + DataType<_Tp>::type), obj((void*)&m) {}
template<typename _Tp> inline _OutputArray::_OutputArray(vector<_Tp>& vec) : _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(vector<vector<_Tp> >& vec) : _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(Mat_<_Tp>& m) : _InputArray(m) {}
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) : _InputArray(mtx) {}
template<typename _Tp> inline _OutputArray::_OutputArray(_Tp* vec, int n) : _InputArray(vec, n) {}
template<typename _Tp> inline _OutputArray::_OutputArray(vector<_Tp>& vec)
: _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(vector<vector<_Tp> >& vec)
: _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(vector<Mat_<_Tp> >& vec)
: _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(Mat_<_Tp>& m)
: _InputArray(m) {}
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx)
: _InputArray(mtx) {}
template<typename _Tp> inline _OutputArray::_OutputArray(_Tp* vec, int n)
: _InputArray(vec, n) {}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<_Tp>& vec) : _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<vector<_Tp> >& vec) : _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const Mat_<_Tp>& m) : _InputArray(m) {flags |= FIXED_SIZE;}
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) : _InputArray(mtx) {}
template<typename _Tp> inline _OutputArray::_OutputArray(const _Tp* vec, int n) : _InputArray(vec, n) {}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<_Tp>& vec)
: _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<vector<_Tp> >& vec)
: _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<Mat_<_Tp> >& vec)
: _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const Mat_<_Tp>& m)
: _InputArray(m) {flags |= FIXED_SIZE;}
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx)
: _InputArray(mtx) {}
template<typename _Tp> inline _OutputArray::_OutputArray(const _Tp* vec, int n)
: _InputArray(vec, n) {}
//////////////////////////////////// Matrix Expressions /////////////////////////////////////////
+6 -1
View File
@@ -1130,7 +1130,7 @@ CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z )
/******************************** CvSize's & CvBox **************************************/
typedef struct
typedef struct CvSize
{
int width;
int height;
@@ -1740,6 +1740,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
@@ -49,7 +49,7 @@
#define CV_MAJOR_VERSION 2
#define CV_MINOR_VERSION 4
#define CV_SUBMINOR_VERSION 0
#define CV_SUBMINOR_VERSION 1
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
+29
View File
@@ -0,0 +1,29 @@
#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
#define TYPICAL_MAT_TYPES_ADWEIGHTED CV_8UC1, CV_8UC4, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32SC4
#define TYPICAL_MATS_ADWEIGHTED testing::Combine(testing::Values(szVGA, sz720p, sz1080p), testing::Values(TYPICAL_MAT_TYPES_ADWEIGHTED))
PERF_TEST_P(Size_MatType, addWeighted, TYPICAL_MATS_ADWEIGHTED)
{
Size size = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src1(size, type);
Mat src2(size, type);
double alpha = 3.75;
double beta = -0.125;
double gamma = 100.0;
Mat dst(size, type);
declare.in(src1, src2, dst, WARMUP_RNG).out(dst);
TEST_CYCLE() cv::addWeighted( src1, alpha, src2, beta, gamma, dst, dst.type() );
SANITY_CHECK(dst);
}
+1 -1
View File
@@ -32,5 +32,5 @@ PERF_TEST_P( Size_DepthSrc_DepthDst_Channels_alpha, convertTo,
TEST_CYCLE() src.convertTo(dst, depthDst, alpha);
SANITY_CHECK(dst, 1e-12);
SANITY_CHECK(dst, alpha == 1.0 ? 1e-12 : 1e-7);
}
+26
View File
@@ -0,0 +1,26 @@
#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
#define TYPICAL_MAT_TYPES_INRANGE CV_8UC1, CV_8UC4, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32FC1, CV_32FC4
#define TYPICAL_MATS_INRANGE testing::Combine(testing::Values(szVGA, sz720p, sz1080p), testing::Values(TYPICAL_MAT_TYPES_INRANGE))
PERF_TEST_P(Size_MatType, inRange, TYPICAL_MATS_INRANGE)
{
Size size = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src1(size, type);
Mat src2(size, type);
Mat src3(size, type);
Mat dst(size, type);
declare.in(src1, src2, src3, WARMUP_RNG).out(dst);
TEST_CYCLE() inRange( src1, src2, src3, dst );
SANITY_CHECK(dst);
}
+4 -4
View File
@@ -1984,8 +1984,8 @@ static void addWeighted64f( const double* src1, size_t step1, const double* src2
static BinaryFunc addWeightedTab[] =
{
(BinaryFunc)addWeighted8u, (BinaryFunc)addWeighted8s, (BinaryFunc)addWeighted16u,
(BinaryFunc)addWeighted16s, (BinaryFunc)addWeighted32s, (BinaryFunc)addWeighted32f,
(BinaryFunc)GET_OPTIMIZED(addWeighted8u), (BinaryFunc)GET_OPTIMIZED(addWeighted8s), (BinaryFunc)GET_OPTIMIZED(addWeighted16u),
(BinaryFunc)GET_OPTIMIZED(addWeighted16s), (BinaryFunc)GET_OPTIMIZED(addWeighted32s), (BinaryFunc)addWeighted32f,
(BinaryFunc)addWeighted64f, 0
};
@@ -2504,8 +2504,8 @@ typedef void (*InRangeFunc)( const uchar* src1, size_t step1, const uchar* src2,
static InRangeFunc inRangeTab[] =
{
(InRangeFunc)inRange8u, (InRangeFunc)inRange8s, (InRangeFunc)inRange16u,
(InRangeFunc)inRange16s, (InRangeFunc)inRange32s, (InRangeFunc)inRange32f,
(InRangeFunc)GET_OPTIMIZED(inRange8u), (InRangeFunc)GET_OPTIMIZED(inRange8s), (InRangeFunc)GET_OPTIMIZED(inRange16u),
(InRangeFunc)GET_OPTIMIZED(inRange16s), (InRangeFunc)GET_OPTIMIZED(inRange32s), (InRangeFunc)GET_OPTIMIZED(inRange32f),
(InRangeFunc)inRange64f, 0
};
+52 -52
View File
@@ -619,28 +619,28 @@ cvtScale_<short, short, float>( const short* src, size_t sstep,
sstep /= sizeof(src[0]);
dstep /= sizeof(dst[0]);
for( ; size.height--; src += sstep, dst += dstep )
for( ; size.height--; src += sstep, dst += dstep )
{
int x = 0;
#if CV_SSE2
if(USE_SSE2)
#if CV_SSE2
if(USE_SSE2)
{
__m128 scale128 = _mm_set1_ps (scale);
__m128 shift128 = _mm_set1_ps (shift);
for(; x <= size.width - 8; x += 8 )
{
__m128i r0 = _mm_loadl_epi64((const __m128i*)(src + x));
for(; x <= size.width - 8; x += 8 )
{
__m128i r0 = _mm_loadl_epi64((const __m128i*)(src + x));
__m128i r1 = _mm_loadl_epi64((const __m128i*)(src + x + 4));
__m128 rf0 =_mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(r0, r0), 16));
__m128 rf0 =_mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(r0, r0), 16));
__m128 rf1 =_mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(r1, r1), 16));
rf0 = _mm_add_ps(_mm_mul_ps(rf0, scale128), shift128);
rf1 = _mm_add_ps(_mm_mul_ps(rf1, scale128), shift128);
r0 = _mm_cvtps_epi32(rf0);
r1 = _mm_cvtps_epi32(rf1);
r0 = _mm_packs_epi32(r0, r1);
_mm_storeu_si128((__m128i*)(dst + x), r0);
}
}
r0 = _mm_cvtps_epi32(rf0);
r1 = _mm_cvtps_epi32(rf1);
r0 = _mm_packs_epi32(r0, r1);
_mm_storeu_si128((__m128i*)(dst + x), r0);
}
}
#endif
for(; x < size.width; x++ )
@@ -659,17 +659,17 @@ cvt_( const T* src, size_t sstep,
for( ; size.height--; src += sstep, dst += dstep )
{
int x = 0;
#if CV_ENABLE_UNROLLED
for( ; x <= size.width - 4; x += 4 )
{
DT t0, t1;
t0 = saturate_cast<DT>(src[x]);
t1 = saturate_cast<DT>(src[x+1]);
dst[x] = t0; dst[x+1] = t1;
t0 = saturate_cast<DT>(src[x+2]);
t1 = saturate_cast<DT>(src[x+3]);
dst[x+2] = t0; dst[x+3] = t1;
}
#if CV_ENABLE_UNROLLED
for( ; x <= size.width - 4; x += 4 )
{
DT t0, t1;
t0 = saturate_cast<DT>(src[x]);
t1 = saturate_cast<DT>(src[x+1]);
dst[x] = t0; dst[x+1] = t1;
t0 = saturate_cast<DT>(src[x+2]);
t1 = saturate_cast<DT>(src[x+3]);
dst[x+2] = t0; dst[x+3] = t1;
}
#endif
for( ; x < size.width; x++ )
dst[x] = saturate_cast<DT>(src[x]);
@@ -687,20 +687,20 @@ cvt_<float, short>( const float* src, size_t sstep,
for( ; size.height--; src += sstep, dst += dstep )
{
int x = 0;
#if CV_SSE2
if(USE_SSE2){
for( ; x <= size.width - 8; x += 8 )
{
__m128 src128 = _mm_loadu_ps (src + x);
__m128i src_int128 = _mm_cvtps_epi32 (src128);
src128 = _mm_loadu_ps (src + x + 4);
__m128i src1_int128 = _mm_cvtps_epi32 (src128);
src1_int128 = _mm_packs_epi32(src_int128, src1_int128);
_mm_storeu_si128((__m128i*)(dst + x),src1_int128);
}
}
#if CV_SSE2
if(USE_SSE2){
for( ; x <= size.width - 8; x += 8 )
{
__m128 src128 = _mm_loadu_ps (src + x);
__m128i src_int128 = _mm_cvtps_epi32 (src128);
src128 = _mm_loadu_ps (src + x + 4);
__m128i src1_int128 = _mm_cvtps_epi32 (src128);
src1_int128 = _mm_packs_epi32(src_int128, src1_int128);
_mm_storeu_si128((__m128i*)(dst + x),src1_int128);
}
}
#endif
for( ; x < size.width; x++ )
dst[x] = saturate_cast<short>(src[x]);
@@ -876,33 +876,33 @@ static BinaryFunc cvtScaleAbsTab[] =
static BinaryFunc cvtScaleTab[][8] =
{
{
(BinaryFunc)cvtScale8u, (BinaryFunc)cvtScale8s8u, (BinaryFunc)cvtScale16u8u,
(BinaryFunc)cvtScale16s8u, (BinaryFunc)cvtScale32s8u, (BinaryFunc)cvtScale32f8u,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u), (BinaryFunc)GET_OPTIMIZED(cvtScale8s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale16u8u),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale32s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale32f8u),
(BinaryFunc)cvtScale64f8u, 0
},
{
(BinaryFunc)cvtScale8u8s, (BinaryFunc)cvtScale8s, (BinaryFunc)cvtScale16u8s,
(BinaryFunc)cvtScale16s8s, (BinaryFunc)cvtScale32s8s, (BinaryFunc)cvtScale32f8s,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u8s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u8s),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s8s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s8s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f8s),
(BinaryFunc)cvtScale64f8s, 0
},
{
(BinaryFunc)cvtScale8u16u, (BinaryFunc)cvtScale8s16u, (BinaryFunc)cvtScale16u,
(BinaryFunc)cvtScale16s16u, (BinaryFunc)cvtScale32s16u, (BinaryFunc)cvtScale32f16u,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u16u), (BinaryFunc)GET_OPTIMIZED(cvtScale8s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale16u),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale32s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale32f16u),
(BinaryFunc)cvtScale64f16u, 0
},
{
(BinaryFunc)cvtScale8u16s, (BinaryFunc)cvtScale8s16s, (BinaryFunc)cvtScale16u16s,
(BinaryFunc)cvtScale16s, (BinaryFunc)cvtScale32s16s, (BinaryFunc)cvtScale32f16s,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u16s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s16s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u16s),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s16s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f16s),
(BinaryFunc)cvtScale64f16s, 0
},
{
(BinaryFunc)cvtScale8u32s, (BinaryFunc)cvtScale8s32s, (BinaryFunc)cvtScale16u32s,
(BinaryFunc)cvtScale16s32s, (BinaryFunc)cvtScale32s, (BinaryFunc)cvtScale32f32s,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u32s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s32s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u32s),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s32s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f32s),
(BinaryFunc)cvtScale64f32s, 0
},
{
(BinaryFunc)cvtScale8u32f, (BinaryFunc)cvtScale8s32f, (BinaryFunc)cvtScale16u32f,
(BinaryFunc)cvtScale16s32f, (BinaryFunc)cvtScale32s32f, (BinaryFunc)cvtScale32f,
(BinaryFunc)GET_OPTIMIZED(cvtScale8u32f), (BinaryFunc)GET_OPTIMIZED(cvtScale8s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale16u32f),
(BinaryFunc)GET_OPTIMIZED(cvtScale16s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale32s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale32f),
(BinaryFunc)cvtScale64f32f, 0
},
{
@@ -918,7 +918,7 @@ static BinaryFunc cvtScaleTab[][8] =
static BinaryFunc cvtTab[][8] =
{
{
(BinaryFunc)cvt8u, (BinaryFunc)GET_OPTIMIZED(cvt8s8u), (BinaryFunc)GET_OPTIMIZED(cvt16u8u),
(BinaryFunc)(cvt8u), (BinaryFunc)GET_OPTIMIZED(cvt8s8u), (BinaryFunc)GET_OPTIMIZED(cvt16u8u),
(BinaryFunc)GET_OPTIMIZED(cvt16s8u), (BinaryFunc)GET_OPTIMIZED(cvt32s8u), (BinaryFunc)GET_OPTIMIZED(cvt32f8u),
(BinaryFunc)GET_OPTIMIZED(cvt64f8u), 0
},
@@ -950,7 +950,7 @@ static BinaryFunc cvtTab[][8] =
{
(BinaryFunc)GET_OPTIMIZED(cvt8u64f), (BinaryFunc)GET_OPTIMIZED(cvt8s64f), (BinaryFunc)GET_OPTIMIZED(cvt16u64f),
(BinaryFunc)GET_OPTIMIZED(cvt16s64f), (BinaryFunc)GET_OPTIMIZED(cvt32s64f), (BinaryFunc)GET_OPTIMIZED(cvt32f64f),
(BinaryFunc)cvt64s, 0
(BinaryFunc)(cvt64s), 0
},
{
0, 0, 0, 0, 0, 0, 0, 0
+49 -49
View File
@@ -140,11 +140,11 @@ bool clipLine( Rect img_rect, Point& pt1, Point& pt2 )
pt1 -= tl; pt2 -= tl;
bool inside = clipLine(img_rect.size(), pt1, pt2);
pt1 += tl; pt2 += tl;
return inside;
}
/*
/*
Initializes line iterator.
Returns number of points on the line or negative number if error.
*/
@@ -195,7 +195,7 @@ LineIterator::LineIterator(const Mat& img, Point pt1, Point pt2,
step = (step ^ s) - s;
s = dy > dx ? -1 : 0;
/* conditional swaps */
dx ^= dy & s;
dy ^= dx & s;
@@ -208,7 +208,7 @@ LineIterator::LineIterator(const Mat& img, Point pt1, Point pt2,
if( connectivity == 8 )
{
assert( dx >= 0 && dy >= 0 );
err = dx - (dy + dy);
plusDelta = dx + dx;
minusDelta = -(dy + dy);
@@ -219,7 +219,7 @@ LineIterator::LineIterator(const Mat& img, Point pt1, Point pt2,
else /* connectivity == 4 */
{
assert( dx >= 0 && dy >= 0 );
err = 0;
plusDelta = (dx + dx) + (dy + dy);
minusDelta = -(dy + dy);
@@ -227,7 +227,7 @@ LineIterator::LineIterator(const Mat& img, Point pt1, Point pt2,
minusStep = bt_pix;
count = dx + dy + 1;
}
this->ptr0 = img.data;
this->step = (int)img.step;
this->elemSize = bt_pix0;
@@ -621,10 +621,10 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
tptr[1] = (uchar)cg; \
tptr[2] = (uchar)cr; \
}
ICV_PUT_POINT((pt2.x + (XY_ONE >> 1)) >> XY_SHIFT,
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
if( ax > ay )
{
pt1.x >>= XY_SHIFT;
@@ -640,7 +640,7 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
else
{
pt1.y >>= XY_SHIFT;
while( ecount >= 0 )
{
ICV_PUT_POINT(pt1.x >> XY_SHIFT, pt1.y);
@@ -664,8 +664,8 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
}
ICV_PUT_POINT((pt2.x + (XY_ONE >> 1)) >> XY_SHIFT,
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
if( ax > ay )
{
pt1.x >>= XY_SHIFT;
@@ -681,7 +681,7 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
else
{
pt1.y >>= XY_SHIFT;
while( ecount >= 0 )
{
ICV_PUT_POINT(pt1.x >> XY_SHIFT, pt1.y);
@@ -690,7 +690,7 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
ecount--;
}
}
#undef ICV_PUT_POINT
}
else
@@ -706,12 +706,12 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
}
ICV_PUT_POINT((pt2.x + (XY_ONE >> 1)) >> XY_SHIFT,
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
(pt2.y + (XY_ONE >> 1)) >> XY_SHIFT);
if( ax > ay )
{
pt1.x >>= XY_SHIFT;
while( ecount >= 0 )
{
ICV_PUT_POINT(pt1.x, pt1.y >> XY_SHIFT);
@@ -723,7 +723,7 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
else
{
pt1.y >>= XY_SHIFT;
while( ecount >= 0 )
{
ICV_PUT_POINT(pt1.x >> XY_SHIFT, pt1.y);
@@ -732,7 +732,7 @@ Line2( Mat& img, Point pt1, Point pt2, const void* color )
ecount--;
}
}
#undef ICV_PUT_POINT
}
}
@@ -830,7 +830,7 @@ sincos( int angle, float& cosval, float& sinval )
cosval = SinTable[450 - angle];
}
/*
/*
constructs polygon that represents elliptic arc.
*/
void ellipse2Poly( Point center, Size axes, int angle,
@@ -880,7 +880,7 @@ void ellipse2Poly( Point center, Size axes, int angle,
angle = arc_end;
if( angle < 0 )
angle += 360;
x = size_a * SinTable[450-angle];
y = size_b * SinTable[angle];
Point pt;
@@ -922,7 +922,7 @@ EllipseEx( Mat& img, Point center, Size axes,
/****************************************************************************************\
* Polygons filling *
* Polygons filling *
\****************************************************************************************/
/* helper macros: filling horizontal row */
@@ -1010,7 +1010,7 @@ FillConvexPoly( Mat& img, const Point* v, int npts, const void* color, int line_
LineAA( img, p0, p, color );
p0 = p;
}
xmin = (xmin + delta) >> shift;
xmax = (xmax + delta) >> shift;
ymin = (ymin + delta) >> shift;
@@ -1118,7 +1118,7 @@ CollectPolyEdges( Mat& img, const Point* v, int count, vector<PolyEdge>& edges,
{
Point t0, t1;
PolyEdge edge;
pt1 = v[i];
pt1.x = (pt1.x + offset.x) << (XY_SHIFT - shift);
pt1.y = (pt1.y + delta) >> shift;
@@ -1337,7 +1337,7 @@ Circle( Mat& img, Point center, int radius, const void* color, int fill )
{
uchar *tptr0 = ptr + y11 * step;
uchar *tptr1 = ptr + y12 * step;
if( !fill )
{
ICV_PUT_POINT( tptr0, x11 );
@@ -1374,7 +1374,7 @@ Circle( Mat& img, Point center, int radius, const void* color, int fill )
x11 = std::max( x11, 0 );
x12 = MIN( x12, size.width - 1 );
}
if( (unsigned)y11 < (unsigned)size.height )
{
uchar *tptr = ptr + y11 * step;
@@ -1523,7 +1523,7 @@ ThickLine( Mat& img, Point p0, Point p1, const void* color,
Point center;
center.x = (p0.x + (XY_ONE>>1)) >> XY_SHIFT;
center.y = (p0.y + (XY_ONE>>1)) >> XY_SHIFT;
Circle( img, center, (thickness + (XY_ONE>>1)) >> XY_SHIFT, color, 1 );
Circle( img, center, (thickness + (XY_ONE>>1)) >> XY_SHIFT, color, 1 );
}
else
{
@@ -1544,7 +1544,7 @@ PolyLine( Mat& img, const Point* v, int count, bool is_closed,
{
if( !v || count <= 0 )
return;
int i = is_closed ? count - 1 : 0;
int flags = 2 + !is_closed;
Point p0;
@@ -1575,7 +1575,7 @@ void line( Mat& img, Point pt1, Point pt2, const Scalar& color,
double buf[4];
scalarToRawData( color, buf, img.type(), 0 );
ThickLine( img, pt1, pt2, buf, thickness, line_type, 3, shift );
ThickLine( img, pt1, pt2, buf, thickness, line_type, 3, shift );
}
void rectangle( Mat& img, Point pt1, Point pt2,
@@ -1606,7 +1606,7 @@ void rectangle( Mat& img, Point pt1, Point pt2,
FillConvexPoly( img, pt, 4, buf, lineType, shift );
}
void rectangle( Mat& img, Rect rec,
const Scalar& color, int thickness,
int lineType, int shift )
@@ -1617,7 +1617,7 @@ void rectangle( Mat& img, Rect rec,
color, thickness, lineType, shift );
}
void circle( Mat& img, Point center, int radius,
const Scalar& color, int thickness, int line_type, int shift )
{
@@ -1667,25 +1667,25 @@ void ellipse( Mat& img, Point center, Size axes,
EllipseEx( img, center, axes, _angle, _start_angle,
_end_angle, buf, thickness, line_type );
}
void ellipse(Mat& img, const RotatedRect& box, const Scalar& color,
int thickness, int lineType)
{
if( lineType == CV_AA && img.depth() != CV_8U )
lineType = 8;
CV_Assert( box.size.width >= 0 && box.size.height >= 0 &&
thickness <= 255 );
double buf[4];
scalarToRawData(color, buf, img.type(), 0);
int _angle = cvRound(box.angle);
Point center(cvRound(box.center.x*(1 << XY_SHIFT)),
cvRound(box.center.y*(1 << XY_SHIFT)));
Size axes(cvRound(box.size.width*(1 << (XY_SHIFT - 1))),
cvRound(box.size.height*(1 << (XY_SHIFT - 1))));
EllipseEx( img, center, axes, _angle, 0, 360, buf, thickness, lineType );
EllipseEx( img, center, axes, _angle, 0, 360, buf, thickness, lineType );
}
void fillConvexPoly( Mat& img, const Point* pts, int npts,
@@ -1875,12 +1875,12 @@ static const int HersheyScriptComplex[] = {
2662, 2663, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2671, 2672, 2673, 2674, 2675, 2676,
2225, 2229, 2226, 2246 };
static const int* getFontData(int fontFace)
{
bool isItalic = (fontFace & FONT_ITALIC) != 0;
const int* ascii = 0;
switch( fontFace & 15 )
{
case FONT_HERSHEY_SIMPLEX:
@@ -1912,15 +1912,15 @@ static const int* getFontData(int fontFace)
}
return ascii;
}
void putText( Mat& img, const string& text, Point org,
int fontFace, double fontScale, Scalar color,
int thickness, int line_type, bool bottomLeftOrigin )
{
const int* ascii = getFontData(fontFace);
double buf[4];
scalarToRawData(color, buf, img.type(), 0);
@@ -1959,7 +1959,7 @@ void putText( Mat& img, const string& text, Point org,
if( *ptr == ' ' || !*ptr )
{
if( pts.size() > 1 )
PolyLine( img, &pts[0], (int)pts.size(), false, buf, thickness, line_type, XY_SHIFT );
PolyLine( img, &pts[0], (int)pts.size(), false, buf, thickness, line_type, XY_SHIFT );
if( !*ptr++ )
break;
pts.resize(0);
@@ -2030,7 +2030,7 @@ void cv::fillPoly(InputOutputArray _img, InputArrayOfArrays pts,
AutoBuffer<int> _npts(ncontours);
Point** ptsptr = _ptsptr;
int* npts = _npts;
for( i = 0; i < ncontours; i++ )
{
Mat p = pts.getMat(i);
@@ -2056,7 +2056,7 @@ void cv::polylines(InputOutputArray _img, InputArrayOfArrays pts,
AutoBuffer<int> _npts(ncontours);
Point** ptsptr = _ptsptr;
int* npts = _npts;
for( i = 0; i < ncontours; i++ )
{
Mat p = pts.getMat(manyContours ? i : -1);
@@ -2078,7 +2078,7 @@ static const int CodeDeltas[8][2] =
CV_IMPL void
cvDrawContours( void* _img, CvSeq* contour,
CvScalar _externalColor, CvScalar _holeColor,
CvScalar _externalColor, CvScalar _holeColor,
int maxLevel, int thickness,
int line_type, CvPoint _offset )
{
@@ -2104,7 +2104,7 @@ cvDrawContours( void* _img, CvSeq* contour,
maxLevel = MAX(maxLevel, INT_MIN+2);
maxLevel = MIN(maxLevel, INT_MAX-1);
if( maxLevel < 0 )
{
h_next = contour->h_next;
@@ -2148,7 +2148,7 @@ cvDrawContours( void* _img, CvSeq* contour,
pts.push_back(pt);
prev_pt = pt;
}
pt.x += CodeDeltas[(int)code][0];
pt.y += CodeDeltas[(int)code][1];
}
@@ -2166,7 +2166,7 @@ cvDrawContours( void* _img, CvSeq* contour,
CV_Assert( elem_type == CV_32SC2 );
cv::Point pt1, pt2;
int shift = 0;
count -= !CV_IS_SEQ_CLOSED(contour);
CV_READ_SEQ_ELEM( pt1, reader );
pt1 += offset;
@@ -2218,7 +2218,7 @@ CV_IMPL CvScalar
cvColorToScalar( double packed_color, int type )
{
CvScalar scalar;
if( CV_MAT_DEPTH( type ) == CV_8U )
{
int icolor = cvRound( packed_color );
+15 -2
View File
@@ -320,7 +320,8 @@ namespace
template <class T> void getCudaAttribute(T *attribute, CUdevice_attribute device_attribute, int device)
{
*attribute = T();
CUresult error = CUDA_SUCCESS;// = cuDeviceGetAttribute( attribute, device_attribute, device ); why link erros under ubuntu??
//CUresult error = CUDA_SUCCESS;// = cuDeviceGetAttribute( attribute, device_attribute, device ); why link erros under ubuntu??
CUresult error = cuDeviceGetAttribute( attribute, device_attribute, device );
if( CUDA_SUCCESS == error )
return;
@@ -336,7 +337,7 @@ namespace
int Cores;
} SMtoCores;
SMtoCores gpuArchCoresPerSM[] = { { 0x10, 8 }, { 0x11, 8 }, { 0x12, 8 }, { 0x13, 8 }, { 0x20, 32 }, { 0x21, 48 }, { -1, -1 } };
SMtoCores gpuArchCoresPerSM[] = { { 0x10, 8 }, { 0x11, 8 }, { 0x12, 8 }, { 0x13, 8 }, { 0x20, 32 }, { 0x21, 48 }, {0x30, 192}, { -1, -1 } };
int index = 0;
while (gpuArchCoresPerSM[index].SM != -1)
@@ -1036,6 +1037,11 @@ namespace
}
};
template <typename T> static inline bool isAligned(const T* ptr, size_t size)
{
return reinterpret_cast<size_t>(ptr) % size == 0;
}
//////////////////////////////////////////////////////////////////////////
// CudaFuncTable
@@ -1164,6 +1170,13 @@ namespace
CV_Error(CV_StsUnsupportedFormat, "The device doesn't support double");
}
bool aligned = isAligned(src.data, 16) && isAligned(dst.data, 16);
if (!aligned)
{
cv::gpu::convertTo(src, dst);
return;
}
const func_t func = funcs[src.depth()][dst.depth()][src.channels() - 1];
CV_DbgAssert(func != 0);
+4 -1
View File
@@ -947,6 +947,9 @@ double cv::invert( InputArray _src, OutputArray _dst, int method )
bool result = false;
Mat src = _src.getMat();
int type = src.type();
CV_Assert(type == CV_32F || type == CV_64F);
size_t esz = CV_ELEM_SIZE(type);
int m = src.rows, n = src.cols;
@@ -969,7 +972,7 @@ double cv::invert( InputArray _src, OutputArray _dst, int method )
((double*)w.data)[n-1]/((double*)w.data)[0] : 0);
}
CV_Assert( m == n && (type == CV_32F || type == CV_64F));
CV_Assert( m == n );
if( method == DECOMP_EIG )
{
+3 -2
View File
@@ -2768,8 +2768,9 @@ typedef double (*DotProdFunc)(const uchar* src1, const uchar* src2, int len);
static DotProdFunc dotProdTab[] =
{
(DotProdFunc)GET_OPTIMIZED(dotProd_8u), (DotProdFunc)dotProd_8s, (DotProdFunc)dotProd_16u,
(DotProdFunc)dotProd_16s, (DotProdFunc)dotProd_32s, (DotProdFunc)GET_OPTIMIZED(dotProd_32f),
(DotProdFunc)GET_OPTIMIZED(dotProd_8u), (DotProdFunc)GET_OPTIMIZED(dotProd_8s),
(DotProdFunc)dotProd_16u, (DotProdFunc)dotProd_16s,
(DotProdFunc)dotProd_32s, (DotProdFunc)GET_OPTIMIZED(dotProd_32f),
(DotProdFunc)dotProd_64f, 0
};
+23 -4
View File
@@ -1352,7 +1352,7 @@ void _OutputArray::create(int dims, const int* size, int type, int i, bool allow
if(CV_MAT_CN(type) == m.channels() && ((1 << CV_MAT_TYPE(flags)) & fixedDepthMask) != 0 )
type = m.type();
else
CV_Assert(!fixedType() || (CV_MAT_CN(type) == m.channels() && ((1 << CV_MAT_TYPE(flags)) & fixedDepthMask) != 0));
CV_Assert(CV_MAT_TYPE(type) == m.type());
}
if(fixedSize())
{
@@ -1470,10 +1470,21 @@ void _OutputArray::create(int dims, const int* size, int type, int i, bool allow
if( i < 0 )
{
CV_Assert( dims == 2 && (size[0] == 1 || size[1] == 1 || size[0]*size[1] == 0) );
size_t len = size[0]*size[1] > 0 ? size[0] + size[1] - 1 : 0;
size_t len = size[0]*size[1] > 0 ? size[0] + size[1] - 1 : 0, len0 = v.size();
CV_Assert(!fixedSize() || len == v.size());
CV_Assert(!fixedSize() || len == len0);
v.resize(len);
if( fixedType() )
{
int type = CV_MAT_TYPE(flags);
for( size_t j = len0; j < len; j++ )
{
if( v[i].type() == type )
continue;
CV_Assert( v[i].empty() );
v[i].flags = (v[i].flags & ~CV_MAT_TYPE_MASK) | type;
}
}
return;
}
@@ -2886,8 +2897,16 @@ cvKMeans2( const CvArr* _samples, int cluster_count, CvArr* _labels,
namespace cv
{
Mat Mat::reshape(int, int, const int*) const
Mat Mat::reshape(int _cn, int _newndims, const int* _newsz) const
{
if(_newndims == dims)
{
if(_newsz == 0)
return reshape(_cn);
if(_newndims == 2)
return reshape(_cn, _newsz[0]);
}
CV_Error(CV_StsNotImplemented, "");
// TBD
return Mat();
+1 -1
View File
@@ -1269,7 +1269,7 @@ void cv::GlFont::draw(const char* str, int len) const
glPushAttrib(GL_LIST_BIT);
glListBase(base_);
glCallLists(len, GL_UNSIGNED_BYTE, str);
glCallLists(static_cast<GLsizei>(len), GL_UNSIGNED_BYTE, str);
glPopAttrib();
+197 -89
View File
@@ -41,7 +41,10 @@
//M*/
#include "precomp.hpp"
#include <ctype.h>
#include <deque>
#include <iterator>
#include <wchar.h>
#include <zlib.h>
@@ -208,7 +211,7 @@ typedef void (*CvStartNextStream)( struct CvFileStorage* fs );
typedef struct CvFileStorage
{
int flags;
int is_xml;
int fmt;
int write_mode;
int is_first;
CvMemStorage* memstorage;
@@ -240,52 +243,86 @@ typedef struct CvFileStorage
CvWriteString write_string;
CvWriteComment write_comment;
CvStartNextStream start_next_stream;
//CvParse parse;
const char* strbuf;
size_t strbufsize, strbufpos;
std::deque<char>* outbuf;
bool is_opened;
}
CvFileStorage;
static void icvPuts( CvFileStorage* fs, const char* str )
{
CV_Assert( fs->file || fs->gzfile );
if( fs->file )
if( fs->outbuf )
std::copy(str, str + strlen(str), std::back_inserter(*fs->outbuf));
else if( fs->file )
fputs( str, fs->file );
else
else if( fs->gzfile )
gzputs( fs->gzfile, str );
else
CV_Error( CV_StsError, "The storage is not opened" );
}
static char* icvGets( CvFileStorage* fs, char* str, int maxCount )
{
CV_Assert( fs->file || fs->gzfile );
if( fs->strbuf )
{
size_t i = fs->strbufpos, len = fs->strbufsize;
int j = 0;
const char* instr = fs->strbuf;
while( i < len && j < maxCount-1 )
{
char c = instr[i++];
if( c == '\0' )
break;
str[j++] = c;
if( c == '\n' )
break;
}
str[j++] = '\0';
fs->strbufpos = i;
return j > 1 ? str : 0;
}
if( fs->file )
return fgets( str, maxCount, fs->file );
return gzgets( fs->gzfile, str, maxCount );
if( fs->gzfile )
return gzgets( fs->gzfile, str, maxCount );
CV_Error( CV_StsError, "The storage is not opened" );
return 0;
}
static int icvEof( CvFileStorage* fs )
{
CV_Assert( fs->file || fs->gzfile );
if( fs->strbuf )
return fs->strbufpos >= fs->strbufsize;
if( fs->file )
return feof(fs->file);
return gzeof(fs->gzfile);
if( fs->gzfile )
return gzeof(fs->gzfile);
return false;
}
static void icvClose( CvFileStorage* fs )
static void icvCloseFile( CvFileStorage* fs )
{
if( fs->file )
fclose( fs->file );
if( fs->gzfile )
else if( fs->gzfile )
gzclose( fs->gzfile );
fs->file = 0;
fs->gzfile = 0;
fs->strbuf = 0;
fs->strbufpos = 0;
fs->is_opened = false;
}
static void icvRewind( CvFileStorage* fs )
{
CV_Assert( fs->file || fs->gzfile );
if( fs->file )
rewind(fs->file);
else
else if( fs->gzfile )
gzrewind(fs->gzfile);
fs->strbufpos = 0;
}
#define CV_YML_INDENT 3
@@ -373,7 +410,7 @@ icvFSCreateCollection( CvFileStorage* fs, int tag, CvFileNode* collection )
{
if( collection->tag != CV_NODE_NONE )
{
assert( fs->is_xml != 0 );
assert( fs->fmt == CV_STORAGE_FORMAT_XML );
CV_PARSE_ERROR( "Sequence element should not have name (use <_></_>)" );
}
@@ -477,19 +514,18 @@ icvFSFlush( CvFileStorage* fs )
}
/* closes file storage and deallocates buffers */
CV_IMPL void
cvReleaseFileStorage( CvFileStorage** p_fs )
static void
icvClose( CvFileStorage* fs, std::string* out )
{
if( !p_fs )
if( out )
out->clear();
if( !fs )
CV_Error( CV_StsNullPtr, "NULL double pointer to file storage" );
if( *p_fs )
if( fs->is_opened )
{
CvFileStorage* fs = *p_fs;
*p_fs = 0;
if( fs->write_mode && (fs->file || fs->gzfile) )
if( fs->write_mode && (fs->file || fs->gzfile || fs->outbuf) )
{
if( fs->write_stack )
{
@@ -497,19 +533,42 @@ cvReleaseFileStorage( CvFileStorage** p_fs )
cvEndWriteStruct(fs);
}
icvFSFlush(fs);
if( fs->is_xml )
if( fs->fmt == CV_STORAGE_FORMAT_XML )
icvPuts( fs, "</opencv_storage>\n" );
}
icvCloseFile(fs);
}
if( fs->outbuf && out )
{
out->resize(fs->outbuf->size());
std::copy(fs->outbuf->begin(), fs->outbuf->end(), out->begin());
}
}
//icvFSReleaseCollection( fs->roots ); // delete all the user types recursively
icvClose(fs);
cvReleaseMemStorage( &fs->strstorage );
/* closes file storage and deallocates buffers */
CV_IMPL void
cvReleaseFileStorage( CvFileStorage** p_fs )
{
if( !p_fs )
CV_Error( CV_StsNullPtr, "NULL double pointer to file storage" );
if( *p_fs )
{
CvFileStorage* fs = *p_fs;
*p_fs = 0;
icvClose(fs, 0);
cvReleaseMemStorage( &fs->strstorage );
cvFree( &fs->buffer_start );
cvReleaseMemStorage( &fs->memstorage );
if( fs->outbuf )
delete fs->outbuf;
memset( fs, 0, sizeof(*fs) );
cvFree( &fs );
}
@@ -2601,10 +2660,22 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
char* xml_buf = 0;
int default_block_size = 1 << 18;
bool append = (flags & 3) == CV_STORAGE_APPEND;
bool mem = (flags & CV_STORAGE_MEMORY) != 0;
bool write_mode = (flags & 3) != 0;
bool isGZ = false;
size_t fnamelen = 0;
if( !filename )
CV_Error( CV_StsNullPtr, "NULL filename" );
if( !filename || filename[0] == '\0' )
{
if( !write_mode )
CV_Error( CV_StsNullPtr, mem ? "NULL or empty filename" : "NULL or empty buffer" );
mem = true;
}
else
fnamelen = strlen(filename);
if( mem && append )
CV_Error( CV_StsBadFlag, "CV_STORAGE_APPEND and CV_STORAGE_MEMORY are not currently compatible" );
fs = (CvFileStorage*)cvAlloc( sizeof(*fs) );
memset( fs, 0, sizeof(*fs));
@@ -2612,44 +2683,43 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
fs->memstorage = cvCreateMemStorage( default_block_size );
fs->dststorage = dststorage ? dststorage : fs->memstorage;
int fnamelen = (int)strlen(filename);
if( !fnamelen )
CV_Error( CV_StsError, "Empty filename" );
fs->filename = (char*)cvMemStorageAlloc( fs->memstorage, fnamelen+1 );
strcpy( fs->filename, filename );
char* dot_pos = strrchr(fs->filename, '.');
char compression = '\0';
if( dot_pos && dot_pos[1] == 'g' && dot_pos[2] == 'z' &&
(dot_pos[3] == '\0' || (cv_isdigit(dot_pos[3]) && dot_pos[4] == '\0')) )
{
if( append )
CV_Error(CV_StsNotImplemented, "Appending data to compressed file is not implemented" );
isGZ = true;
compression = dot_pos[3];
if( compression )
dot_pos[3] = '\0', fnamelen--;
}
fs->flags = CV_FILE_STORAGE;
fs->write_mode = (flags & 3) != 0;
if( !isGZ )
fs->write_mode = write_mode;
if( !mem )
{
fs->file = fopen(fs->filename, !fs->write_mode ? "rt" : !append ? "wt" : "a+t" );
if( !fs->file )
goto _exit_;
}
else
{
char mode[] = { fs->write_mode ? 'w' : 'r', 'b', compression ? compression : '3', '\0' };
fs->gzfile = gzopen(fs->filename, mode);
if( !fs->gzfile )
goto _exit_;
}
fs->filename = (char*)cvMemStorageAlloc( fs->memstorage, fnamelen+1 );
strcpy( fs->filename, filename );
char* dot_pos = strrchr(fs->filename, '.');
char compression = '\0';
if( dot_pos && dot_pos[1] == 'g' && dot_pos[2] == 'z' &&
(dot_pos[3] == '\0' || (cv_isdigit(dot_pos[3]) && dot_pos[4] == '\0')) )
{
if( append )
CV_Error(CV_StsNotImplemented, "Appending data to compressed file is not implemented" );
isGZ = true;
compression = dot_pos[3];
if( compression )
dot_pos[3] = '\0', fnamelen--;
}
if( !isGZ )
{
fs->file = fopen(fs->filename, !fs->write_mode ? "rt" : !append ? "wt" : "a+t" );
if( !fs->file )
goto _exit_;
}
else
{
char mode[] = { fs->write_mode ? 'w' : 'r', 'b', compression ? compression : '3', '\0' };
fs->gzfile = gzopen(fs->filename, mode);
if( !fs->gzfile )
goto _exit_;
}
}
fs->roots = 0;
fs->struct_indent = 0;
fs->struct_flags = 0;
@@ -2657,27 +2727,38 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
if( fs->write_mode )
{
int fmt = flags & CV_STORAGE_FORMAT_MASK;
if( mem )
fs->outbuf = new std::deque<char>;
if( fmt == CV_STORAGE_FORMAT_AUTO && filename )
{
const char* dot_pos = filename + fnamelen - (isGZ ? 7 : 4);
fs->fmt = (dot_pos >= filename && (memcmp( dot_pos, ".xml", 4) == 0 ||
memcmp(dot_pos, ".XML", 4) == 0 || memcmp(dot_pos, ".Xml", 4) == 0)) ?
CV_STORAGE_FORMAT_XML : CV_STORAGE_FORMAT_YAML;
}
else
fs->fmt = fmt != CV_STORAGE_FORMAT_AUTO ? fmt : CV_STORAGE_FORMAT_XML;
// we use factor=6 for XML (the longest characters (' and ") are encoded with 6 bytes (&apos; and &quot;)
// and factor=4 for YAML ( as we use 4 bytes for non ASCII characters (e.g. \xAB))
int buf_size = CV_FS_MAX_LEN*(fs->is_xml ? 6 : 4) + 1024;
dot_pos = fs->filename + fnamelen - (isGZ ? 7 : 4);
fs->is_xml = dot_pos > fs->filename && (memcmp( dot_pos, ".xml", 4) == 0 ||
memcmp(dot_pos, ".XML", 4) == 0 || memcmp(dot_pos, ".Xml", 4) == 0);
int buf_size = CV_FS_MAX_LEN*(fs->fmt == CV_STORAGE_FORMAT_XML ? 6 : 4) + 1024;
if( append )
fseek( fs->file, 0, SEEK_END );
fs->write_stack = cvCreateSeq( 0, sizeof(CvSeq), fs->is_xml ?
fs->write_stack = cvCreateSeq( 0, sizeof(CvSeq), fs->fmt == CV_STORAGE_FORMAT_XML ?
sizeof(CvXMLStackRecord) : sizeof(int), fs->memstorage );
fs->is_first = 1;
fs->struct_indent = 0;
fs->struct_flags = CV_NODE_EMPTY;
fs->buffer_start = fs->buffer = (char*)cvAlloc( buf_size + 1024 );
fs->buffer_end = fs->buffer_start + buf_size;
if( fs->is_xml )
if( fs->fmt == CV_STORAGE_FORMAT_XML )
{
int file_size = fs->file ? (int)ftell( fs->file ) : 0;
size_t file_size = fs->file ? ftell( fs->file ) : (size_t)0;
fs->strstorage = cvCreateChildMemStorage( fs->memstorage );
if( !append || file_size == 0 )
{
@@ -2702,7 +2783,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
int xml_buf_size = 1 << 10;
char substr[] = "</opencv_storage>";
int last_occurence = -1;
xml_buf_size = MIN(xml_buf_size, file_size);
xml_buf_size = MIN(xml_buf_size, int(file_size));
fseek( fs->file, -xml_buf_size, SEEK_END );
xml_buf = (char*)cvAlloc( xml_buf_size+2 );
// find the last occurence of </opencv_storage>
@@ -2724,7 +2805,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
}
if( last_occurence < 0 )
CV_Error( CV_StsError, "Could not find </opencv_storage> in the end of file.\n" );
icvClose( fs );
icvCloseFile( fs );
fs->file = fopen( fs->filename, "r+t" );
fseek( fs->file, last_occurence, SEEK_SET );
// replace the last "</opencv_storage>" with " <!-- resumed -->", which has the same length
@@ -2757,18 +2838,30 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
}
else
{
int buf_size = 1 << 20;
if( mem )
{
fs->strbuf = filename;
fs->strbufsize = fnamelen;
}
size_t buf_size = 1 << 20;
const char* yaml_signature = "%YAML:";
char buf[16];
icvGets( fs, buf, sizeof(buf)-2 );
fs->is_xml = strncmp( buf, yaml_signature, strlen(yaml_signature) ) != 0;
fs->fmt = strncmp( buf, yaml_signature, strlen(yaml_signature) ) == 0 ?
CV_STORAGE_FORMAT_YAML : CV_STORAGE_FORMAT_XML;
if( !isGZ )
{
fseek( fs->file, 0, SEEK_END );
buf_size = ftell( fs->file );
buf_size = MIN( buf_size, (1 << 20) );
buf_size = MAX( buf_size, CV_FS_MAX_LEN*2 + 1024 );
if( !mem )
{
fseek( fs->file, 0, SEEK_END );
buf_size = ftell( fs->file );
}
else
buf_size = fs->strbufsize;
buf_size = MIN( buf_size, (size_t)(1 << 20) );
buf_size = MAX( buf_size, (size_t)(CV_FS_MAX_LEN*2 + 1024) );
}
icvRewind(fs);
@@ -2785,7 +2878,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
//mode = cvGetErrMode();
//cvSetErrMode( CV_ErrModeSilent );
if( fs->is_xml )
if( fs->fmt == CV_STORAGE_FORMAT_XML )
icvXMLParse( fs );
else
icvYMLParse( fs );
@@ -2795,16 +2888,21 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
cvFree( &fs->buffer_start );
fs->buffer = fs->buffer_end = 0;
}
fs->is_opened = true;
_exit_:
if( fs )
{
if( cvGetErrStatus() < 0 || (!fs->file && !fs->gzfile) )
if( cvGetErrStatus() < 0 || (!fs->file && !fs->gzfile && !fs->outbuf && !fs->strbuf) )
{
cvReleaseFileStorage( &fs );
}
else if( !fs->write_mode )
{
icvClose(fs);
icvCloseFile(fs);
// we close the file since it's not needed anymore. But icvCloseFile() resets is_opened,
// which may be misleading. Since we restore the value of is_opened.
fs->is_opened = true;
}
}
@@ -3057,7 +3155,7 @@ cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt )
return;
}
if( fs->is_xml )
if( fs->fmt == CV_STORAGE_FORMAT_XML )
{
int buf_len = (int)strlen(ptr);
icvXMLWriteScalar( fs, 0, ptr, buf_len );
@@ -5054,7 +5152,7 @@ bool FileStorage::open(const string& filename, int flags, const string& encoding
bool FileStorage::isOpened() const
{
return !fs.empty();
return !fs.empty() && fs.obj->is_opened;
}
void FileStorage::release()
@@ -5064,6 +5162,16 @@ void FileStorage::release()
state = UNDEFINED;
}
string FileStorage::releaseAndGetString()
{
string buf;
if( fs.obj && fs.obj->outbuf )
icvClose(fs.obj, &buf);
release();
return buf;
}
FileNode FileStorage::root(int streamidx) const
{
return isOpened() ? FileNode(fs, cvGetRootFileNode(fs, streamidx)) : FileNode();
+6 -6
View File
@@ -1224,16 +1224,16 @@ typedef int (*NormDiffFunc)(const uchar*, const uchar*, const uchar*, uchar*, in
static NormFunc normTab[3][8] =
{
{
(NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)normInf_8s, (NormFunc)normInf_16u, (NormFunc)normInf_16s,
(NormFunc)normInf_32s, (NormFunc)GET_OPTIMIZED(normInf_32f), (NormFunc)normInf_64f, 0
(NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)GET_OPTIMIZED(normInf_8s), (NormFunc)GET_OPTIMIZED(normInf_16u), (NormFunc)GET_OPTIMIZED(normInf_16s),
(NormFunc)GET_OPTIMIZED(normInf_32s), (NormFunc)GET_OPTIMIZED(normInf_32f), (NormFunc)normInf_64f, 0
},
{
(NormFunc)GET_OPTIMIZED(normL1_8u), (NormFunc)normL1_8s, (NormFunc)normL1_16u, (NormFunc)normL1_16s,
(NormFunc)normL1_32s, (NormFunc)GET_OPTIMIZED(normL1_32f), (NormFunc)normL1_64f, 0
(NormFunc)GET_OPTIMIZED(normL1_8u), (NormFunc)GET_OPTIMIZED(normL1_8s), (NormFunc)GET_OPTIMIZED(normL1_16u), (NormFunc)GET_OPTIMIZED(normL1_16s),
(NormFunc)GET_OPTIMIZED(normL1_32s), (NormFunc)GET_OPTIMIZED(normL1_32f), (NormFunc)normL1_64f, 0
},
{
(NormFunc)GET_OPTIMIZED(normL2_8u), (NormFunc)normL2_8s, (NormFunc)normL2_16u, (NormFunc)normL2_16s,
(NormFunc)normL2_32s, (NormFunc)GET_OPTIMIZED(normL2_32f), (NormFunc)normL2_64f, 0
(NormFunc)GET_OPTIMIZED(normL2_8u), (NormFunc)GET_OPTIMIZED(normL2_8s), (NormFunc)GET_OPTIMIZED(normL2_16u), (NormFunc)GET_OPTIMIZED(normL2_16s),
(NormFunc)GET_OPTIMIZED(normL2_32s), (NormFunc)GET_OPTIMIZED(normL2_32f), (NormFunc)normL2_64f, 0
}
};
+8
View File
@@ -1504,6 +1504,14 @@ protected:
d.convertTo(d1, depth);
CV_Assert( norm(c, d1, CV_C) <= DBL_EPSILON );
}
Mat_<uchar> tmpSrc(100,100);
tmpSrc = 124;
Mat_<uchar> tmpMask(100,100);
tmpMask = 255;
Mat_<uchar> tmpDst(100,100);
tmpDst = 2;
tmpSrc.copyTo(tmpDst,tmpMask);
}
catch(...)
{
+8 -7
View File
@@ -91,7 +91,7 @@ protected:
{-1000000, 1000000}, {-10, 10}, {-10, 10}};
RNG& rng = ts->get_rng();
RNG rng0;
test_case_count = 2;
test_case_count = 4;
int progress = 0;
MemStorage storage(cvCreateMemStorage(0));
@@ -102,9 +102,10 @@ protected:
cvClearMemStorage(storage);
bool mem = (idx % 4) >= 2;
string filename = tempfile(idx % 2 ? ".yml" : ".xml");
FileStorage fs(filename.c_str(), FileStorage::WRITE);
FileStorage fs(filename, FileStorage::WRITE + (mem ? FileStorage::MEMORY : 0));
int test_int = (int)cvtest::randInt(rng);
double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9);
@@ -179,11 +180,11 @@ protected:
fs.writeObj("test_graph",graph);
CvGraph* graph2 = (CvGraph*)cvClone(graph);
fs.release();
string content = fs.releaseAndGetString();
if(!fs.open(filename.c_str(), FileStorage::READ))
if(!fs.open(mem ? content : filename, FileStorage::READ + (mem ? FileStorage::MEMORY : 0)))
{
ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", filename.c_str() );
ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", !mem ? filename.c_str() : content.c_str());
ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
return;
}
@@ -310,7 +311,6 @@ protected:
int real_width = (int)tm["width"];
int real_height = (int)tm["height"];
int real_lbp_val = 0;
FileNodeIterator it;
it = tm_lbp.begin();
@@ -370,7 +370,8 @@ protected:
}
fs.release();
remove(filename.c_str());
if( !mem )
remove(filename.c_str());
}
}
};
+11
View File
@@ -861,3 +861,14 @@ TEST(Core_IOArray, submat_create)
EXPECT_THROW( OutputArray_create1(A.row(0)), cv::Exception );
EXPECT_THROW( OutputArray_create2(A.row(0)), cv::Exception );
}
TEST(Core_Mat, reshape_1942)
{
cv::Mat A = (cv::Mat_<float>(2,3) << 3.4884074, 1.4159607, 0.78737736, 2.3456569, -0.88010466, 0.3009364);
int cn = 0;
ASSERT_NO_THROW(
cv::Mat_<float> M = A.reshape(3);
cn = M.channels();
);
ASSERT_EQ(1, cn);
}
+42
View File
@@ -0,0 +1,42 @@
#include "test_precomp.hpp"
using namespace cv;
using namespace std;
TEST(Core_Drawing, _914)
{
const int rows = 256;
const int cols = 256;
Mat img(rows, cols, CV_8UC1, Scalar(255));
line(img, Point(0, 10), Point(255, 10), Scalar(0), 2, 4);
line(img, Point(-5, 20), Point(260, 20), Scalar(0), 2, 4);
line(img, Point(10, 0), Point(10, 255), Scalar(0), 2, 4);
double x0 = 0.0/pow(2.0, -2.0);
double x1 = 255.0/pow(2.0, -2.0);
double y = 30.5/pow(2.0, -2.0);
line(img, Point(int(x0), int(y)), Point(int(x1), int(y)), Scalar(0), 2, 4, 2);
int pixelsDrawn = rows*cols - countNonZero(img);
ASSERT_EQ( (3*rows + cols)*3 - 3*9, pixelsDrawn);
}
TEST(Core_OutputArraySreate, _1997)
{
struct local {
static void create(OutputArray arr, Size submatSize, int type)
{
int sizes[] = {submatSize.width, submatSize.height};
arr.create(sizeof(sizes)/sizeof(sizes[0]), sizes, type);
}
};
Mat mat(Size(512, 512), CV_8U);
Size submatSize = Size(256, 256);
ASSERT_NO_THROW(local::create( mat(Rect(Point(), submatSize)), submatSize, mat.type() ));
}
@@ -13,7 +13,7 @@ descriptor extractors inherit the
DescriptorExtractor
-------------------
.. ocv:class:: DescriptorExtractor
.. ocv:class:: DescriptorExtractor : public Algorithm
Abstract base class for computing descriptors for image keypoints. ::
@@ -65,25 +65,6 @@ Computes the descriptors for a set of keypoints detected in an image (first vari
:param descriptors: Computed descriptors. In the second variant of the method ``descriptors[i]`` are descriptors computed for a ``keypoints[i]`. Row ``j`` is the ``keypoints`` (or ``keypoints[i]``) is the descriptor for keypoint ``j``-th keypoint.
DescriptorExtractor::read
-----------------------------
Reads the object of a descriptor extractor from a file node.
.. ocv:function:: void DescriptorExtractor::read( const FileNode& fn )
:param fn: File node from which the detector is read.
DescriptorExtractor::write
------------------------------
Writes the object of a descriptor extractor to a file storage.
.. ocv:function:: void DescriptorExtractor::write( FileStorage& fs ) const
:param fs: File storage where the detector is written.
DescriptorExtractor::create
-------------------------------
@@ -107,7 +88,7 @@ for example: ``"OpponentSIFT"`` .
OpponentColorDescriptorExtractor
--------------------------------
.. ocv:class:: OpponentColorDescriptorExtractor
.. ocv:class:: OpponentColorDescriptorExtractor : public DescriptorExtractor
Class adapting a descriptor extractor to compute descriptors in the Opponent Color Space
(refer to Van de Sande et al., CGIV 2008 *Color Descriptors for Object Category Recognition*).
@@ -132,7 +113,7 @@ them into a single color descriptor. ::
BriefDescriptorExtractor
------------------------
.. ocv:class:: BriefDescriptorExtractor
.. ocv:class:: BriefDescriptorExtractor : public DescriptorExtractor
Class for computing BRIEF descriptors described in a paper of Calonder M., Lepetit V.,
Strecha C., Fua P. *BRIEF: Binary Robust Independent Elementary Features* ,
@@ -11,7 +11,7 @@ descriptor matchers inherit the
DMatch
------
.. ocv:class:: DMatch
.. ocv:struct:: DMatch
Class for matching keypoint descriptors: query descriptor index,
train descriptor index, train image index, and distance between descriptors. ::
@@ -40,7 +40,7 @@ train descriptor index, train image index, and distance between descriptors. ::
DescriptorMatcher
-----------------
.. ocv:class:: DescriptorMatcher
.. ocv:class:: DescriptorMatcher : public Algorithm
Abstract base class for matching keypoint descriptors. It has two groups
of match methods: for matching descriptors of an image with another image or
@@ -111,7 +111,7 @@ Returns a constant link to the train descriptor collection ``trainDescCollection
.. ocv:function:: const vector<Mat>& DescriptorMatcher::getTrainDescriptors() const
@@ -167,7 +167,7 @@ Finds the best match for each descriptor from a query set.
:param masks: Set of masks. Each ``masks[i]`` specifies permissible matches between the input query descriptors and stored train descriptors from the i-th image ``trainDescCollection[i]``.
In the first variant of this method, the train descriptors are passed as an input argument. In the second variant of the method, train descriptors collection that was set by ``DescriptorMatcher::add`` is used. Optional mask (or masks) can be passed to specify which query and training descriptors can be matched. Namely, ``queryDescriptors[i]`` can be matched with ``trainDescriptors[j]`` only if ``mask.at<uchar>(i,j)`` is non-zero.
In the first variant of this method, the train descriptors are passed as an input argument. In the second variant of the method, train descriptors collection that was set by ``DescriptorMatcher::add`` is used. Optional mask (or masks) can be passed to specify which query and training descriptors can be matched. Namely, ``queryDescriptors[i]`` can be matched with ``trainDescriptors[j]`` only if ``mask.at<uchar>(i,j)`` is non-zero.
@@ -193,7 +193,7 @@ Finds the k best matches for each descriptor from a query set.
:param compactResult: Parameter used when the mask (or masks) is not empty. If ``compactResult`` is false, the ``matches`` vector has the same size as ``queryDescriptors`` rows. If ``compactResult`` is true, the ``matches`` vector does not contain matches for fully masked-out query descriptors.
These extended variants of :ocv:func:`DescriptorMatcher::match` methods find several best matches for each query descriptor. The matches are returned in the distance increasing order. See :ocv:func:`DescriptorMatcher::match` for the details about query and train descriptors.
These extended variants of :ocv:func:`DescriptorMatcher::match` methods find several best matches for each query descriptor. The matches are returned in the distance increasing order. See :ocv:func:`DescriptorMatcher::match` for the details about query and train descriptors.
@@ -218,7 +218,7 @@ For each query descriptor, finds the training descriptors not farther than the s
:param compactResult: Parameter used when the mask (or masks) is not empty. If ``compactResult`` is false, the ``matches`` vector has the same size as ``queryDescriptors`` rows. If ``compactResult`` is true, the ``matches`` vector does not contain matches for fully masked-out query descriptors.
:param maxDistance: Threshold for the distance between matched descriptors.
For each query descriptor, the methods find such training descriptors that the distance between the query descriptor and the training descriptor is equal or smaller than ``maxDistance``. Found matches are returned in the distance increasing order.
@@ -227,7 +227,7 @@ DescriptorMatcher::clone
----------------------------
Clones the matcher.
.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::clone( bool emptyTrainData ) const
.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::clone( bool emptyTrainData=false )
:param emptyTrainData: If ``emptyTrainData`` is false, the method creates a deep copy of the object, that is, copies both parameters and train data. If ``emptyTrainData`` is true, the method creates an object copy with the current parameters but with empty train data.
@@ -241,15 +241,15 @@ Creates a descriptor matcher of a given type with the default parameters (using
:param descriptorMatcherType: Descriptor matcher type. Now the following matcher types are supported:
*
*
``BruteForce`` (it uses ``L2`` )
*
*
``BruteForce-L1``
*
*
``BruteForce-Hamming``
*
*
``BruteForce-Hamming(2)``
*
*
``FlannBased``
@@ -258,25 +258,25 @@ Creates a descriptor matcher of a given type with the default parameters (using
BFMatcher
-----------------
.. ocv:class::BFMatcher
.. ocv:class:: BFMatcher : public DescriptorMatcher
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. This descriptor matcher supports masking permissible matches of descriptor sets. ::
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. This descriptor matcher supports masking permissible matches of descriptor sets.
BFMatcher::BFMatcher
--------------------
Brute-force matcher constructor.
.. ocv:function:: BFMatcher::BFMatcher( int distanceType, bool crossCheck=false )
.. ocv:function:: BFMatcher::BFMatcher( int normType, bool crossCheck=false )
:param normType: One of ``NORM_L1``, ``NORM_L2``, ``NORM_HAMMING``, ``NORM_HAMMING2``. ``L1`` and ``L2`` norms are preferable choices for SIFT and SURF descriptors, ``NORM_HAMMING`` should be used with ORB and BRIEF, ``NORM_HAMMING2`` should be used with ORB when ``WTA_K==3`` or ``4`` (see ORB::ORB constructor description).
:param distanceType: One of ``NORM_L1``, ``NORM_L2``, ``NORM_HAMMING``, ``NORM_HAMMING2``. ``L1`` and ``L2`` norms are preferable choices for SIFT and SURF descriptors, ``NORM_HAMMING`` should be used with ORB and BRIEF, ``NORM_HAMMING2`` should be used with ORB when ``WTA_K==3`` or ``4`` (see ORB::ORB constructor description).
:param crossCheck: If it is false, this is will be default BFMatcher behaviour when it finds the k nearest neighbors for each query descriptor. If ``crossCheck==true``, then the ``knnMatch()`` method with ``k=1`` will only return pairs ``(i,j)`` such that for ``i-th`` query descriptor the ``j-th`` descriptor in the matcher's collection is the nearest and vice versa, i.e. the ``BFMathcher`` will only return consistent pairs. Such technique usually produces best results with minimal number of outliers when there are enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper.
FlannBasedMatcher
-----------------
.. ocv:class:: FlannBasedMatcher
.. ocv:class:: FlannBasedMatcher : public DescriptorMatcher
Flann-based descriptor matcher. This matcher trains :ocv:class:`flann::Index_` on a train descriptor collection and calls its nearest search methods to find the best matches. So, this matcher may be faster when matching a large train collection than the brute force matcher. ``FlannBasedMatcher`` does not support masking permissible matches of descriptor sets because ``flann::Index`` does not support this. ::
@@ -12,31 +12,31 @@ KeyPoint
--------
.. ocv:class:: KeyPoint
Data structure for salient point detectors.
Data structure for salient point detectors.
.. ocv:member:: Point2f pt
.. ocv:member:: Point2f pt
coordinates of the keypoint
coordinates of the keypoint
.. ocv:member:: float size
.. ocv:member:: float size
diameter of the meaningful keypoint neighborhood
diameter of the meaningful keypoint neighborhood
.. ocv:member:: float angle
.. ocv:member:: float angle
computed orientation of the keypoint (-1 if not applicable)
computed orientation of the keypoint (-1 if not applicable)
.. ocv:member:: float response
.. ocv:member:: float response
the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
.. ocv:member:: int octave
.. ocv:member:: int octave
octave (pyramid layer) from which the keypoint has been extracted
octave (pyramid layer) from which the keypoint has been extracted
.. ocv:member:: int class_id
.. ocv:member:: int class_id
object id that can be used to clustered keypoints by an object they belong to
object id that can be used to clustered keypoints by an object they belong to
KeyPoint::KeyPoint
------------------
@@ -48,7 +48,7 @@ The keypoint constructors
.. ocv:function:: KeyPoint::KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
.. ocv:pyfunction:: cv2.KeyPoint(x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]) -> <KeyPoint object>
.. ocv:pyfunction:: cv2.KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>
:param x: x-coordinate of the keypoint
@@ -69,7 +69,7 @@ The keypoint constructors
FeatureDetector
---------------
.. ocv:class:: FeatureDetector
.. ocv:class:: FeatureDetector : public Algorithm
Abstract base class for 2D image feature detectors. ::
@@ -112,22 +112,6 @@ Detects keypoints in an image (first variant) or image set (second variant).
:param masks: Masks for each input image specifying where to look for keypoints (optional). ``masks[i]`` is a mask for ``images[i]``.
FeatureDetector::read
-------------------------
Reads a feature detector object from a file node.
.. ocv:function:: void FeatureDetector::read( const FileNode& fn )
:param fn: File node from which the detector is read.
FeatureDetector::write
--------------------------
Writes a feature detector object to a file storage.
.. ocv:function:: void FeatureDetector::write( FileStorage& fs ) const
:param fs: File storage where the detector is written.
FeatureDetector::create
---------------------------
Creates a feature detector by its name.
@@ -156,7 +140,7 @@ for example: ``"GridFAST"``, ``"PyramidSTAR"`` .
FastFeatureDetector
-------------------
.. ocv:class:: FastFeatureDetector
.. ocv:class:: FastFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the
:ocv:func:`FAST` method. ::
@@ -173,7 +157,7 @@ Wrapping class for feature detection using the
GoodFeaturesToTrackDetector
---------------------------
.. ocv:class:: GoodFeaturesToTrackDetector
.. ocv:class:: GoodFeaturesToTrackDetector : public FeatureDetector
Wrapping class for feature detection using the
:ocv:func:`goodFeaturesToTrack` function. ::
@@ -211,7 +195,7 @@ Wrapping class for feature detection using the
MserFeatureDetector
-------------------
.. ocv:class:: MserFeatureDetector
.. ocv:class:: MserFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the
:ocv:class:`MSER` class. ::
@@ -233,7 +217,7 @@ Wrapping class for feature detection using the
StarFeatureDetector
-------------------
.. ocv:class:: StarFeatureDetector
.. ocv:class:: StarFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the
:ocv:class:`StarDetector` class. ::
@@ -252,7 +236,7 @@ Wrapping class for feature detection using the
DenseFeatureDetector
--------------------
.. ocv:class:: DenseFeatureDetector
.. ocv:class:: DenseFeatureDetector : public FeatureDetector
Class for generation of image features which are distributed densely and regularly over the image. ::
@@ -279,7 +263,7 @@ The detector generates several levels (in the amount of ``featureScaleLevels``)
SimpleBlobDetector
-------------------
.. ocv:class:: SimpleBlobDetector
.. ocv:class:: SimpleBlobDetector : public FeatureDetector
Class for extracting blobs from an image. ::
@@ -344,7 +328,7 @@ Default values of parameters are tuned to extract dark circular blobs.
GridAdaptedFeatureDetector
--------------------------
.. ocv:class:: GridAdaptedFeatureDetector
.. ocv:class:: GridAdaptedFeatureDetector : public FeatureDetector
Class adapting a detector to partition the source image into a grid and detect points in each cell. ::
@@ -369,7 +353,7 @@ Class adapting a detector to partition the source image into a grid and detect p
PyramidAdaptedFeatureDetector
-----------------------------
.. ocv:class:: PyramidAdaptedFeatureDetector
.. ocv:class:: PyramidAdaptedFeatureDetector : public FeatureDetector
Class adapting a detector to detect points over multiple levels of a Gaussian pyramid. Consider using this class for detectors that are not inherently scaled. ::
@@ -387,7 +371,7 @@ Class adapting a detector to detect points over multiple levels of a Gaussian py
DynamicAdaptedFeatureDetector
-----------------------------
.. ocv:class:: DynamicAdaptedFeatureDetector
.. ocv:class:: DynamicAdaptedFeatureDetector : public FeatureDetector
Adaptively adjusting detector that iteratively detects features until the desired number is found. ::
@@ -431,7 +415,7 @@ DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector
----------------------------------------------------------------
The constructor
.. ocv:function:: DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features, int max_features, int max_iters )
.. ocv:function:: DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 )
:param adjuster: :ocv:class:`AdjusterAdapter` that detects features and adjusts parameters.
@@ -443,7 +427,7 @@ The constructor
AdjusterAdapter
---------------
.. ocv:class:: AdjusterAdapter
.. ocv:class:: AdjusterAdapter : public FeatureDetector
Class providing an interface for adjusting parameters of a feature detector. This interface is used by :ocv:class:`DynamicAdaptedFeatureDetector` . It is a wrapper for :ocv:class:`FeatureDetector` that enables adjusting parameters after feature detection. ::
@@ -522,7 +506,7 @@ Creates an adjuster adapter by name
FastAdjuster
------------
.. ocv:class:: FastAdjuster
.. ocv:class:: FastAdjuster : public AdjusterAdapter
:ocv:class:`AdjusterAdapter` for :ocv:class:`FastFeatureDetector`. This class decreases or increases the threshold value by 1. ::
@@ -535,7 +519,7 @@ FastAdjuster
StarAdjuster
------------
.. ocv:class:: StarAdjuster
.. ocv:class:: StarAdjuster : public AdjusterAdapter
:ocv:class:`AdjusterAdapter` for :ocv:class:`StarFeatureDetector`. This class adjusts the ``responseThreshhold`` of ``StarFeatureDetector``. ::
@@ -3,7 +3,7 @@ Common Interfaces of Generic Descriptor Matchers
.. highlight:: cpp
Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to easily switch
Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables you to easily switch
between different algorithms solving the same problem. This section is devoted to matching descriptors
that cannot be represented as vectors in a multidimensional space. ``GenericDescriptorMatcher`` is a more generic interface for descriptors. It does not make any assumptions about descriptor representation.
Every descriptor with the
@@ -130,7 +130,7 @@ GenericDescriptorMatcher::isMaskSupported
---------------------------------------------
Returns ``true`` if a generic descriptor matcher supports masking permissible matches.
.. ocv:function:: void GenericDescriptorMatcher::isMaskSupported()
.. ocv:function:: bool GenericDescriptorMatcher::isMaskSupported()
@@ -151,12 +151,12 @@ Classifies keypoints from a query set.
:param trainKeypoints: Keypoints from a train image.
The method classifies each keypoint from a query set. The first variant of the method takes a train image and its keypoints as an input argument. The second variant uses the internally stored training collection that can be built using the ``GenericDescriptorMatcher::add`` method.
The methods do the following:
#.
Call the ``GenericDescriptorMatcher::match`` method to find correspondence between the query set and the training set.
#.
Set the ``class_id`` field of each keypoint from the query set to ``class_id`` of the corresponding keypoint from the training set.
@@ -195,7 +195,7 @@ Finds the ``k`` best matches for each query keypoint.
.. ocv:function:: void GenericDescriptorMatcher::knnMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, const Mat& trainImage, vector<KeyPoint>& trainKeypoints, vector<vector<DMatch> >& matches, int k, const Mat& mask=Mat(), bool compactResult=false ) const
.. ocv:function:: void GenericDescriptorMatcher::knnMatch( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, vector<vector<DMatch> >& matches, int k, const vector<Mat>& masks=vector<Mat>(), bool compactResult=false )
The methods are extended variants of ``GenericDescriptorMatch::match``. The parameters are similar, and the semantics is similar to ``DescriptorMatcher::knnMatch``. But this class does not require explicitly computed keypoint descriptors.
@@ -231,7 +231,7 @@ GenericDescriptorMatcher::clone
-----------------------------------
Clones the matcher.
.. ocv:function:: Ptr<GenericDescriptorMatcher> GenericDescriptorMatcher::clone( bool emptyTrainData ) const
.. ocv:function:: Ptr<GenericDescriptorMatcher> GenericDescriptorMatcher::clone( bool emptyTrainData=false ) const
:param emptyTrainData: If ``emptyTrainData`` is false, the method creates a deep copy of the object, that is, copies
both parameters and train data. If ``emptyTrainData`` is true, the method creates an object copy with the current parameters
@@ -240,7 +240,7 @@ Clones the matcher.
VectorDescriptorMatcher
-----------------------
.. ocv:class:: VectorDescriptorMatcher
.. ocv:class:: VectorDescriptorMatcher : public GenericDescriptorMatcher
Class used for matching descriptors that can be described as vectors in a finite-dimensional space. ::
@@ -7,9 +7,9 @@ drawMatches
---------------
Draws the found matches of keypoints from two images.
.. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1, const Mat& img2, const vector<KeyPoint>& keypoints2, const vector<DMatch>& matches1to2, Mat& outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const vector<char>& matchesMask=vector<char>(), int flags=DrawMatchesFlags::DEFAULT )
.. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1, const Mat& img2, const vector<KeyPoint>& keypoints2, const vector<DMatch>& matches1to2, Mat& outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const vector<char>& matchesMask=vector<char>(), int flags=DrawMatchesFlags::DEFAULT )
.. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1, const Mat& img2, const vector<KeyPoint>& keypoints2, const vector<vector<DMatch> >& matches1to2, Mat& outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const vector<vector<char>>& matchesMask= vector<vector<char> >(), int flags=DrawMatchesFlags::DEFAULT )
.. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1, const Mat& img2, const vector<KeyPoint>& keypoints2, const vector<vector<DMatch> >& matches1to2, Mat& outImg, const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), const vector<vector<char> >& matchesMask=vector<vector<char> >(), int flags=DrawMatchesFlags::DEFAULT )
:param img1: First source image.
@@ -31,7 +31,7 @@ Draws the found matches of keypoints from two images.
:param matchesMask: Mask determining which matches are drawn. If the mask is empty, all matches are drawn.
:param flags: Flags setting drawing features. Possible ``flags`` bit values are defined by ``DrawMatchesFlags``.
This function draws matches of keypoints from two images in the output image. Match is a line connecting two keypoints (circles). The structure ``DrawMatchesFlags`` is defined as follows:
.. code-block:: cpp
@@ -65,13 +65,13 @@ drawKeypoints
-----------------
Draws keypoints.
.. ocv:function:: void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImg, const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT )
.. ocv:function:: void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage, const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT )
:param image: Source image.
:param keypoints: Keypoints from the source image.
:param outImg: Output image. Its content depends on the ``flags`` value defining what is drawn in the output image. See possible ``flags`` bit values below.
:param outImage: Output image. Its content depends on the ``flags`` value defining what is drawn in the output image. See possible ``flags`` bit values below.
:param color: Color of keypoints.
@@ -24,7 +24,7 @@ Detects corners using the FAST algorithm by [Rosten06]_.
MSER
----
.. ocv:class:: MSER
.. ocv:class:: MSER : public FeatureDetector
Maximally stable extremal region extractor. ::
@@ -50,7 +50,7 @@ http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http:/
ORB
---
.. ocv:class:: ORB
.. ocv:class:: ORB : public Feature2D
Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor, described in [RRKB11]_. The algorithm uses FAST in pyramids to detect stable keypoints, selects the strongest features using FAST or Harris response, finds their orientation using first-order moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or k-tuples) are rotated according to the measured orientation).
@@ -60,39 +60,37 @@ ORB::ORB
--------
The ORB constructor
.. ocv:function:: ORB::ORB()
.. ocv:function:: ORB::ORB(int nfeatures = 500, float scaleFactor = 1.2f, int nlevels = 8, int edgeThreshold = 31, int firstLevel = 0, int WTA_K=2, int scoreType=HARRIS_SCORE, int patchSize=31)
:param nfeatures: The maximum number of features to retain.
:param scaleFactor: Pyramid decimation ratio, greater than 1. ``scaleFactor==2`` means the classical pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor will mean that to cover certain scale range you will need more pyramid levels and so the speed will suffer.
:param nlevels: The number of pyramid levels. The smallest level will have linear size equal to ``input_image_linear_size/pow(scaleFactor, nlevels)``.
:param edgeThreshold: This is size of the border where the features are not detected. It should roughly match the ``patchSize`` parameter.
:param firstLevel: It should be 0 in the current implementation.
:param WTA_K: The number of points that produce each element of the oriented BRIEF descriptor. The default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 random points (of course, those point coordinates are random, but they are generated from the pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, denoted as ``NORM_HAMMING2`` (2 bits per bin). When ``WTA_K=4``, we take 4 random points to compute each bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3).
:param scoreType: The default HARRIS_SCORE means that Harris algorithm is used to rank features (the score is written to ``KeyPoint::score`` and is used to retain best ``nfeatures`` features); FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, but it is a little faster to compute.
:param patchSize: size of the patch used by the oriented BRIEF descriptor. Of course, on smaller pyramid layers the perceived image area covered by a feature will be larger.
ORB::operator()
---------------
Finds keypoints in an image and computes their descriptors
.. ocv:function:: void ORB::operator()(InputArray image, InputArray mask, vector<KeyPoint>& keypoints, OutputArray descriptors, bool useProvidedKeypoints=false ) const
:param image: The input 8-bit grayscale image.
:param mask: The operation mask.
:param keypoints: The output vector of keypoints.
:param descriptors: The output descriptors. Pass ``cv::noArray()`` if you do not need it.
:param useProvidedKeypoints: If it is true, then the method will use the provided vector of keypoints instead of detecting them.
@@ -54,7 +54,7 @@ BOWTrainer::descripotorsCount
---------------------------------
Returns the count of all descriptors stored in the training set.
.. ocv:function:: const vector<Mat>& BOWTrainer::descripotorsCount() const
.. ocv:function:: int BOWTrainer::descripotorsCount() const
@@ -72,7 +72,7 @@ The vocabulary consists of cluster centers. So, this method returns the vocabula
BOWKMeansTrainer
----------------
.. ocv:class:: BOWKMeansTrainer
.. ocv:class:: BOWKMeansTrainer : public BOWTrainer
:ocv:func:`kmeans` -based class to train visual vocabulary using the *bag of visual words* approach.
::
@@ -51,15 +51,15 @@
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
@@ -81,9 +81,9 @@ public:
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<KeyPoint>& keypoints,
CV_OUT vector<Point2f>& points2f,
@@ -103,13 +103,13 @@ public:
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)
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<KeyPoint>& keypoints);
//! reads vector of keypoints from the specified file storage node
CV_EXPORTS void read(const FileNode& node, CV_OUT vector<KeyPoint>& keypoints);
CV_EXPORTS void read(const FileNode& node, CV_OUT vector<KeyPoint>& keypoints);
/*
* A class filters a vector of keypoints.
@@ -138,14 +138,14 @@ public:
* Remove duplicated keypoints.
*/
static void removeDuplicated( vector<KeyPoint>& keypoints );
/*
* Retain the specified number of the best keypoints (according to the response)
*/
static void retainBest(vector<KeyPoint>& keypoints, int npoints);
};
/************************************ Base Classes ************************************/
/*
@@ -155,7 +155,7 @@ class CV_EXPORTS_W FeatureDetector : public virtual Algorithm
{
public:
virtual ~FeatureDetector();
/*
* Detect keypoints in an image.
* image The image.
@@ -164,7 +164,7 @@ public:
* matrix with non-zero values in the region of interest.
*/
CV_WRAP void detect( const Mat& image, CV_OUT vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
/*
* Detect keypoints in an image set.
* images Image collection.
@@ -172,16 +172,16 @@ public:
* masks Masks for image set. masks[i] is a mask for images[i].
*/
void detect( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, const vector<Mat>& masks=vector<Mat>() ) const;
// Return true if detector object is empty
CV_WRAP virtual bool empty() const;
// Create feature detector by detector name.
CV_WRAP static Ptr<FeatureDetector> create( const string& detectorType );
protected:
virtual void detectImpl( const Mat& image, vector<KeyPoint>& 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
@@ -189,8 +189,8 @@ protected:
*/
static void removeInvalidPoints( const Mat& mask, vector<KeyPoint>& keypoints );
};
/*
* Abstract base class for computing descriptors for image keypoints.
*
@@ -204,7 +204,7 @@ 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.
@@ -212,7 +212,7 @@ public:
* descriptors Copmputed descriptors. Row i is the descriptor for keypoint i.
*/
CV_WRAP void compute( const Mat& image, CV_OUT CV_IN_OUT vector<KeyPoint>& keypoints, CV_OUT Mat& descriptors ) const;
/*
* Compute the descriptors for a keypoints collection detected in image collection.
* images Image collection.
@@ -221,26 +221,26 @@ public:
* descriptors Descriptor collection. descriptors[i] are descriptors computed for set keypoints[i].
*/
void compute( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, vector<Mat>& 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<DescriptorExtractor> create( const string& descriptorExtractorType );
protected:
virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const = 0;
/*
* Remove keypoints within borderPixels of an image edge.
*/
static void removeBorderKeypoints( vector<KeyPoint>& keypoints,
Size imageSize, int borderSize );
};
/*
* Abstract base class for simultaneous 2D feature detection descriptor extraction.
*/
@@ -254,18 +254,18 @@ public:
* 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
* descriptors for the provided keypoints
*/
CV_WRAP_AS(detectAndCompute) virtual void operator()( InputArray image, InputArray mask,
CV_OUT vector<KeyPoint>& keypoints,
OutputArray descriptors,
bool useProvidedKeypoints=false ) const = 0;
// Create feature detector and descriptor extractor by name.
static Ptr<Feature2D> create( const string& name );
};
/*!
ORB implementation.
*/
@@ -276,7 +276,7 @@ public:
enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 };
explicit ORB(int nfeatures = 500, float scaleFactor = 1.2f, int nlevels = 8, int edgeThreshold = 31,
int firstLevel = 0, int WTA_K=2, int scoreType=0, int patchSize=31 );
int firstLevel = 0, int WTA_K=2, int scoreType=HARRIS_SCORE, int patchSize=31 );
// returns the descriptor size in bytes
int descriptorSize() const;
@@ -289,14 +289,14 @@ public:
// Compute the ORB features and descriptors on an image
void operator()( InputArray image, InputArray mask, vector<KeyPoint>& keypoints,
OutputArray descriptors, bool useProvidedKeypoints=false ) const;
AlgorithmInfo* info() const;
protected:
void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
CV_PROP_RW int nfeatures;
CV_PROP_RW double scaleFactor;
CV_PROP_RW int nlevels;
@@ -306,37 +306,37 @@ protected:
CV_PROP_RW int scoreType;
CV_PROP_RW int patchSize;
};
typedef ORB OrbFeatureDetector;
typedef ORB OrbDescriptorExtractor;
/*!
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
explicit MSER( int _delta=5, int _min_area=60, int _max_area=14400,
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, vector<vector<Point> >& msers,
const Mat& mask=Mat() ) const;
CV_WRAP_AS(detect) void operator()( const Mat& image, CV_OUT vector<vector<Point> >& msers,
const Mat& mask=Mat() ) const;
AlgorithmInfo* info() const;
protected:
void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
int delta;
int minArea;
int maxArea;
@@ -347,12 +347,12 @@ protected:
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
@@ -363,16 +363,16 @@ public:
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<KeyPoint>& keypoints) const;
AlgorithmInfo* info() const;
protected:
void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
int maxSize;
int responseThreshold;
int lineThresholdProjected;
@@ -389,7 +389,7 @@ class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector
public:
CV_WRAP FastFeatureDetector( int threshold=10, bool nonmaxSuppression=true );
AlgorithmInfo* info() const;
protected:
virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
@@ -469,7 +469,7 @@ protected:
Params params;
};
class CV_EXPORTS DenseFeatureDetector : public FeatureDetector
{
public:
@@ -486,10 +486,10 @@ protected:
double initFeatureScale;
int featureScaleLevels;
double featureScaleMul;
int initXyStep;
int initImgBound;
bool varyXyStepWithScale;
bool varyImgBoundWithScale;
};
@@ -508,12 +508,14 @@ public:
* gridRows Grid rows count.
* gridCols Grid column count.
*/
CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector,
CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& 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<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
@@ -533,7 +535,7 @@ class CV_EXPORTS_W PyramidAdaptedFeatureDetector : public FeatureDetector
public:
// maxLevel - The 0-based index of the last pyramid layer
CV_WRAP PyramidAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector, int maxLevel=2 );
// TODO implement read/write
virtual bool empty() const;
@@ -549,7 +551,7 @@ protected:
*/
class CV_EXPORTS AdjusterAdapter: public FeatureDetector
{
public:
public:
/** pure virtual interface
*/
virtual ~AdjusterAdapter() {}
@@ -588,13 +590,13 @@ class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector
{
public:
/** \param adjaster an AdjusterAdapter that will do the detection and parameter adjustment
/** \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<AdjusterAdapter>& adjaster, int min_features=400, int max_features=500, int max_iters=5 );
DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 );
virtual bool empty() const;
@@ -741,7 +743,7 @@ protected:
/****************************************************************************************\
* Distance *
\****************************************************************************************/
template<typename T>
struct CV_EXPORTS Accumulator
{
@@ -762,7 +764,7 @@ struct CV_EXPORTS SL2
enum { normType = NORM_L2SQR };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
ResultType operator()( const T* a, const T* b, int size ) const
{
return normL2Sqr<ValueType, ResultType>(a, b, size);
@@ -778,7 +780,7 @@ struct CV_EXPORTS L2
enum { normType = NORM_L2 };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
ResultType operator()( const T* a, const T* b, int size ) const
{
return (ResultType)sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
@@ -794,7 +796,7 @@ struct CV_EXPORTS L1
enum { normType = NORM_L1 };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
ResultType operator()( const T* a, const T* b, int size ) const
{
return normL1<ValueType, ResultType>(a, b, size);
@@ -810,7 +812,7 @@ 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
@@ -826,13 +828,13 @@ template<int cellsize> 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 *
\****************************************************************************************/
@@ -1042,7 +1044,7 @@ public:
virtual void train();
virtual bool isMaskSupported() const;
virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false ) const;
protected:
@@ -1158,9 +1160,9 @@ public:
const vector<Mat>& masks=vector<Mat>(), bool compactResult=false );
// Reads matcher object from a file node
virtual void read( const FileNode& );
virtual void read( const FileNode& fn );
// Writes matcher object to a file storage
virtual void write( FileStorage& ) const;
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;
+32 -32
View File
@@ -16,8 +16,8 @@ are met:
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*Neither the name of the University of Cambridge nor the names of
its contributors may be used to endorse or promote products derived
*Neither the name of the University of Cambridge 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
@@ -35,7 +35,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
The references are:
* Machine learning for high-speed corner detection,
* Machine learning for high-speed corner detection,
E. Rosten and T. Drummond, ECCV 2006
* Faster and better: A machine learning approach to corner detection
E. Rosten, R. Porter and T. Drummond, PAMI, 2009
@@ -64,7 +64,7 @@ static void makeOffsets(int pixel[], int row_stride)
pixel[13] = -3 + row_stride * 1;
pixel[14] = -2 + row_stride * 2;
pixel[15] = -1 + row_stride * 3;
}
}
static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
{
@@ -73,7 +73,7 @@ static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
short d[N];
for( k = 0; k < N; k++ )
d[k] = (short)(v - ptr[pixel[k]]);
#if CV_SSE2
__m128i q0 = _mm_set1_epi16(-1000), q1 = _mm_set1_epi16(1000);
for( k = 0; k < 16; k += 8 )
@@ -128,7 +128,7 @@ static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
a0 = std::max(a0, std::min(a, (int)d[k]));
a0 = std::max(a0, std::min(a, (int)d[k+9]));
}
int b0 = -a0;
for( k = 0; k < 16; k += 2 )
{
@@ -141,14 +141,14 @@ static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
b = std::max(b, (int)d[k+6]);
b = std::max(b, (int)d[k+7]);
b = std::max(b, (int)d[k+8]);
b0 = std::min(b0, std::max(b, (int)d[k]));
b0 = std::min(b0, std::max(b, (int)d[k+9]));
}
threshold = -b0-1;
#endif
#if 0
// check that with the computed "threshold" the pixel is still a corner
// and that with the increased-by-1 "threshold" the pixel is not a corner anymore
@@ -157,7 +157,7 @@ static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
int v0 = std::min(ptr[0] + threshold + delta, 255);
int v1 = std::max(ptr[0] - threshold - delta, 0);
int c0 = 0, c1 = 0;
for( int k = 0; k < N; k++ )
{
int x = ptr[pixel[k]];
@@ -184,7 +184,7 @@ static int cornerScore(const uchar* ptr, const int pixel[], int threshold)
#endif
return threshold;
}
void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool nonmax_suppression)
{
@@ -214,7 +214,7 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
cpbuf[1] = cpbuf[0] + img.cols + 1;
cpbuf[2] = cpbuf[1] + img.cols + 1;
memset(buf[0], 0, img.cols*3);
for(i = 3; i < img.rows-2; i++)
{
const uchar* ptr = img.ptr<uchar>(i) + 3;
@@ -222,7 +222,7 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
int* cornerpos = cpbuf[(i - 3)%3];
memset(curr, 0, img.cols);
int ncorners = 0;
if( i < img.rows - 3 )
{
j = 3;
@@ -233,7 +233,7 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
__m128i v0 = _mm_loadu_si128((const __m128i*)ptr);
__m128i v1 = _mm_xor_si128(_mm_subs_epu8(v0, t), delta);
v0 = _mm_xor_si128(_mm_adds_epu8(v0, t), delta);
__m128i x0 = _mm_sub_epi8(_mm_loadu_si128((const __m128i*)(ptr + pixel[0])), delta);
__m128i x1 = _mm_sub_epi8(_mm_loadu_si128((const __m128i*)(ptr + pixel[4])), delta);
__m128i x2 = _mm_sub_epi8(_mm_loadu_si128((const __m128i*)(ptr + pixel[8])), delta);
@@ -256,24 +256,24 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
ptr -= 8;
continue;
}
__m128i c0 = _mm_setzero_si128(), c1 = c0, max0 = c0, max1 = c0;
for( k = 0; k < N; k++ )
{
__m128i x = _mm_xor_si128(_mm_loadu_si128((const __m128i*)(ptr + pixel[k])), delta);
m0 = _mm_cmpgt_epi8(x, v0);
m1 = _mm_cmpgt_epi8(v1, x);
c0 = _mm_and_si128(_mm_sub_epi8(c0, m0), m0);
c1 = _mm_and_si128(_mm_sub_epi8(c1, m1), m1);
max0 = _mm_max_epu8(max0, c0);
max1 = _mm_max_epu8(max1, c1);
}
max0 = _mm_max_epu8(max0, max1);
int m = _mm_movemask_epi8(_mm_cmpgt_epi8(max0, K16));
for( k = 0; m > 0 && k < 16; k++, m >>= 1 )
if(m & 1)
{
@@ -288,26 +288,26 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
int v = ptr[0];
const uchar* tab = &threshold_tab[0] - v + 255;
int d = tab[ptr[pixel[0]]] | tab[ptr[pixel[8]]];
if( d == 0 )
continue;
d &= tab[ptr[pixel[2]]] | tab[ptr[pixel[10]]];
d &= tab[ptr[pixel[4]]] | tab[ptr[pixel[12]]];
d &= tab[ptr[pixel[6]]] | tab[ptr[pixel[14]]];
if( d == 0 )
continue;
d &= tab[ptr[pixel[1]]] | tab[ptr[pixel[9]]];
d &= tab[ptr[pixel[3]]] | tab[ptr[pixel[11]]];
d &= tab[ptr[pixel[5]]] | tab[ptr[pixel[13]]];
d &= tab[ptr[pixel[7]]] | tab[ptr[pixel[15]]];
if( d & 1 )
{
int vt = v - threshold, count = 0;
for( k = 0; k < N; k++ )
{
int x = ptr[pixel[k]];
@@ -325,11 +325,11 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
count = 0;
}
}
if( d & 2 )
{
int vt = v + threshold, count = 0;
for( k = 0; k < N; k++ )
{
int x = ptr[pixel[k]];
@@ -349,17 +349,17 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
}
}
}
cornerpos[-1] = ncorners;
if( i == 3 )
continue;
const uchar* prev = buf[(i - 4 + 3)%3];
const uchar* pprev = buf[(i - 5 + 3)%3];
cornerpos = cpbuf[(i - 4 + 3)%3];
ncorners = cornerpos[-1];
for( k = 0; k < ncorners; k++ )
{
j = cornerpos[k];
@@ -375,7 +375,7 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
}
}
/*
* FastFeatureDetector
*/
+82 -190
View File
@@ -51,212 +51,104 @@ namespace cv
All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
Otherwise, linker may throw away some seemingly unused stuff.
*/
static Algorithm* createBRIEF() { return new BriefDescriptorExtractor; }
static AlgorithmInfo& brief_info()
{
static AlgorithmInfo brief_info_var("Feature2D.BRIEF", createBRIEF);
return brief_info_var;
}
static AlgorithmInfo& brief_info_auto = brief_info();
AlgorithmInfo* BriefDescriptorExtractor::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
BriefDescriptorExtractor brief;
brief_info().addParam(brief, "bytes", brief.bytes_);
initialized = true;
}
return &brief_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createFAST() { return new FastFeatureDetector; }
static AlgorithmInfo& fast_info()
{
static AlgorithmInfo fast_info_var("Feature2D.FAST", createFAST);
return fast_info_var;
}
static AlgorithmInfo& fast_info_auto = fast_info();
AlgorithmInfo* FastFeatureDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
FastFeatureDetector obj;
fast_info().addParam(obj, "threshold", obj.threshold);
fast_info().addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
initialized = true;
}
return &fast_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createStarDetector() { return new StarDetector; }
static AlgorithmInfo& star_info()
{
static AlgorithmInfo star_info_var("Feature2D.STAR", createStarDetector);
return star_info_var;
}
static AlgorithmInfo& star_info_auto = star_info();
AlgorithmInfo* StarDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
StarDetector obj;
star_info().addParam(obj, "maxSize", obj.maxSize);
star_info().addParam(obj, "responseThreshold", obj.responseThreshold);
star_info().addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
star_info().addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
star_info().addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize);
initialized = true;
}
return &star_info();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createMSER() { return new MSER; }
static AlgorithmInfo& mser_info()
{
static AlgorithmInfo mser_info_var("Feature2D.MSER", createMSER);
return mser_info_var;
}
static AlgorithmInfo& mser_info_auto = mser_info();
AlgorithmInfo* MSER::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
MSER obj;
mser_info().addParam(obj, "delta", obj.delta);
mser_info().addParam(obj, "minArea", obj.minArea);
mser_info().addParam(obj, "maxArea", obj.maxArea);
mser_info().addParam(obj, "maxVariation", obj.maxVariation);
mser_info().addParam(obj, "minDiversity", obj.minDiversity);
mser_info().addParam(obj, "maxEvolution", obj.maxEvolution);
mser_info().addParam(obj, "areaThreshold", obj.areaThreshold);
mser_info().addParam(obj, "minMargin", obj.minMargin);
mser_info().addParam(obj, "edgeBlurSize", obj.edgeBlurSize);
initialized = true;
}
return &mser_info();
}
CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
obj.info()->addParam(obj, "bytes", obj.bytes_));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createORB() { return new ORB; }
static AlgorithmInfo& orb_info()
{
static AlgorithmInfo orb_info_var("Feature2D.ORB", createORB);
return orb_info_var;
}
CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
obj.info()->addParam(obj, "threshold", obj.threshold);
obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression));
static AlgorithmInfo& orb_info_auto = orb_info();
///////////////////////////////////////////////////////////////////////////////////////////////////////////
AlgorithmInfo* ORB::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
ORB obj;
orb_info().addParam(obj, "nFeatures", obj.nfeatures);
orb_info().addParam(obj, "scaleFactor", obj.scaleFactor);
orb_info().addParam(obj, "nLevels", obj.nlevels);
orb_info().addParam(obj, "firstLevel", obj.firstLevel);
orb_info().addParam(obj, "edgeThreshold", obj.edgeThreshold);
orb_info().addParam(obj, "patchSize", obj.patchSize);
orb_info().addParam(obj, "WTA_K", obj.WTA_K);
orb_info().addParam(obj, "scoreType", obj.scoreType);
initialized = true;
}
return &orb_info();
}
static Algorithm* createGFTT() { return new GFTTDetector; }
static Algorithm* createHarris()
{
GFTTDetector* d = new GFTTDetector;
d->set("useHarris", true);
return d;
}
static AlgorithmInfo gftt_info("Feature2D.GFTT", createGFTT);
static AlgorithmInfo harris_info("Feature2D.HARRIS", createHarris);
CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
obj.info()->addParam(obj, "maxSize", obj.maxSize);
obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));
AlgorithmInfo* GFTTDetector::info() const
{
static volatile bool initialized = false;
if( !initialized )
{
GFTTDetector obj;
gftt_info.addParam(obj, "nfeatures", obj.nfeatures);
gftt_info.addParam(obj, "qualityLevel", obj.qualityLevel);
gftt_info.addParam(obj, "minDistance", obj.minDistance);
gftt_info.addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
gftt_info.addParam(obj, "k", obj.k);
harris_info.addParam(obj, "nfeatures", obj.nfeatures);
harris_info.addParam(obj, "qualityLevel", obj.qualityLevel);
harris_info.addParam(obj, "minDistance", obj.minDistance);
harris_info.addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
harris_info.addParam(obj, "k", obj.k);
initialized = true;
}
return &gftt_info;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createDense() { return new DenseFeatureDetector; }
static AlgorithmInfo dense_info("Feature2D.Dense", createDense);
CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
obj.info()->addParam(obj, "delta", obj.delta);
obj.info()->addParam(obj, "minArea", obj.minArea);
obj.info()->addParam(obj, "maxArea", obj.maxArea);
obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
obj.info()->addParam(obj, "minMargin", obj.minMargin);
obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));
AlgorithmInfo* DenseFeatureDetector::info() const
///////////////////////////////////////////////////////////////////////////////////////////////////////////
CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
obj.info()->addParam(obj, "nFeatures", obj.nfeatures);
obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor);
obj.info()->addParam(obj, "nLevels", obj.nlevels);
obj.info()->addParam(obj, "firstLevel", obj.firstLevel);
obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold);
obj.info()->addParam(obj, "patchSize", obj.patchSize);
obj.info()->addParam(obj, "WTA_K", obj.WTA_K);
obj.info()->addParam(obj, "scoreType", obj.scoreType));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT",
obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
obj.info()->addParam(obj, "minDistance", obj.minDistance);
obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
obj.info()->addParam(obj, "k", obj.k));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
class CV_EXPORTS HarrisDetector : public GFTTDetector
{
static volatile bool initialized = false;
if( !initialized )
{
DenseFeatureDetector obj;
dense_info.addParam(obj, "initFeatureScale", obj.initFeatureScale);
dense_info.addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
dense_info.addParam(obj, "featureScaleMul", obj.featureScaleMul);
dense_info.addParam(obj, "initXyStep", obj.initXyStep);
dense_info.addParam(obj, "initImgBound", obj.initImgBound);
dense_info.addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
dense_info.addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale);
initialized = true;
}
return &dense_info;
}
public:
HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
int blockSize=3, bool useHarrisDetector=true, double k=0.04 )
: GFTTDetector( maxCorners, qualityLevel, minDistance, blockSize, useHarrisDetector, k ) {}
AlgorithmInfo* info() const;
};
CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS",
obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
obj.info()->addParam(obj, "minDistance", obj.minDistance);
obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
obj.info()->addParam(obj, "k", obj.k));
////////////////////////////////////////////////////////////////////////////////////////////////////////////
CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul);
obj.info()->addParam(obj, "initXyStep", obj.initXyStep);
obj.info()->addParam(obj, "initImgBound", obj.initImgBound);
obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale));
CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
obj.info()->addParam(obj, "detector", (Ptr<Algorithm>&)obj.detector);
obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
obj.info()->addParam(obj, "gridRows", obj.gridRows);
obj.info()->addParam(obj, "gridCols", obj.gridCols));
bool initModule_features2d(void)
{
Ptr<Algorithm> brief = createBRIEF(), orb = createORB(),
star = createStarDetector(), fastd = createFAST(), mser = createMSER(),
dense = createDense(), gftt = createGFTT(), harris = createHarris();
Ptr<Algorithm> brief = createBriefDescriptorExtractor(), orb = createORB(),
star = createStarDetector(), fastd = createFastFeatureDetector(), mser = createMSER(),
dense = createDenseFeatureDetector(), gftt = createGFTTDetector(),
harris = createHarrisDetector(), grid = createGridAdaptedFeatureDetector();
return brief->info() != 0 && orb->info() != 0 && star->info() != 0 &&
fastd->info() != 0 && mser->info() != 0 && dense->info() != 0 &&
gftt->info() != 0 && harris->info() != 0;
gftt->info() != 0 && harris->info() != 0 && grid->info() != 0;
}
}
+98 -99
View File
@@ -53,31 +53,31 @@ static void
HarrisResponses(const Mat& img, vector<KeyPoint>& pts, int blockSize, float harris_k)
{
CV_Assert( img.type() == CV_8UC1 && blockSize*blockSize <= 2048 );
size_t ptidx, ptsize = pts.size();
const uchar* ptr00 = img.ptr<uchar>();
int step = (int)(img.step/img.elemSize1());
int r = blockSize/2;
float scale = (1 << 2) * blockSize * 255.0f;
scale = 1.0f / scale;
float scale_sq_sq = scale * scale * scale * scale;
AutoBuffer<int> ofsbuf(blockSize*blockSize);
int* ofs = ofsbuf;
for( int i = 0; i < blockSize; i++ )
for( int j = 0; j < blockSize; j++ )
ofs[i*blockSize + j] = (int)(i*step + j);
for( ptidx = 0; ptidx < ptsize; ptidx++ )
{
int x0 = cvRound(pts[ptidx].pt.x - r);
int y0 = cvRound(pts[ptidx].pt.y - r);
const uchar* ptr0 = ptr00 + y0*step + x0;
int a = 0, b = 0, c = 0;
for( int k = 0; k < blockSize*blockSize; k++ )
{
const uchar* ptr = ptr0 + ofs[k];
@@ -98,13 +98,13 @@ static float IC_Angle(const Mat& image, const int half_k, Point2f pt,
const vector<int> & u_max)
{
int m_01 = 0, m_10 = 0;
const uchar* center = &image.at<uchar> (cvRound(pt.y), cvRound(pt.x));
// Treat the center line differently, v=0
for (int u = -half_k; u <= half_k; ++u)
m_10 += u * center[u];
// Go line by line in the circular patch
int step = (int)image.step1();
for (int v = 1; v <= half_k; ++v)
@@ -120,7 +120,7 @@ static float IC_Angle(const Mat& image, const int half_k, Point2f pt,
}
m_01 += v * v_sum;
}
return fastAtan2((float)m_01, (float)m_10);
}
@@ -134,10 +134,10 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
//angle = cvFloor(angle/12)*12.f;
angle *= (float)(CV_PI/180.f);
float a = (float)cos(angle), b = (float)sin(angle);
const uchar* center = &img.at<uchar>(cvRound(kpt.pt.y), cvRound(kpt.pt.x));
int step = (int)img.step;
#if 1
#define GET_VALUE(idx) \
center[cvRound(pattern[idx].x*b + pattern[idx].y*a)*step + \
@@ -153,7 +153,7 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
cvRound(center[iy*step + ix]*(1-x)*(1-y) + center[(iy+1)*step + ix]*(1-x)*y + \
center[iy*step + ix+1]*x*(1-y) + center[(iy+1)*step + ix+1]*x*y))
#endif
if( WTA_K == 2 )
{
for (int i = 0; i < dsize; ++i, pattern += 16)
@@ -175,7 +175,7 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
val |= (t0 < t1) << 6;
t0 = GET_VALUE(14); t1 = GET_VALUE(15);
val |= (t0 < t1) << 7;
desc[i] = (uchar)val;
}
}
@@ -186,16 +186,16 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
int t0, t1, t2, val;
t0 = GET_VALUE(0); t1 = GET_VALUE(1); t2 = GET_VALUE(2);
val = t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0);
t0 = GET_VALUE(3); t1 = GET_VALUE(4); t2 = GET_VALUE(5);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 2;
t0 = GET_VALUE(6); t1 = GET_VALUE(7); t2 = GET_VALUE(8);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 4;
t0 = GET_VALUE(9); t1 = GET_VALUE(10); t2 = GET_VALUE(11);
val |= (t2 > t1 ? (t2 > t0 ? 2 : 0) : (t1 > t0)) << 6;
desc[i] = (uchar)val;
}
}
@@ -211,7 +211,7 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val = k;
t0 = GET_VALUE(4); t1 = GET_VALUE(5);
t2 = GET_VALUE(6); t3 = GET_VALUE(7);
u = 0, v = 2;
@@ -219,7 +219,7 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 2;
t0 = GET_VALUE(8); t1 = GET_VALUE(9);
t2 = GET_VALUE(10); t3 = GET_VALUE(11);
u = 0, v = 2;
@@ -227,7 +227,7 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 4;
t0 = GET_VALUE(12); t1 = GET_VALUE(13);
t2 = GET_VALUE(14); t3 = GET_VALUE(15);
u = 0, v = 2;
@@ -235,23 +235,23 @@ static void computeOrbDescriptor(const KeyPoint& kpt,
if( t3 > t2 ) t2 = t3, v = 3;
k = t0 > t2 ? u : v;
val |= k << 6;
desc[i] = (uchar)val;
}
}
else
CV_Error( CV_StsBadSize, "Wrong WTA_K. It can be only 2, 3 or 4." );
#undef GET_VALUE
}
static void initializeOrbPattern( const Point* pattern0, vector<Point>& pattern, int ntuples, int tupleSize, int poolSize )
{
RNG rng(0x12345678);
int i, k, k1;
pattern.resize(ntuples*tupleSize);
for( i = 0; i < ntuples; i++ )
{
for( k = 0; k < tupleSize; k++ )
@@ -545,7 +545,7 @@ static void makeRandomPattern(int patchSize, Point* pattern, int npoints)
}
}
static inline float getScale(int level, int firstLevel, double scaleFactor)
{
return (float)std::pow(scaleFactor, (double)(level - firstLevel));
@@ -570,8 +570,8 @@ int ORB::descriptorSize() const
int ORB::descriptorType() const
{
return CV_8U;
}
}
/** 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
@@ -599,7 +599,7 @@ static void computeOrientation(const Mat& image, vector<KeyPoint>& keypoints,
keypoint->angle = IC_Angle(image, halfPatchSize, keypoint->pt, umax);
}
}
/** Compute the ORB keypoints on an image
* @param image_pyramid the image pyramid to compute the features and descriptors on
@@ -614,11 +614,11 @@ static void computeKeyPoints(const vector<Mat>& imagePyramid,
{
int nlevels = (int)imagePyramid.size();
vector<int> nfeaturesPerLevel(nlevels);
// fill the extractors and descriptors for the corresponding scales
float factor = (float)(1.0 / scaleFactor);
float ndesiredFeaturesPerScale = nfeatures*(1 - factor)/(1 - (float)pow((double)factor, (double)nlevels));
int sumFeatures = 0;
for( int level = 0; level < nlevels-1; level++ )
{
@@ -627,19 +627,19 @@ static void computeKeyPoints(const vector<Mat>& imagePyramid,
ndesiredFeaturesPerScale *= factor;
}
nfeaturesPerLevel[nlevels-1] = std::max(nfeatures - sumFeatures, 0);
// Make sure we forget about what is too close to the boundary
//edge_threshold_ = std::max(edge_threshold_, patch_size_/2 + kKernelWidth / 2 + 2);
// pre-compute the end of a row in a circular patch
int halfPatchSize = patchSize / 2;
vector<int> umax(halfPatchSize + 1);
int v, v0, vmax = cvFloor(halfPatchSize * sqrt(2.f) / 2 + 1);
int vmin = cvCeil(halfPatchSize * sqrt(2.f) / 2);
for (v = 0; v <= vmax; ++v)
umax[v] = cvRound(sqrt((double)halfPatchSize * halfPatchSize - v * v));
// Make sure we are symmetric
for (v = halfPatchSize, v0 = 0; v >= vmin; --v)
{
@@ -648,37 +648,37 @@ static void computeKeyPoints(const vector<Mat>& imagePyramid,
umax[v] = v0;
++v0;
}
allKeypoints.resize(nlevels);
for (int level = 0; level < nlevels; ++level)
{
int nfeatures = nfeaturesPerLevel[level];
allKeypoints[level].reserve(nfeatures*2);
vector<KeyPoint> & keypoints = allKeypoints[level];
// Detect FAST features, 20 is a good threshold
FastFeatureDetector fd(20, true);
fd.detect(imagePyramid[level], keypoints, maskPyramid[level]);
// Remove keypoints very close to the border
KeyPointsFilter::runByImageBorder(keypoints, imagePyramid[level].size(), edgeThreshold);
if( scoreType == ORB::HARRIS_SCORE )
{
// Keep more points than necessary as FAST does not give amazing corners
KeyPointsFilter::retainBest(keypoints, 2 * nfeatures);
// Compute the Harris cornerness (better scoring than FAST)
HarrisResponses(imagePyramid[level], keypoints, 7, HARRIS_K);
}
//cull to the final desired level, using the new Harris scores or the original FAST scores.
KeyPointsFilter::retainBest(keypoints, nfeatures);
KeyPointsFilter::retainBest(keypoints, nfeatures);
float sf = getScale(level, firstLevel, scaleFactor);
// Set the level of the coordinates
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
@@ -686,12 +686,12 @@ static void computeKeyPoints(const vector<Mat>& imagePyramid,
keypoint->octave = level;
keypoint->size = patchSize*sf;
}
computeOrientation(imagePyramid[level], keypoints, halfPatchSize, umax);
}
}
}
/** Compute the ORB decriptors
* @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)
@@ -706,12 +706,12 @@ static void computeDescriptors(const Mat& image, vector<KeyPoint>& keypoints, Ma
CV_Assert(image.type() == CV_8UC1);
//create the descriptor mat, keypoints.size() rows, BYTES cols
descriptors = Mat::zeros((int)keypoints.size(), dsize, CV_8UC1);
for (size_t i = 0; i < keypoints.size(); i++)
computeOrbDescriptor(keypoints[i], image, &pattern[0], descriptors.ptr((int)i), dsize, WTA_K);
}
/** 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
@@ -725,21 +725,21 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
{
bool do_keypoints = !useProvidedKeypoints;
bool do_descriptors = _descriptors.needed();
if( (!do_keypoints && !do_descriptors) || _image.empty() )
return;
//ROI handling
const int HARRIS_BLOCK_SIZE = 9;
int halfPatchSize = patchSize / 2;
int border = std::max(edgeThreshold, std::max(halfPatchSize, HARRIS_BLOCK_SIZE/2))+1;
Mat image = _image.getMat(), mask = _mask.getMat();
if( image.type() != CV_8UC1 )
cvtColor(_image, image, CV_BGR2GRAY);
int nlevels = this->nlevels;
if( !do_keypoints )
{
// if we have pre-computed keypoints, they may use more levels than it is set in parameters
@@ -756,7 +756,7 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
nlevels = std::max(nlevels, std::max(_keypoints[i].octave, 0));
nlevels++;
}
// Pre-compute the scale pyramids
vector<Mat> imagePyramid(nlevels), maskPyramid(nlevels);
for (int level = 0; level < nlevels; ++level)
@@ -766,49 +766,48 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
Size wholeSize(sz.width + border*2, sz.height + border*2);
Mat temp(wholeSize, image.type()), masktemp;
imagePyramid[level] = temp(Rect(border, border, sz.width, sz.height));
if( !mask.empty() )
{
masktemp = Mat(wholeSize, mask.type());
maskPyramid[level] = masktemp(Rect(border, border, sz.width, sz.height));
}
// Compute the resized image
if( level != firstLevel )
{
if( level < firstLevel )
{
resize(image, imagePyramid[level], sz, scale, scale, INTER_LINEAR);
resize(image, imagePyramid[level], sz, 0, 0, INTER_LINEAR);
if (!mask.empty())
resize(mask, maskPyramid[level], sz, scale, scale, INTER_LINEAR);
copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
BORDER_REFLECT_101+BORDER_ISOLATED);
resize(mask, maskPyramid[level], sz, 0, 0, INTER_LINEAR);
}
else
{
resize(imagePyramid[level-1], imagePyramid[level], sz,
1./scaleFactor, 1./scaleFactor, INTER_LINEAR);
resize(imagePyramid[level-1], imagePyramid[level], sz, 0, 0, INTER_LINEAR);
if (!mask.empty())
resize(maskPyramid[level-1], maskPyramid[level], sz,
1./scaleFactor, 1./scaleFactor, INTER_LINEAR);
copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
BORDER_REFLECT_101+BORDER_ISOLATED);
{
resize(maskPyramid[level-1], maskPyramid[level], sz, 0, 0, INTER_LINEAR);
threshold(maskPyramid[level], maskPyramid[level], 254, 0, THRESH_TOZERO);
}
}
copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
BORDER_REFLECT_101+BORDER_ISOLATED);
if (!mask.empty())
copyMakeBorder(maskPyramid[level], masktemp, border, border, border, border,
BORDER_CONSTANT+BORDER_ISOLATED);
}
else
{
copyMakeBorder(image, temp, border, border, border, border,
BORDER_REFLECT_101);
image.copyTo(imagePyramid[level]);
if( !mask.empty() )
mask.copyTo(maskPyramid[level]);
copyMakeBorder(mask, masktemp, border, border, border, border,
BORDER_CONSTANT+BORDER_ISOLATED);
}
if( !mask.empty() )
copyMakeBorder(maskPyramid[level], masktemp, border, border, border, border,
BORDER_CONSTANT+BORDER_ISOLATED);
}
// Pre-compute the keypoints (we keep the best over all scales, so this has to be done beforehand
vector < vector<KeyPoint> > allKeypoints;
if( do_keypoints )
@@ -817,19 +816,19 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
computeKeyPoints(imagePyramid, maskPyramid, allKeypoints,
nfeatures, firstLevel, scaleFactor,
edgeThreshold, patchSize, scoreType);
// make sure we have the right number of keypoints keypoints
/*vector<KeyPoint> temp;
for (int level = 0; level < n_levels; ++level)
{
vector<KeyPoint>& keypoints = all_keypoints[level];
temp.insert(temp.end(), keypoints.begin(), keypoints.end());
keypoints.clear();
}
KeyPoint::retainBest(temp, n_features_);
for (vector<KeyPoint>::iterator keypoint = temp.begin(),
keypoint_end = temp.end(); keypoint != keypoint_end; ++keypoint)
all_keypoints[keypoint->octave].push_back(*keypoint);*/
@@ -838,19 +837,19 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
{
// Remove keypoints very close to the border
KeyPointsFilter::runByImageBorder(_keypoints, image.size(), edgeThreshold);
// Cluster the input keypoints depending on the level they were computed at
allKeypoints.resize(nlevels);
for (vector<KeyPoint>::iterator keypoint = _keypoints.begin(),
keypointEnd = _keypoints.end(); keypoint != keypointEnd; ++keypoint)
allKeypoints[keypoint->octave].push_back(*keypoint);
// Make sure we rescale the coordinates
for (int level = 0; level < nlevels; ++level)
{
if (level == firstLevel)
continue;
vector<KeyPoint> & keypoints = allKeypoints[level];
float scale = 1/getScale(level, firstLevel, scaleFactor);
for (vector<KeyPoint>::iterator keypoint = keypoints.begin(),
@@ -858,10 +857,10 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
keypoint->pt *= scale;
}
}
Mat descriptors;
vector<Point> pattern;
if( do_descriptors )
{
int nkeypoints = 0;
@@ -874,19 +873,19 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
_descriptors.create(nkeypoints, descriptorSize(), CV_8U);
descriptors = _descriptors.getMat();
}
const int npoints = 512;
Point patternbuf[npoints];
const Point* pattern0 = (const Point*)bit_pattern_31_;
if( patchSize != 31 )
{
pattern0 = patternbuf;
makeRandomPattern(patchSize, patternbuf, npoints);
}
CV_Assert( WTA_K == 2 || WTA_K == 3 || WTA_K == 4 );
if( WTA_K == 2 )
std::copy(pattern0, pattern0 + npoints, std::back_inserter(pattern));
else
@@ -895,7 +894,7 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
initializeOrbPattern(pattern0, pattern, ntuples, WTA_K, npoints);
}
}
_keypoints.clear();
int offset = 0;
for (int level = 0; level < nlevels; ++level)
@@ -903,15 +902,15 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
// Get the features and compute their orientation
vector<KeyPoint>& keypoints = allKeypoints[level];
int nkeypoints = (int)keypoints.size();
// Compute the descriptors
if (do_descriptors)
{
Mat desc;
if (!descriptors.empty())
if (!descriptors.empty())
{
desc = descriptors.rowRange(offset, offset + nkeypoints);
}
}
offset += nkeypoints;
// preprocess the resized image
@@ -920,7 +919,7 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
GaussianBlur(workingMat, workingMat, Size(7, 7), 2, 2, BORDER_REFLECT_101);
computeDescriptors(workingMat, keypoints, desc, pattern, descriptorSize(), WTA_K);
}
// Copy to the output data
if (level != firstLevel)
{
@@ -933,11 +932,11 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
_keypoints.insert(_keypoints.end(), keypoints.begin(), keypoints.end());
}
}
void ORB::detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask) const
{
(*this)(image, mask, keypoints, noArray(), false);
}
}
void ORB::computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors) const
{
@@ -1091,3 +1091,51 @@ TEST( Features2d_DescriptorMatcher_FlannBased, regression )
CV_DescriptorMatcherTest test( "descriptor-matcher-flann-based", new FlannBasedMatcher, 0.04f );
test.safe_run();
}
TEST(Features2D_ORB, _1996)
{
cv::Ptr<cv::FeatureDetector> fd = cv::FeatureDetector::create("ORB");
cv::Ptr<cv::DescriptorExtractor> de = cv::DescriptorExtractor::create("ORB");
Mat image = cv::imread(string(cvtest::TS::ptr()->get_data_path()) + "shared/lena.jpg");
ASSERT_FALSE(image.empty());
Mat roi(image.size(), CV_8UC1, Scalar(0));
Point poly[] = {Point(100, 20), Point(300, 50), Point(400, 200), Point(10, 500)};
fillConvexPoly(roi, poly, int(sizeof(poly) / sizeof(poly[0])), Scalar(255));
std::vector<cv::KeyPoint> keypoints;
fd->detect(image, keypoints, roi);
cv::Mat descriptors;
de->compute(image, keypoints, descriptors);
//image.setTo(Scalar(255,255,255), roi);
int roiViolations = 0;
for(std::vector<cv::KeyPoint>::const_iterator kp = keypoints.begin(); kp != keypoints.end(); ++kp)
{
int x = cvRound(kp->pt.x);
int y = cvRound(kp->pt.y);
ASSERT_LE(0, x);
ASSERT_LE(0, y);
ASSERT_GT(image.cols, x);
ASSERT_GT(image.rows, y);
// if (!roi.at<uchar>(y,x))
// {
// roiViolations++;
// circle(image, kp->pt, 3, Scalar(0,0,255));
// }
}
// if(roiViolations)
// {
// imshow("img", image);
// waitKey();
// }
ASSERT_EQ(0, roiViolations);
}
@@ -289,7 +289,7 @@ Enables the :ocv:class:`gpu::StereoConstantSpaceBP` constructors.
.. ocv:function:: gpu::StereoConstantSpaceBP::StereoConstantSpaceBP(int ndisp = DEFAULT_NDISP, int iters = DEFAULT_ITERS, int levels = DEFAULT_LEVELS, int nr_plane = DEFAULT_NR_PLANE, int msg_type = CV_32F)
.. ocv:function:: StereoConstantSpaceBP::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)
.. ocv:function:: gpu::StereoConstantSpaceBP::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)
:param ndisp: Number of disparities.
+1 -1
View File
@@ -338,7 +338,7 @@ Blocks the current CPU thread until all operations in the stream are complete.
gpu::StreamAccessor
-------------------
.. ocv:class:: gpu::StreamAccessor
.. ocv:struct:: gpu::StreamAccessor
Class that enables getting ``cudaStream_t`` from :ocv:class:`gpu::Stream` and is declared in ``stream_accessor.hpp`` because it is the only public header that depends on the CUDA Runtime API. Including it brings a dependency to your code. ::
@@ -346,19 +346,19 @@ Detects keypoints and computes descriptors for them.
gpu::ORB_GPU::downloadKeypoints
gpu::ORB_GPU::downloadKeyPoints
-------------------------------------
Download keypoints from GPU to CPU memory.
.. ocv:function:: void gpu::ORB_GPU::downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints)
.. ocv:function:: void gpu::ORB_GPU::downloadKeyPoints( GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints )
gpu::ORB_GPU::convertKeypoints
gpu::ORB_GPU::convertKeyPoints
-------------------------------------
Converts keypoints from GPU representation to vector of ``KeyPoint``.
.. ocv:function:: void gpu::ORB_GPU::convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints)
.. ocv:function:: void gpu::ORB_GPU::convertKeyPoints( Mat& d_keypoints, std::vector<KeyPoint>& keypoints )
@@ -372,7 +372,7 @@ Releases inner buffer memory.
gpu::BruteForceMatcher_GPU
--------------------------
.. ocv:class:: gpu::BruteForceMatcher_GPU
.. ocv:class:: template<class Distance> gpu::BruteForceMatcher_GPU
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. This descriptor matcher supports masking permissible matches between descriptor sets. ::
+31 -18
View File
@@ -195,7 +195,7 @@ Creates a normalized 2D box filter.
.. ocv:function:: Ptr<FilterEngine_GPU> gpu::createBoxFilter_GPU(int srcType, int dstType, const Size& ksize, const Point& anchor = Point(-1,-1))
.. ocv:function:: Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1))
.. ocv:function:: Ptr<BaseFilter_GPU> gpu::getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1))
:param srcType: Input image type supporting ``CV_8UC1`` and ``CV_8UC4`` .
@@ -285,7 +285,9 @@ gpu::erode
--------------
Erodes an image by using a specific structuring element.
.. ocv:function:: void gpu::erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::erode( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor=Point(-1, -1), int iterations=1 )
.. ocv:function:: void gpu::erode( const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf, Point anchor=Point(-1, -1), int iterations=1, Stream& stream=Stream::Null() )
:param src: Source image. Only ``CV_8UC1`` and ``CV_8UC4`` types are supported.
@@ -309,7 +311,9 @@ gpu::dilate
---------------
Dilates an image by using a specific structuring element.
.. ocv:function:: void gpu::dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::dilate( const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor=Point(-1, -1), int iterations=1 )
.. ocv:function:: void gpu::dilate( const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf, Point anchor=Point(-1, -1), int iterations=1, Stream& stream=Stream::Null() )
:param src: Source image. ``CV_8UC1`` and ``CV_8UC4`` source types are supported.
@@ -333,7 +337,9 @@ gpu::morphologyEx
---------------------
Applies an advanced morphological operation to an image.
.. ocv:function:: void gpu::morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::morphologyEx( const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor=Point(-1, -1), int iterations=1 )
.. ocv:function:: void gpu::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() )
:param src: Source image. ``CV_8UC1`` and ``CV_8UC4`` source types are supported.
@@ -371,8 +377,6 @@ Creates a non-separable linear filter.
.. ocv:function:: Ptr<FilterEngine_GPU> gpu::createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT)
.. ocv:function:: Ptr<BaseFilter_GPU> gpu::getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, const Size& ksize, Point anchor = Point(-1, -1))
:param srcType: Input image type. Supports ``CV_8U`` , ``CV_16U`` and ``CV_32F`` one and four channel image.
:param dstType: Output image type. The same type as ``src`` is supported.
@@ -441,7 +445,7 @@ gpu::getLinearRowFilter_GPU
-------------------------------
Creates a primitive row filter with the specified kernel.
.. ocv:function:: Ptr<BaseRowFilter_GPU> gpu::getLinearRowFilter_GPU(int srcType, int bufType, const Mat& rowKernel, int anchor = -1, int borderType = BORDER_CONSTANT)
.. ocv:function:: Ptr<BaseRowFilter_GPU> gpu::getLinearRowFilter_GPU( int srcType, int bufType, const Mat& rowKernel, int anchor=-1, int borderType=BORDER_DEFAULT )
:param srcType: Source array type. Only ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` source types are supported.
@@ -467,7 +471,7 @@ gpu::getLinearColumnFilter_GPU
----------------------------------
Creates a primitive column filter with the specified kernel.
.. ocv:function:: Ptr<BaseColumnFilter_GPU> gpu::getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel, int anchor = -1, int borderType = BORDER_CONSTANT)
.. ocv:function:: Ptr<BaseColumnFilter_GPU> gpu::getLinearColumnFilter_GPU( int bufType, int dstType, const Mat& columnKernel, int anchor=-1, int borderType=BORDER_DEFAULT )
:param bufType: Intermediate buffer type with as many channels as ``dstType`` .
@@ -517,7 +521,10 @@ gpu::sepFilter2D
--------------------
Applies a separable 2D linear filter to an image.
.. ocv:function:: void gpu::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, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::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 )
.. ocv:function:: void gpu::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() )
:param src: Source image. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_32SC1`` , ``CV_32FC1`` source types are supported.
@@ -569,7 +576,9 @@ gpu::Sobel
--------------
Applies the generalized Sobel operator to an image.
.. ocv:function:: void gpu::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, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::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 )
.. ocv:function:: void gpu::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() )
:param src: Source image. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` source types are supported.
@@ -599,7 +608,9 @@ gpu::Scharr
---------------
Calculates the first x- or y- image derivative using the Scharr operator.
.. ocv:function:: void gpu::Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::Scharr( const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale=1, int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1 )
.. ocv:function:: void gpu::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() )
:param src: Source image. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` source types are supported.
@@ -627,15 +638,15 @@ gpu::createGaussianFilter_GPU
---------------------------------
Creates a Gaussian filter engine.
.. ocv:function:: Ptr<FilterEngine_GPU> gpu::createGaussianFilter_GPU(int type, Size ksize, double sigmaX, double sigmaY = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1)
.. ocv:function:: Ptr<FilterEngine_GPU> gpu::createGaussianFilter_GPU( int type, Size ksize, double sigma1, double sigma2=0, int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1 )
:param type: Source and destination image type. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` are supported.
:param ksize: Aperture size. See :ocv:func:`getGaussianKernel` for details.
:param sigmaX: Gaussian sigma in the horizontal direction. See :ocv:func:`getGaussianKernel` for details.
:param sigma1: Gaussian sigma in the horizontal direction. See :ocv:func:`getGaussianKernel` for details.
:param sigmaY: Gaussian sigma in the vertical direction. If 0, then :math:`\texttt{sigmaY}\leftarrow\texttt{sigmaX}` .
:param sigma2: Gaussian sigma in the vertical direction. If 0, then :math:`\texttt{sigma2}\leftarrow\texttt{sigma1}` .
:param rowBorderType: Pixel extrapolation method in the vertical direction. For details, see :ocv:func:`borderInterpolate`.
@@ -649,17 +660,19 @@ gpu::GaussianBlur
---------------------
Smooths an image using the Gaussian filter.
.. ocv:function:: void gpu::GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigmaX, double sigmaY = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::GaussianBlur( const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2=0, int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1 )
.. ocv:function:: void gpu::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() )
:param src: Source image. ``CV_8UC1`` , ``CV_8UC4`` , ``CV_16SC1`` , ``CV_16SC2`` , ``CV_16SC3`` , ``CV_32SC1`` , ``CV_32FC1`` source types are supported.
:param dst: Destination image with the same size and type as ``src`` .
:param ksize: Gaussian kernel size. ``ksize.width`` and ``ksize.height`` can differ but they both must be positive and odd. If they are zeros, they are computed from ``sigmaX`` and ``sigmaY`` .
:param ksize: Gaussian kernel size. ``ksize.width`` and ``ksize.height`` can differ but they both must be positive and odd. If they are zeros, they are computed from ``sigma1`` and ``sigma2`` .
:param sigmaX: Gaussian kernel standard deviation in X direction.
:param sigma1: Gaussian kernel standard deviation in X direction.
:param sigmaY: Gaussian kernel standard deviation in Y direction. If ``sigmaY`` is zero, it is set to be equal to ``sigmaX`` . If they are both zeros, they are computed from ``ksize.width`` and ``ksize.height``, respectively. See :ocv:func:`getGaussianKernel` for details. To fully control the result regardless of possible future modification of all this semantics, you are recommended to specify all of ``ksize`` , ``sigmaX`` , and ``sigmaY`` .
:param sigma2: Gaussian kernel standard deviation in Y direction. If ``sigma2`` is zero, it is set to be equal to ``sigma1`` . If they are both zeros, they are computed from ``ksize.width`` and ``ksize.height``, respectively. See :ocv:func:`getGaussianKernel` for details. To fully control the result regardless of possible future modification of all this semantics, you are recommended to specify all of ``ksize`` , ``sigma1`` , and ``sigma2`` .
:param rowBorderType: Pixel extrapolation method in the vertical direction. For details, see :ocv:func:`borderInterpolate`.
+21 -25
View File
@@ -9,7 +9,7 @@ gpu::meanShiftFiltering
---------------------------
Performs mean-shift filtering for each point of the source image.
.. ocv:function:: void gpu::meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr,TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1))
.. ocv:function:: void gpu::meanShiftFiltering( const GpuMat& src, GpuMat& dst, int sp, int sr, TermCriteria criteria=TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1), Stream& stream=Stream::Null() )
:param src: Source image. Only ``CV_8UC4`` images are supported for now.
@@ -29,7 +29,7 @@ gpu::meanShiftProc
----------------------
Performs a mean-shift procedure and stores information about processed points (their colors and positions) in two images.
.. ocv:function:: void gpu::meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr, TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1))
.. ocv:function:: void gpu::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() )
:param src: Source image. Only ``CV_8UC4`` images are supported for now.
@@ -159,7 +159,7 @@ gpu::mulSpectrums
---------------------
Performs a per-element multiplication of two Fourier spectrums.
.. ocv:function:: void gpu::mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false)
.. ocv:function:: void gpu::mulSpectrums( const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false, Stream& stream=Stream::Null() )
:param a: First spectrum.
@@ -181,7 +181,7 @@ gpu::mulAndScaleSpectrums
-----------------------------
Performs a per-element multiplication of two Fourier spectrums and scales the result.
.. ocv:function:: void gpu::mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false)
.. ocv:function:: void gpu::mulAndScaleSpectrums( const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false, Stream& stream=Stream::Null() )
:param a: First spectrum.
@@ -205,7 +205,7 @@ gpu::dft
------------
Performs a forward or inverse discrete Fourier transform (1D or 2D) of the floating point matrix.
.. ocv:function:: void gpu::dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0)
.. ocv:function:: void gpu::dft( const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0, Stream& stream=Stream::Null() )
:param src: Source matrix (real or complex).
@@ -238,7 +238,7 @@ The source matrix should be continuous, otherwise reallocation and data copying
gpu::ConvolveBuf
----------------
.. ocv:class:: gpu::ConvolveBuf
.. ocv:struct:: gpu::ConvolveBuf
Class providing a memory buffer for :ocv:func:`gpu::convolve` function, plus it allows to adjust some specific parameters. ::
@@ -261,7 +261,7 @@ You can use field `user_block_size` to set specific block size for :ocv:func:`gp
gpu::ConvolveBuf::create
------------------------
.. ocv:function:: ConvolveBuf::create(Size image_size, Size templ_size)
.. ocv:function:: gpu::ConvolveBuf::create(Size image_size, Size templ_size)
Constructs a buffer for :ocv:func:`gpu::convolve` function with respective arguments.
@@ -272,7 +272,7 @@ Computes a convolution (or cross-correlation) of two images.
.. ocv:function:: void gpu::convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr=false)
.. ocv:function:: void gpu::convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream &stream = Stream::Null())
.. ocv:function:: void gpu::convolve( const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream& stream=Stream::Null() )
:param image: Source image. Only ``CV_32FC1`` images are supported for now.
@@ -282,7 +282,7 @@ Computes a convolution (or cross-correlation) of two images.
:param ccorr: Flags to evaluate cross-correlation instead of convolution.
:param buf: Optional buffer to avoid extra memory allocations and to adjust some specific parameters. See :ocv:class:`gpu::ConvolveBuf`.
:param buf: Optional buffer to avoid extra memory allocations and to adjust some specific parameters. See :ocv:struct:`gpu::ConvolveBuf`.
:param stream: Stream for the asynchronous version.
@@ -290,7 +290,7 @@ Computes a convolution (or cross-correlation) of two images.
gpu::MatchTemplateBuf
---------------------
.. ocv:class:: gpu::MatchTemplateBuf
.. ocv:struct:: gpu::MatchTemplateBuf
Class providing memory buffers for :ocv:func:`gpu::matchTemplate` function, plus it allows to adjust some specific parameters. ::
@@ -321,7 +321,7 @@ Computes a proximity map for a raster template and an image where the template i
:param method: Specifies the way to compare the template with the image.
:param buf: Optional buffer to avoid extra memory allocations and to adjust some specific parameters. See :ocv:class:`gpu::MatchTemplateBuf`.
:param buf: Optional buffer to avoid extra memory allocations and to adjust some specific parameters. See :ocv:struct:`gpu::MatchTemplateBuf`.
:param stream: Stream for the asynchronous version.
@@ -346,7 +346,7 @@ gpu::remap
--------------
Applies a generic geometrical transformation to an image.
.. ocv:function:: void gpu::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())
.. ocv:function:: void gpu::remap( const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap, int interpolation, int borderMode=BORDER_CONSTANT, Scalar borderValue=Scalar(), Stream& stream=Stream::Null() )
:param src: Source image.
@@ -477,7 +477,7 @@ gpu::warpAffine
-------------------
Applies an affine transformation to an image.
.. ocv:function:: void gpu::warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::warpAffine( const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, Scalar borderValue=Scalar(), Stream& stream=Stream::Null() )
:param src: Source image. ``CV_8U`` , ``CV_16U`` , ``CV_32S`` , or ``CV_32F`` depth and 1, 3, or 4 channels are supported.
@@ -499,7 +499,7 @@ gpu::buildWarpAffineMaps
------------------------
Builds transformation maps for affine transformation.
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
:param M: *2x3* transformation matrix.
@@ -521,7 +521,7 @@ gpu::warpPerspective
------------------------
Applies a perspective transformation to an image.
.. ocv:function:: void gpu::warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::warpPerspective( const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, Scalar borderValue=Scalar(), Stream& stream=Stream::Null() )
:param src: Source image. ``CV_8U`` , ``CV_16U`` , ``CV_32S`` , or ``CV_32F`` depth and 1, 3, or 4 channels are supported.
@@ -543,7 +543,7 @@ gpu::buildWarpPerspectiveMaps
-----------------------------
Builds transformation maps for perspective transformation.
.. ocv:function:: void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null())
:param M: *3x3* transformation matrix.
@@ -657,9 +657,9 @@ Calculates a histogram with evenly distributed bins.
.. ocv:function:: void gpu::histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::histEven(const GpuMat& src, GpuMat* hist, int* histSize, int* lowerLevel, int* upperLevel, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::histEven( const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream=Stream::Null() )
.. ocv:function:: void gpu::histEven(const GpuMat& src, GpuMat* hist, GpuMat& buf, int* histSize, int* lowerLevel, int* upperLevel, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::histEven( const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream=Stream::Null() )
:param src: Source image. ``CV_8U``, ``CV_16U``, or ``CV_16S`` depth and 1 or 4 channels are supported. For a four-channel image, all channels are processed separately.
@@ -685,10 +685,6 @@ Calculates a histogram with bins determined by the ``levels`` array.
.. ocv:function:: void gpu::histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::histRange(const GpuMat& src, GpuMat* hist, const GpuMat* levels, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::histRange(const GpuMat& src, GpuMat* hist, const GpuMat* levels, GpuMat& buf, Stream& stream = Stream::Null())
:param src: Source image. ``CV_8U`` , ``CV_16U`` , or ``CV_16S`` depth and 1 or 4 channels are supported. For a four-channel image, all channels are processed separately.
:param hist: Destination histogram with one row, ``(levels.cols-1)`` columns, and the ``CV_32SC1`` type.
@@ -747,7 +743,7 @@ gpu::buildWarpPlaneMaps
-----------------------
Builds plane warping maps.
.. ocv:function:: void gpu::buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s, double dist, GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::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() )
:param stream: Stream for the asynchronous version.
@@ -757,7 +753,7 @@ gpu::buildWarpCylindricalMaps
-----------------------------
Builds cylindrical warping maps.
.. ocv:function:: void gpu::buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s, GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::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() )
:param stream: Stream for the asynchronous version.
@@ -767,7 +763,7 @@ gpu::buildWarpSphericalMaps
---------------------------
Builds spherical warping maps.
.. ocv:function:: void gpu::buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat& R, double f, double s, GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null())
.. ocv:function:: void gpu::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() )
:param stream: Stream for the asynchronous version.

Some files were not shown because too many files have changed in this diff Show More