1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-29 15:23:05 +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) 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 # 4.0 update 3 - build broken
#set(tbb_ver "tbb40_20120201oss") #set(tbb_ver "tbb40_20120201oss")
#set(tbb_url "http://threadingbuildingblocks.org/uploads/77/182/4.0%20update%203/tbb40_20120201oss_src.tgz") #set(tbb_url "http://threadingbuildingblocks.org/uploads/77/182/4.0%20update%203/tbb40_20120201oss_src.tgz")
#set(tbb_md5 "4669e7d4adee018de7a7b8b972987218") #set(tbb_md5 "4669e7d4adee018de7a7b8b972987218")
#set(tbb_version_file "version_string.tmp")
# 4.0 update 2 - works fine # 4.0 update 2 - works fine
set(tbb_ver "tbb40_20111130oss") #set(tbb_ver "tbb40_20111130oss")
set(tbb_url "http://threadingbuildingblocks.org/uploads/77/180/4.0%20update%202/tbb40_20111130oss_src.tgz") #set(tbb_url "http://threadingbuildingblocks.org/uploads/77/180/4.0%20update%202/tbb40_20111130oss_src.tgz")
set(tbb_md5 "1e6926b21e865e79772119cd44fc3ad8") #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 # 4.0 update 1 - works fine
#set(tbb_ver "tbb40_20111003oss") #set(tbb_ver "tbb40_20111003oss")
#set(tbb_url "http://threadingbuildingblocks.org/uploads/77/177/4.0%20update%201/tbb40_20111003oss_src.tgz") #set(tbb_url "http://threadingbuildingblocks.org/uploads/77/177/4.0%20update%201/tbb40_20111003oss_src.tgz")
#set(tbb_md5 "7b5d94eb35a563b29ef402e0fd8f15c9") #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_tarball "${CMAKE_CURRENT_SOURCE_DIR}/${tbb_ver}_src.tgz")
set(tbb_src_dir "${CMAKE_CURRENT_BINARY_DIR}/${tbb_ver}") 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 add_definitions(-D__TBB_DYNAMIC_LOAD_ENABLED=0 #required
-D__TBB_BUILD=1 #required -D__TBB_BUILD=1 #required
-D__TBB_SURVIVE_THREAD_SWITCH=0 #no cilk on Android -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
-DUSE_PTHREAD #required -DUSE_PTHREAD #required
-DTBB_USE_GCC_BUILTINS=1 #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 -DTBB_NO_LEGACY=1 #don't need backward compatibility
-DDO_ITT_NOTIFY=0 #it seems that we don't need these notifications -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) target_link_libraries(tbb c m dl)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -w -include \"${CMAKE_CURRENT_SOURCE_DIR}/android_additional.h\"") 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 \ #define __TBB_VERSION_STRINGS \
"TBB: BUILD_HOST buit as part of OpenCV" ENDL \ "TBB: BUILD_HOST Unknown" ENDL \
"TBB: BUILD_OS crosscompiling" ENDL \ "TBB: BUILD_OS Android" ENDL \
"TBB: BUILD_KERNEL UNKNOWN" ENDL \ "TBB: BUILD_KERNEL Unknown" ENDL \
"TBB: BUILD_GCC gcc version 4.4.3" ENDL \ "TBB: BUILD_GCC gcc version 4.4.3" ENDL \
"TBB: BUILD_GLIBC 2.11.1" ENDL \ "TBB: BUILD_GLIBC Unknown" ENDL \
"TBB: BUILD_LD " ENDL \ "TBB: BUILD_LD Unknown" ENDL \
"TBB: BUILD_TARGET on " ENDL \ "TBB: BUILD_TARGET Unknown" ENDL \
"TBB: BUILD_COMMAND TBD" ENDL \ "TBB: BUILD_COMMAND use cv::getBuildInformation() for details" ENDL \
#define __TBB_DATETIME "Sun Jan 01 00:00:01 UTC 2012"
+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 \
+156 -344
View File
@@ -50,6 +50,7 @@ else()
cmake_minimum_required(VERSION 2.6.3) cmake_minimum_required(VERSION 2.6.3)
endif() endif()
# must go before the project command
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE) set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
if(DEFINED CMAKE_BUILD_TYPE AND CMAKE_VERSION VERSION_GREATER "2.8") if(DEFINED CMAKE_BUILD_TYPE AND CMAKE_VERSION VERSION_GREATER "2.8")
set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} ) set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} )
@@ -59,6 +60,14 @@ project(OpenCV CXX C)
include(cmake/OpenCVUtils.cmake REQUIRED) 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 # 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_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_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_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_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_JASPER "Include JPEG2K support" ON IF (NOT IOS) )
OCV_OPTION(WITH_JPEG "Include JPEG 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_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_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_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_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_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) ) 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_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) ) 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 # OpenCV build options
# =================================================== # ===================================================
OCV_OPTION(ENABLE_PRECOMPILED_HEADERS "Use precompiled headers" ON IF (NOT IOS) ) 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_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_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.*) ) OCV_OPTION(ENABLE_POWERPC "Enable PowerPC for GCC" ON IF (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_SYSTEM_PROCESSOR MATCHES powerpc.*) )
@@ -293,182 +310,50 @@ if(UNIX)
include(cmake/OpenCVFindPkgConfig.cmake OPTIONAL) include(cmake/OpenCVFindPkgConfig.cmake OPTIONAL)
include(CheckFunctionExists) include(CheckFunctionExists)
include(CheckIncludeFile) 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() endif()
include(cmake/OpenCVPCHSupport.cmake REQUIRED) include(cmake/OpenCVPCHSupport.cmake REQUIRED)
include(cmake/OpenCVModule.cmake REQUIRED) include(cmake/OpenCVModule.cmake REQUIRED)
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Detect 3rd-party tools and libraries # Detect 3rd-party libraries
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# IO libraries include(cmake/OpenCVFindLibsGrfmt.cmake REQUIRED)
include(cmake/OpenCVIOLibs.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_) # Detect other 3rd-party libraries/tools
CHECK_MODULE(libucil HAVE_UNICAP_UCIL) # ----------------------------------------------------------------------------
if(HAVE_UNICAP_ AND HAVE_UNICAP_UCIL)
set(HAVE_UNICAP 1)
endif()
else()
set(HAVE_UNICAP FALSE)
endif()
if(WITH_PVAPI) # --- LATEX for pdf documentation ---
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 ##################
if(BUILD_DOCS) if(BUILD_DOCS)
include(cmake/OpenCVFindLATEX.cmake REQUIRED) include(cmake/OpenCVFindLATEX.cmake REQUIRED)
endif() endif(BUILD_DOCS)
########################## Python Support ######################### # --- Python Support ---
include(cmake/OpenCVDetectPython.cmake REQUIRED) include(cmake/OpenCVDetectPython.cmake REQUIRED)
########################### Java Support ########################## # --- Java Support ---
if(ANDROID) if(ANDROID)
include(cmake/OpenCVDetectApacheAnt.cmake REQUIRED) include(cmake/OpenCVDetectApacheAnt.cmake REQUIRED)
include(cmake/OpenCVDetectAndroidSDK.cmake REQUIRED) include(cmake/OpenCVDetectAndroidSDK.cmake REQUIRED)
@@ -476,7 +361,7 @@ if(ANDROID)
if(NOT ANDROID_TOOLS_Pkg_Revision GREATER 13) 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.") message(WARNING "OpenCV requires Android SDK tools revision 14 or newer. Otherwise tests and samples will no be compiled.")
endif() 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)) 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) SET(CAN_BUILD_ANDROID_PROJECTS TRUE)
@@ -484,115 +369,6 @@ else()
SET(CAN_BUILD_ANDROID_PROJECTS FALSE) SET(CAN_BUILD_ANDROID_PROJECTS FALSE)
endif() 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: # Solution folders:
@@ -658,12 +434,12 @@ if(OPENCV_SVNVERSION)
status("Version control:" ${OPENCV_SVNVERSION}) status("Version control:" ${OPENCV_SVNVERSION})
endif() endif()
#build platform # ========================== build platform ==========================
status("") status("")
status(" Platform:") status(" Platform:")
status(" Host:" ${CMAKE_HOST_SYSTEM_NAME} ${CMAKE_HOST_SYSTEM_VERSION} ${CMAKE_HOST_SYSTEM_PROCESSOR}) status(" Host:" ${CMAKE_HOST_SYSTEM_NAME} ${CMAKE_HOST_SYSTEM_VERSION} ${CMAKE_HOST_SYSTEM_PROCESSOR})
if(CMAKE_CROSSCOMPILING) 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() endif()
status(" CMake:" ${CMAKE_VERSION}) status(" CMake:" ${CMAKE_VERSION})
status(" CMake generator:" ${CMAKE_GENERATOR}) status(" CMake generator:" ${CMAKE_GENERATOR})
@@ -678,7 +454,7 @@ if(NOT CMAKE_GENERATOR MATCHES "Xcode|Visual Studio")
status(" Configuration:" ${CMAKE_BUILD_TYPE}) status(" Configuration:" ${CMAKE_BUILD_TYPE})
endif() endif()
# C/C++ options # ========================== C/C++ options ==========================
status("") status("")
status(" C/C++:") status(" C/C++:")
status(" Built as dynamic libs?:" BUILD_SHARED_LIBS THEN YES ELSE NO) 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}) status(" Linker flags (Debug):" ${CMAKE_SHARED_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS_DEBUG})
endif() endif()
# OpenCV modules # ========================== OpenCV modules ==========================
status("") status("")
status(" OpenCV modules:") status(" OpenCV modules:")
string(REPLACE "opencv_" "" OPENCV_MODULES_BUILD_ST "${OPENCV_MODULES_BUILD}") 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}") 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(" 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(" 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 "-") status(" Unavailable:" OPENCV_MODULES_DISABLED_FORCE THEN ${OPENCV_MODULES_DISABLED_FORCE_ST} ELSE "-")
# Android extra # ========================== Android details ==========================
if(ANDROID) if(ANDROID)
status("") status("")
status(" Android: ") status(" Android: ")
@@ -735,14 +511,17 @@ if(ANDROID)
status(" ant:" ANT_EXECUTABLE THEN "${ANT_EXECUTABLE} (ver ${ANT_VERSION})" ELSE NO) status(" ant:" ANT_EXECUTABLE THEN "${ANT_EXECUTABLE} (ver ${ANT_VERSION})" ELSE NO)
endif() endif()
#YV # ========================== GUI ==========================
status("") status("")
status(" GUI: ") 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 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) status(" QT OpenGL support:" HAVE_QT_OPENGL THEN "YES (${QT_QTOPENGL_LIBRARY})" ELSE NO)
else() else()
if(DEFINED WITH_QT)
status(" QT 4.x:" NO)
endif()
if(WIN32) if(WIN32)
status(" Win32 UI:" YES) status(" Win32 UI:" YES)
else() else()
@@ -762,7 +541,7 @@ endif()
status(" OpenGL support:" HAVE_OPENGL THEN "YES (${OPENGL_LIBRARIES})" ELSE NO) status(" OpenGL support:" HAVE_OPENGL THEN "YES (${OPENGL_LIBRARIES})" ELSE NO)
# media # ========================== MEDIA IO ==========================
status("") status("")
status(" Media I/O: ") status(" Media I/O: ")
status(" ZLib:" BUILD_ZLIB THEN "build (ver ${ZLIB_VERSION_STRING})" ELSE "${ZLIB_LIBRARY} (ver ${ZLIB_VERSION_STRING})") status(" ZLib:" BUILD_ZLIB THEN "build (ver ${ZLIB_VERSION_STRING})" ELSE "${ZLIB_LIBRARY} (ver ${ZLIB_VERSION_STRING})")
@@ -793,82 +572,120 @@ else()
endif() endif()
status(" OpenEXR:" WITH_OPENEXR AND OPENEXR_FOUND THEN "${OPENEXR_LIBRARIES} (ver ${OPENEXR_VERSION})" ELSE NO) 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("") 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 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(" 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) if(HAVE_GSTREAMER)
status(" base:" "YES (ver ${ALIASOF_gstreamer-base-0.10_VERSION})") status(" base:" "YES (ver ${ALIASOF_gstreamer-base-0.10_VERSION})")
status(" app:" "YES (ver ${ALIASOF_gstreamer-app-0.10_VERSION})") status(" app:" "YES (ver ${ALIASOF_gstreamer-app-0.10_VERSION})")
status(" video:" "YES (ver ${ALIASOF_gstreamer-video-0.10_VERSION})") status(" video:" "YES (ver ${ALIASOF_gstreamer-video-0.10_VERSION})")
endif() endif()
status(" UniCap:" HAVE_UNICAP THEN "YES (ver ${ALIASOF_libunicap_VERSION})" ELSE NO) endif(DEFINED WITH_GSTREAMER)
status(" UniCap ucil:" HAVE_UNICAP_UCIL THEN "YES (ver ${ALIASOF_libucil_VERSION})" ELSE NO)
status(" PvAPI:" HAVE_PVAPI THEN YES ELSE NO) 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) if(HAVE_CAMV4L)
set(HAVE_CAMV4L_STR "YES") set(HAVE_CAMV4L_STR "YES")
else() else()
set(HAVE_CAMV4L_STR "NO") set(HAVE_CAMV4L_STR "NO")
endif() endif()
if(HAVE_CAMV4L2) if(HAVE_CAMV4L2)
set(HAVE_CAMV4L2_STR "YES") set(HAVE_CAMV4L2_STR "YES")
else() else()
set(HAVE_CAMV4L2_STR "NO") set(HAVE_CAMV4L2_STR "NO")
endif() endif()
status(" V4L/V4L2:" HAVE_LIBV4L THEN "Using libv4l (ver ${ALIASOF_libv4l1_VERSION})" ELSE "${HAVE_CAMV4L_STR}/${HAVE_CAMV4L2_STR}") status(" V4L/V4L2:" HAVE_LIBV4L THEN "Using libv4l (ver ${ALIASOF_libv4l1_VERSION})"
status(" Xine:" HAVE_XINE THEN "YES (ver ${ALIASOF_libxine_VERSION})" ELSE NO) ELSE "${HAVE_CAMV4L_STR}/${HAVE_CAMV4L2_STR}")
endif(DEFINED WITH_V4L)
if(ANDROID) if(DEFINED WITH_VIDEOINPUT)
if(HAVE_opencv_androidcamera) status(" DirectShow:" HAVE_VIDEOINPUT THEN YES ELSE NO)
status(" AndroidNativeCamera:" BUILD_ANDROID_CAMERA_WRAPPER THEN "YES, build for Android ${ANDROID_VERSION}" ELSE "YES, use prebuilt libraries") endif(DEFINED WITH_VIDEOINPUT)
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(WIN32) if(DEFINED WITH_XIMEA)
status(" FFMPEG:" WITH_FFMPEG THEN "YES (prebuilt binaries)" ELSE NO) status(" XIMEA:" HAVE_XIMEA THEN YES ELSE NO)
else() endif(DEFINED WITH_XIMEA)
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)
# 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("")
status(" Other third-party libraries:") status(" Other third-party libraries:")
if(WITH_IPP AND IPP_FOUND) if(DEFINED WITH_IPP)
status(" Use IPP:" "${IPP_LATEST_VERSION_STR} [${IPP_LATEST_VERSION_MAJOR}.${IPP_LATEST_VERSION_MINOR}.${IPP_LATEST_VERSION_BUILD}]") if(WITH_IPP AND IPP_FOUND)
status(" at:" "${IPP_ROOT_DIR}") status(" Use IPP:" "${IPP_LATEST_VERSION_STR} [${IPP_LATEST_VERSION_MAJOR}.${IPP_LATEST_VERSION_MINOR}.${IPP_LATEST_VERSION_BUILD}]")
else() status(" at:" "${IPP_ROOT_DIR}")
status(" Use IPP:" WITH_IPP AND NOT IPP_FOUND THEN "IPP not found" ELSE NO) else()
endif() 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) status(" Use Eigen:" HAVE_EIGEN THEN "YES (ver ${EIGEN_WORLD_VERSION}.${EIGEN_MAJOR_VERSION}.${EIGEN_MINOR_VERSION})" ELSE NO)
if(HAVE_CUDA) if(HAVE_CUDA)
@@ -882,7 +699,7 @@ if(HAVE_CUDA)
status(" NVIDIA GPU features:" ${OPENCV_CUDA_ARCH_FEATURES}) status(" NVIDIA GPU features:" ${OPENCV_CUDA_ARCH_FEATURES})
endif() endif()
# interfaces to other languages # ========================== python ==========================
status("") status("")
status(" Python:") status(" Python:")
status(" Interpreter:" PYTHON_EXECUTABLE THEN "${PYTHON_EXECUTABLE} (ver ${PYTHON_VERSION_FULL})" ELSE NO) 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 "-") status(" packages path:" PYTHON_EXECUTABLE THEN "${PYTHON_PACKAGES_PATH}" ELSE "-")
endif() endif()
if(BUILD_opencv_java) # ========================== documentation ==========================
status("")
status(" Java:" HAVE_opencv_java THEN YES ELSE NO)
endif()
# documentation
if(BUILD_DOCS) if(BUILD_DOCS)
status("") status("")
status(" Documentation:") status(" Documentation:")
@@ -914,7 +726,7 @@ if(BUILD_DOCS)
status(" PdfLaTeX compiler:" PDFLATEX_COMPILER THEN "${PDFLATEX_COMPILER}" ELSE NO) status(" PdfLaTeX compiler:" PDFLATEX_COMPILER THEN "${PDFLATEX_COMPILER}" ELSE NO)
endif() endif()
# samples and tests # ========================== samples and tests ==========================
status("") status("")
status(" Tests and samples:") status(" Tests and samples:")
status(" Tests:" BUILD_TESTS AND HAVE_opencv_ts THEN YES ELSE NO) 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) status(" Examples:" BUILD_EXAMPLES THEN YES ELSE NO)
if(ANDROID) if(ANDROID)
status(" Android tests:" BUILD_TESTS AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO) 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 examples:" BUILD_ANDROID_EXAMPLES AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO)
endif() endif()
#auxiliary # ========================== auxiliary ==========================
status("") status("")
status(" Install path:" "${CMAKE_INSTALL_PREFIX}") status(" Install path:" "${CMAKE_INSTALL_PREFIX}")
status("") 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). # Requires cmake 2.6.3 or newer (2.8.3 or newer is recommended).
# See home page: http://code.google.com/p/android-cmake/ # See home page: http://code.google.com/p/android-cmake/
# #
@@ -20,7 +20,7 @@
# #
# Usage Windows: # Usage Windows:
# You need native port of make to build your project. # 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 older NDK you have to install it separately.
# For example, this one: http://gnuwin32.sourceforge.net/packages/make.htm # For example, this one: http://gnuwin32.sourceforge.net/packages/make.htm
# #
@@ -177,6 +177,9 @@
# [+] updated for NDK r7c # [+] updated for NDK r7c
# [~] fixed most of problems with compiler/linker flags and caching # [~] fixed most of problems with compiler/linker flags and caching
# [+] added option ANDROID_FUNCTION_LEVEL_LINKING # [+] added option ANDROID_FUNCTION_LEVEL_LINKING
# - modified May 2012
# [+] updated for NDK r8
# [+] added mips architecture support
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
cmake_minimum_required( VERSION 2.6.3 ) cmake_minimum_required( VERSION 2.6.3 )
@@ -186,7 +189,8 @@ if( DEFINED CMAKE_CROSSCOMPILING )
return() return()
endif() 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 ) include( "${CMAKE_CURRENT_SOURCE_DIR}/../android.toolchain.config.cmake" OPTIONAL )
endif() endif()
@@ -195,7 +199,7 @@ set( CMAKE_SYSTEM_NAME Linux )
#this one not so much #this one not so much
set( CMAKE_SYSTEM_VERSION 1 ) 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(NOT DEFINED ANDROID_NDK_SEARCH_PATHS)
if( CMAKE_HOST_WIN32 ) if( CMAKE_HOST_WIN32 )
file( TO_CMAKE_PATH "$ENV{PROGRAMFILES}" ANDROID_NDK_SEARCH_PATHS ) 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_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_x86 "x86" )
set( ANDROID_SUPPORTED_ABIS_mipsel "mips" )
set( ANDROID_DEFAULT_NDK_API_LEVEL 8 ) set( ANDROID_DEFAULT_NDK_API_LEVEL 8 )
set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 9 ) set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 9 )
set( ANDROID_DEFAULT_NDK_API_LEVEL_mips 9 )
macro( __LIST_FILTER listvar regex ) macro( __LIST_FILTER listvar regex )
@@ -432,6 +438,7 @@ endif()
#get all the details about standalone toolchain #get all the details about standalone toolchain
if( BUILD_WITH_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" ) __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" ) set( __availableToolchains "standalone" )
__DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" ) __DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" )
if( NOT __availableToolchainMachines ) if( NOT __availableToolchainMachines )
@@ -441,6 +448,8 @@ if( BUILD_WITH_STANDALONE_TOOLCHAIN )
set( __availableToolchainArchs "x86" ) set( __availableToolchainArchs "x86" )
elseif( __availableToolchainMachines MATCHES arm ) elseif( __availableToolchainMachines MATCHES arm )
set( __availableToolchainArchs "arm" ) set( __availableToolchainArchs "arm" )
elseif( __availableToolchainMachines MATCHES mipsel )
set( __availableToolchainArchs "mipsel" )
endif() endif()
if( ANDROID_COMPILER_VERSION ) if( ANDROID_COMPILER_VERSION )
#do not run gcc every time because it is relatevely expencive #do not run gcc every time because it is relatevely expencive
@@ -513,16 +522,25 @@ if( ANDROID_ABI STREQUAL "x86" )
set( X86 true ) set( X86 true )
set( ANDROID_NDK_ABI_NAME "x86" ) set( ANDROID_NDK_ABI_NAME "x86" )
set( ANDROID_ARCH_NAME "x86" ) set( ANDROID_ARCH_NAME "x86" )
set( ANDROID_ARCH_FULLNAME "x86" )
set( CMAKE_SYSTEM_PROCESSOR "i686" ) 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" ) elseif( ANDROID_ABI STREQUAL "armeabi" )
set( ARMEABI true ) set( ARMEABI true )
set( ANDROID_NDK_ABI_NAME "armeabi" ) set( ANDROID_NDK_ABI_NAME "armeabi" )
set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv5te" ) set( CMAKE_SYSTEM_PROCESSOR "armv5te" )
elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" ) elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" )
set( ARMEABI_V6 true ) set( ARMEABI_V6 true )
set( ANDROID_NDK_ABI_NAME "armeabi" ) set( ANDROID_NDK_ABI_NAME "armeabi" )
set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv6" ) set( CMAKE_SYSTEM_PROCESSOR "armv6" )
#need always fallback to older platform #need always fallback to older platform
set( ARMEABI true ) set( ARMEABI true )
@@ -530,17 +548,20 @@ elseif( ANDROID_ABI STREQUAL "armeabi-v7a")
set( ARMEABI_V7A true ) set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" ) elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" )
set( ARMEABI_V7A true ) set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
set( VFPV3 true ) set( VFPV3 true )
elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" ) elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" )
set( ARMEABI_V7A true ) set( ARMEABI_V7A true )
set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" )
set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_NAME "arm" )
set( ANDROID_ARCH_FULLNAME "arm" )
set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" )
set( VFPV3 true ) set( VFPV3 true )
set( NEON 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" ) file( APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" "SET(CMAKE_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")\n" )
endif() 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" ) if( CMAKE_VERSION VERSION_GREATER "2.8" )
list( SORT 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_NAME}} ) set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} )
endif() endif()
if( ANDROID_ARCH_NAME STREQUAL "arm" AND NOT ARMEABI_V6 ) 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" ) 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() endif()
list( GET __availableToolchainArchs ${__toolchainIdx} __toolchainArch ) 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." ) message( SEND_ERROR "Previously selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is not able to compile binaries for the \"${ANDROID_ARCH_NAME}\" platform." )
endif() endif()
else() else()
@@ -586,7 +607,7 @@ else()
math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" ) math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" )
foreach( __idx RANGE ${__availableToolchainsCount} ) foreach( __idx RANGE ${__availableToolchainsCount} )
list( GET __availableToolchainArchs ${__idx} __toolchainArch ) list( GET __availableToolchainArchs ${__idx} __toolchainArch )
if( __toolchainArch STREQUAL ANDROID_ARCH_NAME ) if( __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME )
list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion ) list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion )
if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion ) if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion )
set( __toolchainMaxVersion "${__toolchainVersion}" ) set( __toolchainMaxVersion "${__toolchainVersion}" )
@@ -614,7 +635,7 @@ unset( __availableToolchainArchs )
unset( __availableToolchainCompilerVersions ) unset( __availableToolchainCompilerVersions )
#choose native API level #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}" ) string( REGEX MATCH "[0-9]+" ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" )
#validate #validate
list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx ) list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx )
@@ -745,32 +766,30 @@ set( CMAKE_COMPILER_IS_GNUASM 1)
# NDK flags # NDK flags
if( ARMEABI OR ARMEABI_V7A ) if( ARMEABI OR ARMEABI_V7A )
# NDK also defines -ffunction-sections -funwind-tables but they result in worse OpenCV performance # NDK also defines -ffunction-sections -funwind-tables but they result in worse OpenCV performance
set( CMAKE_CXX_FLAGS "-fPIC -Wno-psabi" ) set( _CMAKE_CXX_FLAGS "-fPIC -Wno-psabi" )
set( CMAKE_C_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()
remove_definitions( -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ ) 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__ ) add_definitions( -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ )
# extra arm-specific flags # extra arm-specific flags
set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" )
elseif( X86 ) elseif( X86 )
set( CMAKE_CXX_FLAGS "-funwind-tables" ) set( _CMAKE_CXX_FLAGS "-funwind-tables" )
set( CMAKE_C_FLAGS "-funwind-tables" ) set( _CMAKE_C_FLAGS "-funwind-tables" )
if( ANDROID_USE_STLPORT ) elseif( MIPS )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti -fno-exceptions" ) 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_C_FLAGS "${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions" ) 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" )
else() set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -frtti -fexceptions" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fexceptions" )
endif()
else() else()
set( CMAKE_CXX_FLAGS "" ) set( _CMAKE_CXX_FLAGS "" )
set( CMAKE_C_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() endif()
#release and debug flags #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 #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). #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 # O3 instead of O2/Os in release mode - like cmake sets for desktop gcc
set( CMAKE_CXX_FLAGS_RELEASE "-mthumb -O3" ) set( _CMAKE_CXX_FLAGS_RELEASE "-mthumb -O3" )
set( CMAKE_C_FLAGS_RELEASE "-mthumb -O3" ) set( _CMAKE_C_FLAGS_RELEASE "-mthumb -O3" )
set( CMAKE_CXX_FLAGS_DEBUG "-marm -Os -finline-limit=64" ) set( _CMAKE_CXX_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
set( CMAKE_C_FLAGS_DEBUG "-marm -Os -finline-limit=64" ) set( _CMAKE_C_FLAGS_DEBUG "-marm -Os -finline-limit=64" )
else() else()
# always compile ARMEABI_V6 in arm mode; otherwise there is no difference from ARMEABI # 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 # 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_CXX_FLAGS_RELEASE "-marm -O3 -fstrict-aliasing" )
set( CMAKE_C_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_CXX_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
set( CMAKE_C_FLAGS_DEBUG "-marm -O0 -finline-limit=300" ) set( _CMAKE_C_FLAGS_DEBUG "-marm -O0 -finline-limit=300" )
endif() endif()
elseif( X86 ) elseif( X86 )
set( CMAKE_CXX_FLAGS_RELEASE "-O3 -fstrict-aliasing" ) set( _CMAKE_CXX_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( CMAKE_C_FLAGS_RELEASE "-O3 -fstrict-aliasing" ) set( _CMAKE_C_FLAGS_RELEASE "-O3 -fstrict-aliasing" )
set( CMAKE_CXX_FLAGS_DEBUG "-O0 -finline-limit=300" ) set( _CMAKE_CXX_FLAGS_DEBUG "-O0 -finline-limit=300" )
set( CMAKE_C_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() endif()
set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -DNDEBUG" ) 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_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_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_C_FLAGS_DEBUG "${_CMAKE_C_FLAGS_DEBUG} -fno-strict-aliasing -fno-omit-frame-pointer -DDEBUG -D_DEBUG" )
#ABI-specific flags #ABI-specific flags
if( ARMEABI_V7A ) if( ARMEABI_V7A )
@@ -904,12 +928,12 @@ if( ARMEABI_V7A )
endif() endif()
#cache flags #cache flags
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" CACHE STRING "c++ 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_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_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_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_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_C_FLAGS_DEBUG "${_CMAKE_C_FLAGS_DEBUG}" CACHE STRING "c Debug flags" )
set( CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "linker flags" ) set( CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "linker flags" )
set( CMAKE_MODULE_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" ) 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( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}" CACHE INTERNAL "Extra Android linker flags")
set( CMAKE_CXX_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" ) set( CMAKE_CXX_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" )
set( CMAKE_C_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" ) set( CMAKE_C_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" )
set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" ) if( MIPS AND BUILD_WITH_ANDROID_NDK )
set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" ) set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.xsc ${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
set( CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_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 these global flags for cmake client scripts to change behavior
set( ANDROID True ) set( ANDROID True )
@@ -1020,7 +1050,7 @@ endif()
# Variables controlling behavior or set by cmake toolchain: # 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_NATIVE_API_LEVEL : 3,4,5,8,9,14 (depends on NDK version)
# ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF # ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF
# ANDROID_USE_STLPORT : OFF/ON - EXPERIMENTAL!!! # ANDROID_USE_STLPORT : OFF/ON - EXPERIMENTAL!!!
@@ -1054,7 +1084,7 @@ endif()
# BUILD_WITH_STANDALONE_TOOLCHAIN : TRUE if standalone toolchain is used # 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_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_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 # TOOL_OS_SUFFIX : "" or ".exe" depending on host platform
# ANDROID_SYSROOT : path to the compiler sysroot # ANDROID_SYSROOT : path to the compiler sysroot
# ANDROID_SYSTEM_INCLUDE_DIRS # 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)") if(MINGW)
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG" CACHE STRING "") # 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() endif()
if(MSVC) 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_RELEASE "")
set(OPENCV_EXTRA_EXE_LINKER_FLAGS_DEBUG "") 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) if(CMAKE_COMPILER_IS_GNUCXX)
# High level of warnings. # High level of warnings.
set(OPENCV_EXTRA_C_FLAGS "${OPENCV_EXTRA_C_FLAGS} -Wall") 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) if(CMAKE_HOST_WIN32)
set(ANDROID_SDK_OS windows) set(ANDROID_SDK_OS windows)
elseif(CMAKE_HOST_APPLE) elseif(CMAKE_HOST_APPLE)
set(ANDROID_SDK_OS mac) set(ANDROID_SDK_OS macosx)
else() else()
set(ANDROID_SDK_OS linux) set(ANDROID_SDK_OS linux)
endif() 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) find_package(CUDA 4.1)
if(CUDA_FOUND) if(CUDA_FOUND)
@@ -13,7 +18,12 @@ if(CUDA_FOUND)
message(STATUS "CUDA detected: " ${CUDA_VERSION}) 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") 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}") string(REGEX REPLACE "\\." "" ARCH_BIN_NO_POINTS "${CUDA_ARCH_BIN}")
+3 -3
View File
@@ -8,11 +8,11 @@ endif()
if(NOT APPLE) if(NOT APPLE)
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_COMPILER_IS_GNUCXX 1) set(CMAKE_COMPILER_IS_GNUCXX 1)
unset(ENABLE_PRECOMPILED_HEADERS CACHE) set(ENABLE_PRECOMPILED_HEADERS OFF CACHE BOOL "" FORCE)
endif() endif()
if(CMAKE_C_COMPILER_ID STREQUAL "Clang") if(CMAKE_C_COMPILER_ID STREQUAL "Clang")
set(CMAKE_COMPILER_IS_GNUC 1) set(CMAKE_COMPILER_IS_GNUCC 1)
unset(ENABLE_PRECOMPILED_HEADERS CACHE) set(ENABLE_PRECOMPILED_HEADERS OFF CACHE BOOL "" FORCE)
endif() endif()
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 # search for executable with the same bitness as resulting binaries
# standard FindPythonInterp always prefers executable from system path # 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 # 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() endforeach()
endif() endif()
find_host_package(PythonInterp 2.0) find_host_package(PythonInterp 2.0)
unset(PYTHON_USE_NUMPY CACHE) unset(PYTHON_USE_NUMPY CACHE)
unset(HAVE_SPHINX CACHE) unset(HAVE_SPHINX CACHE)
if(PYTHON_EXECUTABLE) if(PYTHON_EXECUTABLE)
if(PYTHON_VERSION_STRING) if(PYTHON_VERSION_STRING)
set(PYTHON_VERSION_FULL "${PYTHON_VERSION_STRING}")
set(PYTHON_VERSION_MAJOR_MINOR "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}") 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() else()
execute_process(COMMAND ${PYTHON_EXECUTABLE} --version execute_process(COMMAND ${PYTHON_EXECUTABLE} --version
ERROR_VARIABLE PYTHON_VERSION_FULL ERROR_VARIABLE PYTHON_VERSION_FULL
@@ -46,16 +44,15 @@ if(PYTHON_EXECUTABLE)
OUTPUT_VARIABLE PYTHON_STD_PACKAGES_PATH OUTPUT_VARIABLE PYTHON_STD_PACKAGES_PATH
OUTPUT_STRIP_TRAILING_WHITESPACE) OUTPUT_STRIP_TRAILING_WHITESPACE)
if("${PYTHON_STD_PACKAGES_PATH}" MATCHES "site-packages") 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. 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() endif()
if(EXISTS "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/${PYTHON_PACKAGES_PATH}") 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() else()
set(PYTHON_PACKAGES_PATH "lib/${PYTHON_PACKAGES_PATH}") set(_PYTHON_PACKAGES_PATH "lib/${_PYTHON_PACKAGES_PATH}")
endif() endif()
set(PYTHON_PACKAGES_PATH "${PYTHON_PACKAGES_PATH}" CACHE PATH "Where to install the python packages.")
elseif(CMAKE_HOST_WIN32) elseif(CMAKE_HOST_WIN32)
get_filename_component(PYTHON_PATH "${PYTHON_EXECUTABLE}" PATH) get_filename_component(PYTHON_PATH "${PYTHON_EXECUTABLE}" PATH)
file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH) file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH)
@@ -67,8 +64,9 @@ if(PYTHON_EXECUTABLE)
endif() endif()
file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH) file(TO_CMAKE_PATH "${PYTHON_PATH}" PYTHON_PATH)
endif() endif()
set(PYTHON_PACKAGES_PATH "${PYTHON_PATH}/Lib/site-packages") set(_PYTHON_PACKAGES_PATH "${PYTHON_PATH}/Lib/site-packages")
endif() endif()
SET(PYTHON_PACKAGES_PATH "${_PYTHON_PACKAGES_PATH}" CACHE PATH "Where to install the python packages.")
if(NOT PYTHON_NUMPY_INCLUDE_DIR) if(NOT PYTHON_NUMPY_INCLUDE_DIR)
# Attempt to discover the NumPy include directory. If this succeeds, then build python API with NumPy # 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) OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PYTHON_NUMPY_PROCESS EQUAL 0) if(PYTHON_NUMPY_PROCESS EQUAL 0)
file(TO_CMAKE_PATH "${PYTHON_NUMPY_INCLUDE_DIR}" PYTHON_NUMPY_INCLUDE_DIR) 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") set(PYTHON_NUMPY_INCLUDE_DIR ${_PYTHON_NUMPY_INCLUDE_DIR} CACHE PATH "Path to numpy headers")
endif() endif()
endif() endif()
+60 -46
View File
@@ -220,45 +220,40 @@ function(set_ipp_variables _LATEST_VERSION)
endfunction() endfunction()
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
# This section will look for IPP through IPPROOT env variable # 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 # Note, IPPROOT is not set by IPP installer, you may need to set it manually
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
find_path( find_path(
IPP_H_PATH IPP_H_PATH
NAMES ippversion.h NAMES ippversion.h
PATHS $ENV{IPPROOT} PATHS $ENV{IPPROOT}
PATH_SUFFIXES include PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files" DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH NO_DEFAULT_PATH
NO_CMAKE_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 # extract IPP version info
get_filename_component(IPP_ROOT_DIR ${IPP_H_PATH} PATH) get_ipp_version(${IPP_ROOT_DIR})
# extract IPP version info # keep info in the same vars for auto search and search by IPPROOT
get_ipp_version(${IPP_ROOT_DIR}) 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 INCLUDE, LIB dirs and library names
set(IPP_LATEST_VERSION_STR ${IPP_VERSION_STR}) set_ipp_variables(${IPP_LATEST_VERSION_STR})
set(IPP_LATEST_VERSION_MAJOR ${IPP_VERSION_MAJOR}) endif()
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()
if(IPP_FOUND) if(NOT IPP_FOUND)
return()
endif()
# reset var from previous search # reset var from previous search
set(IPP_H_PATH) set(IPP_H_PATH)
@@ -304,19 +299,38 @@ endfunction()
endforeach() endforeach()
endif() endif()
endforeach() endforeach()
endif()
if(IPP_FOUND) if(IPP_FOUND)
# set IPP INCLUDE, LIB dirs and library names # set IPP INCLUDE, LIB dirs and library names
set_ipp_variables(${IPP_LATEST_VERSION_STR}) set_ipp_variables(${IPP_LATEST_VERSION_STR})
# set CACHE variable IPP_H_PATH, # set CACHE variable IPP_H_PATH,
# path to IPP header files for the latest version # path to IPP header files for the latest version
find_path( find_path(
IPP_H_PATH IPP_H_PATH
NAMES ippversion.h NAMES ippversion.h
PATHS ${IPP_ROOT_DIR} PATHS ${IPP_ROOT_DIR}
PATH_SUFFIXES include PATH_SUFFIXES include
DOC "The path to Intel(R) IPP header files" DOC "The path to Intel(R) IPP header files"
NO_DEFAULT_PATH NO_DEFAULT_PATH
NO_CMAKE_PATH) NO_CMAKE_PATH)
endif() 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}) # Detect 3rd-party image IO libraries
unset(${var} CACHE) # ----------------------------------------------------------------------------
endforeach()
endmacro()
################### zlib - required # --- zlib (required) ---
if(BUILD_ZLIB) if(BUILD_ZLIB)
unset_all(ZLIB_FOUND) ocv_clear_vars(ZLIB_FOUND)
else() else()
include(FindZLIB) 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 "") ocv_parse_header2(ZLIB "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_VERSION "")
endif() endif()
if(ZLIB_FOUND AND ANDROID) if(ZLIB_FOUND AND ANDROID)
@@ -21,7 +23,7 @@ else()
endif() endif()
if(NOT ZLIB_FOUND) 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_LIBRARY zlib)
set(ZLIB_LIBRARIES ${ZLIB_LIBRARY}) 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}") set(ZLIB_INCLUDE_DIR "${${ZLIB_LIBRARY}_SOURCE_DIR}" "${${ZLIB_LIBRARY}_BINARY_DIR}")
endif() endif()
################### libtiff - optional (should be searched after zlib) # --- libtiff (optional, should be searched after zlib) ---
if(WITH_TIFF) if(WITH_TIFF)
if(BUILD_TIFF) if(BUILD_TIFF)
unset_all(TIFF_FOUND) ocv_clear_vars(TIFF_FOUND)
else() else()
include(FindTIFF) include(FindTIFF)
if(TIFF_FOUND) if(TIFF_FOUND)
@@ -42,7 +44,7 @@ if(WITH_TIFF)
endif() endif()
if(WITH_TIFF AND NOT TIFF_FOUND) 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_LIBRARY libtiff)
set(TIFF_LIBRARIES ${TIFF_LIBRARY}) 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}) set(TIFF_VERSION_BIG ${TIFF_BIGTIFF_VERSION})
endif() endif()
################### libjpeg - optional # --- libjpeg (optional) ---
if(WITH_JPEG) if(WITH_JPEG)
if(BUILD_JPEG) if(BUILD_JPEG)
unset_all(JPEG_FOUND) ocv_clear_vars(JPEG_FOUND)
else() else()
include(FindJPEG) include(FindJPEG)
endif() endif()
endif() endif()
if(WITH_JPEG AND NOT JPEG_FOUND) 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_LIBRARY libjpeg)
set(JPEG_LIBRARIES ${JPEG_LIBRARY}) set(JPEG_LIBRARIES ${JPEG_LIBRARY})
@@ -80,17 +82,17 @@ endif()
ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION) 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(WITH_JASPER)
if(BUILD_JASPER) if(BUILD_JASPER)
unset_all(JASPER_FOUND) ocv_clear_vars(JASPER_FOUND)
else() else()
include(FindJasper) include(FindJasper)
endif() endif()
endif() endif()
if(WITH_JASPER AND NOT JASPER_FOUND) 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_LIBRARY libjasper)
set(JASPER_LIBRARIES ${JASPER_LIBRARY}) 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 "") ocv_parse_header2(JASPER "${JASPER_INCLUDE_DIR}/jasper/jas_config.h" JAS_VERSION "")
endif() endif()
################### libpng - optional (should be searched after zlib) # --- libpng (optional, should be searched after zlib) ---
if(WITH_PNG) if(WITH_PNG)
if(BUILD_PNG) if(BUILD_PNG)
unset_all(PNG_FOUND) ocv_clear_vars(PNG_FOUND)
else() else()
include(FindPNG) include(FindPNG)
if(PNG_FOUND) if(PNG_FOUND)
@@ -121,7 +123,7 @@ if(WITH_PNG)
endif() endif()
if(WITH_PNG AND NOT PNG_FOUND) 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_LIBRARY libpng)
set(PNG_LIBRARIES ${PNG_LIBRARY}) 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}") set(PNG_VERSION "${PNG_LIBPNG_VER_MAJOR}.${PNG_LIBPNG_VER_MINOR}.${PNG_LIBPNG_VER_RELEASE}")
################### OpenEXR - optional # --- OpenEXR (optional) ---
if(WITH_OPENEXR) if(WITH_OPENEXR)
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindOpenEXR.cmake") include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindOpenEXR.cmake")
endif() 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}") set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE "${ANDROID_NATIVE_API_LEVEL}")
endif() 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) set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE TRUE)
else() else()
set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE FALSE) set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE FALSE)
+25 -9
View File
@@ -7,6 +7,7 @@
# #
# OPENCV_MODULE_${the_module}_LOCATION # OPENCV_MODULE_${the_module}_LOCATION
# OPENCV_MODULE_${the_module}_DESCRIPTION # OPENCV_MODULE_${the_module}_DESCRIPTION
# OPENCV_MODULE_${the_module}_CLASS - PUBLIC|INTERNAL|BINDINGS
# OPENCV_MODULE_${the_module}_HEADERS # OPENCV_MODULE_${the_module}_HEADERS
# OPENCV_MODULE_${the_module}_SOURCES # OPENCV_MODULE_${the_module}_SOURCES
# OPENCV_MODULE_${the_module}_DEPS - final flattened set of module dependencies # 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: # To control the setup of the module you could also set:
# the_description - text to be used as current module description # 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_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: # The verbose template for OpenCV module:
# #
@@ -38,10 +41,12 @@
# clean flags for modules enabled on previous cmake run # clean flags for modules enabled on previous cmake run
# this is necessary to correctly handle modules removal # 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}) if(HAVE_${mod})
unset(HAVE_${mod} CACHE) unset(HAVE_${mod} CACHE)
endif() endif()
unset(OPENCV_MODULE_${mod}_REQ_DEPS CACHE)
unset(OPENCV_MODULE_${mod}_OPT_DEPS CACHE)
endforeach() endforeach()
# clean modules info which needs to be recalculated # 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 # * <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) macro(ocv_add_dependencies full_modname)
#we don't clean the dependencies here to allow this macro several times for every module #we don't clean the dependencies here to allow this macro several times for every module
foreach(d "REQIRED" ${ARGN}) foreach(d "REQUIRED" ${ARGN})
if(d STREQUAL "REQIRED") if(d STREQUAL "REQUIRED")
set(__depsvar OPENCV_MODULE_${full_modname}_REQ_DEPS) set(__depsvar OPENCV_MODULE_${full_modname}_REQ_DEPS)
elseif(d STREQUAL "OPTIONAL") elseif(d STREQUAL "OPTIONAL")
set(__depsvar OPENCV_MODULE_${full_modname}_OPT_DEPS) set(__depsvar OPENCV_MODULE_${full_modname}_OPT_DEPS)
@@ -84,7 +89,7 @@ endmacro()
# Usage: # Usage:
# ocv_add_module(<name> [INTERNAL|BINDINGS] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>]) # ocv_add_module(<name> [INTERNAL|BINDINGS] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>])
# Example: # 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) macro(ocv_add_module _name)
string(TOLOWER "${_name}" name) string(TOLOWER "${_name}" name)
string(REGEX REPLACE "^opencv_" "" ${name} "${name}") string(REGEX REPLACE "^opencv_" "" ${name} "${name}")
@@ -106,24 +111,32 @@ macro(ocv_add_module _name)
endif() endif()
set(OPENCV_MODULE_${the_module}_DESCRIPTION "${the_description}" CACHE INTERNAL "Brief description of ${the_module} module") 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") 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 #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") 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}) set(__ocv_argn__ ${ARGN})
list(REMOVE_AT __ocv_argn__ 0) list(REMOVE_AT __ocv_argn__ 0)
ocv_add_dependencies(${the_module} ${__ocv_argn__}) ocv_add_dependencies(${the_module} ${__ocv_argn__})
unset(__ocv_argn__) unset(__ocv_argn__)
else() else()
set(OPENCV_MODULE_${the_module}_CLASS "PUBLIC" CACHE INTERNAL "The cathegory of the module")
ocv_add_dependencies(${the_module} ${ARGN}) ocv_add_dependencies(${the_module} ${ARGN})
if(BUILD_${the_module}) if(BUILD_${the_module})
set(OPENCV_MODULES_PUBLIC ${OPENCV_MODULES_PUBLIC} "${the_module}" CACHE INTERNAL "List of OpenCV modules marked for export") set(OPENCV_MODULES_PUBLIC ${OPENCV_MODULES_PUBLIC} "${the_module}" CACHE INTERNAL "List of OpenCV modules marked for export")
endif() endif()
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}) if(BUILD_${the_module})
set(OPENCV_MODULES_BUILD ${OPENCV_MODULES_BUILD} "${the_module}" CACHE INTERNAL "List of OpenCV modules included into the build") set(OPENCV_MODULES_BUILD ${OPENCV_MODULES_BUILD} "${the_module}" CACHE INTERNAL "List of OpenCV modules included into the build")
else() else()
@@ -429,10 +442,13 @@ endmacro()
# creates OpenCV module in current folder # creates OpenCV module in current folder
# creates new target, configures standard dependencies, compilers flags, install rules # creates new target, configures standard dependencies, compilers flags, install rules
# Usage: # Usage:
# ocv_create_module(<extra link dependencies>) # ocv_create_module(<extra link dependencies>)
# ocv_create_module(SKIP_LINK)
macro(ocv_create_module) macro(ocv_create_module)
add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES}) 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}) add_dependencies(opencv_modules ${the_module})
if(ENABLE_SOLUTION_FOLDERS) if(ENABLE_SOLUTION_FOLDERS)
+13 -6
View File
@@ -11,7 +11,7 @@ if(NOT COMMAND find_host_program)
endmacro() endmacro()
endif() 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) function(ocv_include_directories)
set(__add_before "") set(__add_before "")
foreach(dir ${ARGN}) foreach(dir ${ARGN})
@@ -25,6 +25,12 @@ function(ocv_include_directories)
include_directories(BEFORE ${__add_before}) include_directories(BEFORE ${__add_before})
endfunction() 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. # Provides an option that the user can optionally select.
# Can accept condition to control when option is available for user. # 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}) set(${LIBNAME}_VERSION_STRING "${${LIBNAME}_VERSION_STRING}.${${LIBNAME}_VERSION_TWEAK}" ${SCOPE})
endif() endif()
else() else()
unset(${LIBNAME}_VERSION_MAJOR CACHE) ocv_clear_vars(${LIBNAME}_VERSION_MAJOR
unset(${LIBNAME}_VERSION_MINOR CACHE) ${LIBNAME}_VERSION_MAJOR
unset(${LIBNAME}_VERSION_PATCH CACHE) ${LIBNAME}_VERSION_MINOR
unset(${LIBNAME}_VERSION_TWEAK CACHE) ${LIBNAME}_VERSION_PATCH
unset(${LIBNAME}_VERSION_STRING CACHE) ${LIBNAME}_VERSION_TWEAK
${LIBNAME}_VERSION_STRING)
endif() endif()
endmacro() endmacro()
+38 -2
View File
@@ -11,8 +11,44 @@ if(BUILD_DOCS AND HAVE_SPHINX)
project(opencv_docs) project(opencv_docs)
file(GLOB_RECURSE OPENCV_FILES_REF ../modules/*.rst) set(OPENCV2_BASE_MODULES core imgproc highgui video calib3d features2d objdetect ml flann gpu photo stitching nonfree contrib legacy)
file(GLOB_RECURSE OPENCV_FILES_REF_PICT ../modules/*.png ../modules/*.jpg)
# 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_UG user_guide/*.rst)
file(GLOB_RECURSE OPENCV_FILES_TUT tutorials/*.rst) file(GLOB_RECURSE OPENCV_FILES_TUT tutorials/*.rst)
file(GLOB_RECURSE OPENCV_FILES_TUT_PICT tutorials/*.png tutorials/*.jpg) file(GLOB_RECURSE OPENCV_FILES_TUT_PICT tutorials/*.png tutorials/*.jpg)
+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)
+63 -14
View File
@@ -294,7 +294,8 @@ class OCVPyXRefRole(XRefRole):
########################### 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)') _whitespace_re = re.compile(r'\s+(?u)')
_string_re = re.compile(r"[LuU8]?('([^'\\]*(?:\\.[^'\\]*)*)'" _string_re = re.compile(r"[LuU8]?('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S) r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)
@@ -303,10 +304,10 @@ _operator_re = re.compile(r'''(?x)
\[\s*\] \[\s*\]
| \(\s*\) | \(\s*\)
| (<<|>>)=? | (<<|>>)=?
| \+\+ | -- | ->\*?
| [!<>=/*%+|&^-]=? | [!<>=/*%+|&^-]=?
| \+\+ | --
| ~ | && | \| | \|\| | ~ | && | \| | \|\|
| ->\*? | \, | \,
''') ''')
_id_shortwords = { _id_shortwords = {
@@ -667,13 +668,14 @@ class MemberObjDefExpr(NamedDefExpr):
class FuncDefExpr(NamedDefExpr): class FuncDefExpr(NamedDefExpr):
def __init__(self, name, visibility, static, explicit, rv, def __init__(self, name, visibility, static, explicit, rv,
signature, const, pure_virtual): signature, const, pure_virtual, virtual):
NamedDefExpr.__init__(self, name, visibility, static) NamedDefExpr.__init__(self, name, visibility, static)
self.rv = rv self.rv = rv
self.signature = signature self.signature = signature
self.explicit = explicit self.explicit = explicit
self.const = const self.const = const
self.pure_virtual = pure_virtual self.pure_virtual = pure_virtual
self.virtual = virtual
def get_id(self): def get_id(self):
return u'%s%s%s' % ( return u'%s%s%s' % (
@@ -687,6 +689,8 @@ class FuncDefExpr(NamedDefExpr):
buf = self.get_modifiers() buf = self.get_modifiers()
if self.explicit: if self.explicit:
buf.append(u'explicit') buf.append(u'explicit')
if self.virtual:
buf.append(u'virtual')
if self.rv is not None: if self.rv is not None:
buf.append(unicode(self.rv)) buf.append(unicode(self.rv))
buf.append(u'%s(%s)' % (self.name, u', '.join( buf.append(u'%s(%s)' % (self.name, u', '.join(
@@ -700,8 +704,9 @@ class FuncDefExpr(NamedDefExpr):
class ClassDefExpr(NamedDefExpr): class ClassDefExpr(NamedDefExpr):
def __init__(self, name, visibility, static): def __init__(self, name, visibility, static, parents = None):
NamedDefExpr.__init__(self, name, visibility, static) NamedDefExpr.__init__(self, name, visibility, static)
self.parents = parents
def get_id(self): def get_id(self):
return self.name.get_id() return self.name.get_id()
@@ -788,7 +793,6 @@ class DefinitionParser(object):
if self.match(_operator_re): if self.match(_operator_re):
return NameDefExpr('operator' + return NameDefExpr('operator' +
_whitespace_re.sub('', self.matched_text)) _whitespace_re.sub('', self.matched_text))
# new/delete operator? # new/delete operator?
for allocop in 'new', 'delete': for allocop in 'new', 'delete':
if not self.skip_word(allocop): if not self.skip_word(allocop):
@@ -807,7 +811,7 @@ class DefinitionParser(object):
return CastOpDefExpr(type) return CastOpDefExpr(type)
def _parse_name(self): def _parse_name(self):
if not self.match(_identifier_re): if not self.match(_argument_name_re):
self.fail('expected name') self.fail('expected name')
identifier = self.matched_text identifier = self.matched_text
@@ -1004,8 +1008,13 @@ class DefinitionParser(object):
self.skip_ws() self.skip_ws()
argtype = self._parse_type() argtype = self._parse_type()
argname = default = None
self.skip_ws() 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('='): if self.skip_string('='):
self.pos += 1 self.pos += 1
default = self._parse_default_expr() default = self._parse_default_expr()
@@ -1072,6 +1081,11 @@ class DefinitionParser(object):
self.skip_ws() self.skip_ws()
else: else:
explicit = False explicit = False
if self.skip_word('virtual'):
virtual = True
self.skip_ws()
else:
virtual = False
rv = self._parse_type() rv = self._parse_type()
self.skip_ws() self.skip_ws()
# some things just don't have return values # some things just don't have return values
@@ -1080,12 +1094,27 @@ class DefinitionParser(object):
rv = None rv = None
else: else:
name = self._parse_type() name = self._parse_type()
return FuncDefExpr(name, visibility, static, explicit, rv, return FuncDefExpr(name, visibility, static, explicit, rv,
*self._parse_signature()) *self._parse_signature(), virtual = virtual)
def parse_class(self): def parse_class(self):
visibility, static = self._parse_visibility_static() 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): def read_rest(self):
rv = self.definition[self.pos:] rv = self.definition[self.pos:]
@@ -1212,8 +1241,8 @@ class OCVClassObject(OCVObject):
object_annotation = "class " object_annotation = "class "
object_long_name = "class" object_long_name = "class"
def attach_modifiers(self, node, obj): def attach_modifiers(self, node, obj, skip_visibility = 'public'):
if obj.visibility != 'public': if obj.visibility != skip_visibility:
node += addnodes.desc_annotation(obj.visibility, node += addnodes.desc_annotation(obj.visibility,
obj.visibility) obj.visibility)
node += nodes.Text(' ') node += nodes.Text(' ')
@@ -1231,6 +1260,15 @@ class OCVClassObject(OCVObject):
self.attach_modifiers(signode, cls) self.attach_modifiers(signode, cls)
signode += addnodes.desc_annotation(self.__class__.object_annotation, self.__class__.object_annotation) signode += addnodes.desc_annotation(self.__class__.object_annotation, self.__class__.object_annotation)
self.attach_name(signode, cls.name) 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): class OCVStructObject(OCVClassObject):
object_annotation = "struct " object_annotation = "struct "
@@ -1263,6 +1301,9 @@ class OCVMemberObject(OCVObject):
return '' return ''
def parse_definition(self, parser): 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() return parser.parse_member_object()
def describe_signature(self, signode, obj): def describe_signature(self, signode, obj):
@@ -1298,7 +1339,12 @@ class OCVFunctionObject(OCVObject):
self.attach_type(param, arg.type) self.attach_type(param, arg.type)
param += nodes.Text(u' ') param += nodes.Text(u' ')
#param += nodes.emphasis(unicode(arg.name), unicode(arg.name)) #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: if arg.default is not None:
def_ = u'=' + unicode(arg.default) def_ = u'=' + unicode(arg.default)
#param += nodes.emphasis(def_, def_) #param += nodes.emphasis(def_, def_)
@@ -1325,6 +1371,9 @@ class OCVFunctionObject(OCVObject):
if func.explicit: if func.explicit:
signode += addnodes.desc_annotation('explicit', 'explicit') signode += addnodes.desc_annotation('explicit', 'explicit')
signode += nodes.Text(' ') 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 # return value is None for things with a reverse return value
# such as casting operator definitions or constructors # such as casting operator definitions or constructors
# and destructors. # and destructors.
+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) int is_supported(const char* supp_modes_key, const char* mode)
{ {
const char* supported_modes = params.get(supp_modes_key); 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) 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. 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: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 .. 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. 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. :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: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 .. 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:function:: void convertPointsHomogeneous( InputArray src, OutputArray dst )
.. ocv:pyfunction:: cv2.convertPointsHomogeneous(src[, dst]) -> dst
.. ocv:cfunction:: void cvConvertPointsHomogeneous( const CvMat* src, CvMat* 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. :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: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 .. 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: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 .. ocv:pyoldfunction:: cv.DrawChessboardCorners(image, patternSize, corners, patternWasFound)-> None
:param image: Destination image. It must be an 8-bit color image. :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. 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: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 .. 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. :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: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. :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. 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. :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. 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 .. 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: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: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) -> None .. 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). :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: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>`` . :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. 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: 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. 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` . :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. 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: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. :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 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` . :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: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 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 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. :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: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 .. 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. :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. 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: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 .. ocv:pyoldfunction:: cv.ReprojectImageTo3D(disparity, _3dImage, Q, handleMissingValues=0) -> None
@@ -978,18 +977,18 @@ RQDecomp3x3
--------------- ---------------
Computes an RQ decomposition of 3x3 matrices. 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: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 .. 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. :param Qx: Optional output 3x3 rotation matrix around x-axis.
@@ -1083,11 +1082,11 @@ The constructors.
.. ocv:function:: StereoBM::StereoBM() .. ocv:function:: StereoBM::StereoBM()
.. ocv:function:: StereoBM::StereoBM(int preset, int ndisparities=0, int SADWindowSize=21) .. 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: :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. 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 .. 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 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``. :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: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.?? 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. .. 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 stereoCalibrate
------------------- -------------------
Calibrates the stereo camera. 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: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, termCrit=(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), flags=CV_CALIB_FIX_INTRINSIC)-> None
.. 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. :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. 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: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)
.. 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. :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 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 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: :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: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 .. 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 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. :param H1: Output rectification homography matrix for the first image.
@@ -215,8 +215,7 @@ CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size);
CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size, CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size,
CvPoint2D32f* corners, CvPoint2D32f* corners,
int* corner_count CV_DEFAULT(NULL), int* corner_count CV_DEFAULT(NULL),
int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+ int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) );
CV_CALIB_CB_NORMALIZE_IMAGE) );
/* Draws individual chessboard corners or the whole chessboard detected */ /* Draws individual chessboard corners or the whole chessboard detected */
CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size, CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size,
@@ -469,12 +468,12 @@ enum
{ {
ITERATIVE=CV_ITERATIVE, ITERATIVE=CV_ITERATIVE,
EPNP=CV_EPNP, EPNP=CV_EPNP,
P3P=CV_P3P P3P=CV_P3P
}; };
CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
InputArray cameraMatrix, InputArray distCoeffs, InputArray cameraMatrix, InputArray distCoeffs,
OutputArray rvec, OutputArray tvec, 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. //! computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible.
CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints, CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints,
@@ -488,7 +487,7 @@ CV_EXPORTS_W void solvePnPRansac( InputArray objectPoints,
float reprojectionError = 8.0, float reprojectionError = 8.0,
int minInliersCount = 100, int minInliersCount = 100,
OutputArray inliers = noArray(), OutputArray inliers = noArray(),
int flags = 0); int flags = ITERATIVE);
//! initializes camera matrix from a few 3D points and the corresponding projections. //! initializes camera matrix from a few 3D points and the corresponding projections.
CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
@@ -501,8 +500,7 @@ enum { CALIB_CB_ADAPTIVE_THRESH = 1, CALIB_CB_NORMALIZE_IMAGE = 2,
//! finds checkerboard pattern of the specified size in the image //! finds checkerboard pattern of the specified size in the image
CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize,
OutputArray corners, OutputArray corners,
int flags=CALIB_CB_ADAPTIVE_THRESH+ int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE );
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); CV_EXPORTS bool find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size region_size);
@@ -574,8 +572,7 @@ CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
CV_OUT InputOutputArray distCoeffs2, CV_OUT InputOutputArray distCoeffs2,
Size imageSize, OutputArray R, Size imageSize, OutputArray R,
OutputArray T, OutputArray E, OutputArray F, OutputArray T, OutputArray E, OutputArray F,
TermCriteria criteria = TermCriteria(TermCriteria::COUNT+ TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6),
TermCriteria::EPS, 30, 1e-6),
int flags=CALIB_FIX_INTRINSIC ); int flags=CALIB_FIX_INTRINSIC );
@@ -642,7 +639,7 @@ CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
double param1=3., double param2=0.99); double param1=3., double param2=0.99);
//! finds coordinates of epipolar lines corresponding the specified points //! 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, int whichImage, InputArray F,
OutputArray lines ); OutputArray lines );
@@ -743,9 +740,9 @@ CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
bool handleMissingValues=false, bool handleMissingValues=false,
int ddepth=-1 ); int ddepth=-1 );
CV_EXPORTS_W int estimateAffine3D(InputArray _from, InputArray _to, CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst,
OutputArray _out, OutputArray _inliers, OutputArray out, OutputArray inliers,
double param1=3, double param2=0.99); double ransacThreshold=3, double confidence=0.99);
} }
@@ -75,7 +75,6 @@ void CV_ChessboardDetectorTimingTest::run( int start_from )
sprintf( filepath, "%scameracalibration/", ts->get_data_path().c_str() ); sprintf( filepath, "%scameracalibration/", ts->get_data_path().c_str() );
sprintf( filename, "%schessboard_timing_list.dat", filepath ); sprintf( filename, "%schessboard_timing_list.dat", filepath );
printf("Reading file %s\n", filename);
CvFileStorage* fs = cvOpenFileStorage( filename, 0, CV_STORAGE_READ ); CvFileStorage* fs = cvOpenFileStorage( filename, 0, CV_STORAGE_READ );
CvFileNode* board_list = fs ? cvGetFileNodeByName( fs, 0, "boards" ) : 0; 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. 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 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::SeparateDetectionWork::SeparateDetectionWork(DetectionBasedTracker& _detectionBasedTracker, const std::string& cascadeFilename)
:detectionBasedTracker(_detectionBasedTracker), :detectionBasedTracker(_detectionBasedTracker),
cascadeInThread(cascadeFilename), cascadeInThread(),
isObjectDetectingReady(false), isObjectDetectingReady(false),
shouldObjectDetectingResultsBeForgot(false), shouldObjectDetectingResultsBeForgot(false),
stateThread(STATE_THREAD_STOPPED), stateThread(STATE_THREAD_STOPPED),
timeWhenDetectingThreadStartedWork(-1) timeWhenDetectingThreadStartedWork(-1)
{ {
if(!cascadeInThread.load(cascadeFilename)) {
CV_Error(CV_StsBadArg, "DetectionBasedTracker::SeparateDetectionWork::SeparateDetectionWork: Cannot load a cascade from the file '"+cascadeFilename+"'");
}
int res=0; int res=0;
res=pthread_mutex_init(&mutex, NULL);//TODO: should be attributes? res=pthread_mutex_init(&mutex, NULL);//TODO: should be attributes?
if (res) { if (res) {
@@ -238,6 +241,11 @@ void DetectionBasedTracker::SeparateDetectionWork::workcycleObjectDetector()
CV_Assert(stateThread==STATE_THREAD_WORKING_SLEEPING); CV_Assert(stateThread==STATE_THREAD_WORKING_SLEEPING);
pthread_mutex_lock(&mutex); 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); CV_Assert(stateThread==STATE_THREAD_WORKING_SLEEPING);
pthread_cond_wait(&objectDetectorRun, &mutex); pthread_cond_wait(&objectDetectorRun, &mutex);
if (isWorking()) { if (isWorking()) {
@@ -439,14 +447,17 @@ DetectionBasedTracker::InnerParameters::InnerParameters()
DetectionBasedTracker::DetectionBasedTracker(const std::string& cascadeFilename, const Parameters& params) DetectionBasedTracker::DetectionBasedTracker(const std::string& cascadeFilename, const Parameters& params)
:separateDetectionWork(), :separateDetectionWork(),
innerParameters(), innerParameters(),
numTrackedSteps(0), numTrackedSteps(0)
cascadeForTracking(cascadeFilename)
{ {
CV_Assert( (params.minObjectSize > 0) CV_Assert( (params.minObjectSize > 0)
&& (params.maxObjectSize >= 0) && (params.maxObjectSize >= 0)
&& (params.scaleFactor > 1.0) && (params.scaleFactor > 1.0)
&& (params.maxTrackLifetime >= 0) ); && (params.maxTrackLifetime >= 0) );
if (!cascadeForTracking.load(cascadeFilename)) {
CV_Error(CV_StsBadArg, "DetectionBasedTracker::DetectionBasedTracker: Cannot load a cascade from the file '"+cascadeFilename+"'");
}
parameters=params; parameters=params;
separateDetectionWork=new SeparateDetectionWork(*this, cascadeFilename); 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); 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 W = _W.getMat();
Mat mean = _mean.getMat(); Mat mean = _mean.getMat();
Mat src = _src.getMat(); Mat src = _src.getMat();
// get number of samples and dimension // get number of samples
int n = src.rows; int n = src.rows;
int d = src.cols;
// initalize temporary matrices // initalize temporary matrices
Mat X, Y; Mat X, Y;
// copy data & make sure we are using the correct type // copy data & make sure we are using the correct type
src.convertTo(Y, W.type()); src.convertTo(Y, W.type());
// calculate the reconstruction // calculate the reconstruction
gemm(Y, gemm(Y, W, 1.0, Mat(), 0.0, X, GEMM_2_T);
W, if(mean.total() == (size_t) X.cols)
1.0, add(X, repeat(mean.reshape(1,1), n, 1), X);
((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);
return X; return X;
} }
+51 -67
View File
@@ -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 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. :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:: Rect RotatedRect::boundingRect() const
.. ocv:function:: RotatedRect::operator CvBox2D() const .. ocv:function:: RotatedRect::operator CvBox2D() const
@@ -797,7 +797,7 @@ Various Mat constructors
.. ocv:function:: Mat::Mat(Size size, 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 Mat& m, const Rect& roi)
@@ -811,8 +811,6 @@ Various Mat constructors
.. ocv:function:: template<typename T> explicit Mat::Mat(const vector<T>& vec, bool copyData=false) .. 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)
.. 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, const Scalar& s)
@@ -857,8 +855,6 @@ Various Mat constructors
:param ranges: Array of selected ranges of ``m`` along each dimensionality. :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`, 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 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. :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 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) .. 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. 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 Mat::row
------------ ------------
Creates a matrix header for the specified matrix 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: :: 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. 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 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. :ocv:func:`Mat::row` description.
@@ -988,11 +974,11 @@ Mat::diag
------------- -------------
Extracts a diagonal from a matrix, or creates a diagonal matrix. 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. * **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. * **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 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::row` and
:ocv:func:`Mat::col` , this is an O(1) operation. :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. 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. :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(int rows, int cols, int type)
.. ocv:function:: static MatExpr Mat::zeros(Size size, 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. :param ndims: Array dimensionality.
@@ -1199,7 +1183,7 @@ Returns a zero array of the specified size and type.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` . :param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sizes: Array of integers specifying the array shape. :param sz: Array of integers specifying the array shape.
:param type: Created matrix type. :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(int rows, int cols, int type)
.. ocv:function:: static MatExpr Mat::ones(Size size, 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. :param ndims: Array dimensionality.
@@ -1228,7 +1212,7 @@ Returns an array of all 1's of the specified size and type.
:param size: Alternative to the matrix size specification ``Size(cols, rows)`` . :param size: Alternative to the matrix size specification ``Size(cols, rows)`` .
:param sizes: Array of integers specifying the array shape. :param sz: Array of integers specifying the array shape.
:param type: Created matrix type. :param type: Created matrix type.
@@ -1367,7 +1351,8 @@ Mat::push_back
Adds elements to the bottom of the matrix. Adds elements to the bottom of the matrix.
.. ocv:function:: template<typename T> void Mat::push_back(const T& elem) .. 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). :param elem: Added element(s).
@@ -1439,7 +1424,7 @@ Extracts a rectangular submatrix.
.. ocv:function:: Mat Mat::operator()( const Rect& roi ) const .. 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 rowRange: Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use ``Range::all()``.
@@ -1626,7 +1611,7 @@ Mat::step1
-------------- --------------
Returns a normalized step. 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 The method returns a matrix step divided by
:ocv:func:`Mat::elemSize1()` . It can be useful to quickly access an arbitrary matrix element. :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. 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 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. :ocv:func:`Mat::isContinuous` to know how to use these methods.
@@ -1816,6 +1801,7 @@ To use ``Mat_`` for multi-channel images/matrices, pass ``Vec`` as a ``Mat_`` pa
InputArray InputArray
---------- ----------
.. ocv:class:: InputArray
This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as :: This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as ::
@@ -1880,6 +1866,7 @@ It denotes function arguments that are either vectors of vectors or vectors of m
OutputArray 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. 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.
@@ -2310,6 +2297,7 @@ It simplifies notation of some operations. ::
Algorithm 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.). 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.).
@@ -2324,6 +2312,7 @@ The class provides the following features for all derived classes:
Here is example of SIFT use in your application via Algorithm interface: :: Here is example of SIFT use in your application via Algorithm interface: ::
#include "opencv2/opencv.hpp" #include "opencv2/opencv.hpp"
#include "opencv2/nonfree/nonfree.hpp"
... ...
@@ -2334,29 +2323,29 @@ Here is example of SIFT use in your application via Algorithm interface: ::
FileStorage fs("sift_params.xml", FileStorage::READ); FileStorage fs("sift_params.xml", FileStorage::READ);
if( fs.isOpened() ) // if we have file with parameters, read them if( fs.isOpened() ) // if we have file with parameters, read them
{ {
sift.read(fs["sift_params"]); sift->read(fs["sift_params"]);
fs.release(); fs.release();
} }
else // else modify the parameters and store them; user can later edit the file to use different parameters 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); WriteStructContext ws(fs, "sift_params", CV_NODE_MAP);
sift.write(fs); sift->write(fs);
} }
} }
Mat image = imread("myimage.png", 0), descriptors; Mat image = imread("myimage.png", 0), descriptors;
vector<KeyPoint> keypoints; vector<KeyPoint> keypoints;
sift(image, noArray(), keypoints, descriptors); (*sift)(image, noArray(), keypoints, descriptors);
Algorithm::get Algorithm::get
-------------- --------------
Returns the algorithm parameter 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. :param name: The parameter name.
@@ -2377,13 +2366,13 @@ Algorithm::set
-------------- --------------
Sets the algorithm parameter Sets the algorithm parameter
.. ocv:function:: void set(const string& name, int value) .. ocv:function:: void Algorithm::set(const string& name, int value)
.. ocv:function:: void set(const string& name, double value) .. ocv:function:: void Algorithm::set(const string& name, double value)
.. ocv:function:: void set(const string& name, bool value) .. ocv:function:: void Algorithm::set(const string& name, bool value)
.. ocv:function:: void set(const string& name, const string& value) .. ocv:function:: void Algorithm::set(const string& name, const string& value)
.. ocv:function:: void set(const string& name, const Mat& value) .. ocv:function:: void Algorithm::set(const string& name, const Mat& value)
.. ocv:function:: void set(const string& name, const vector<Mat>& value) .. ocv:function:: void Algorithm::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, const Ptr<Algorithm>& value)
:param name: The parameter name. :param name: The parameter name.
:param value: The parameter value. :param value: The parameter value.
@@ -2395,7 +2384,7 @@ Algorithm::write
---------------- ----------------
Stores algorithm parameters in a file storage 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. :param fs: File storage.
@@ -2412,7 +2401,7 @@ Algorithm::read
--------------- ---------------
Reads algorithm parameters from a file storage 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. :param fn: File node of the file storage.
@@ -2422,29 +2411,24 @@ Algorithm::getList
------------------ ------------------
Returns the list of registered algorithms 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. :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 ::
vector<string> algorithms;
Algorithm::getList Algorithm::getList(algorithms);
------------------ cout << "Algorithms: " << algorithms.size() << endl;
Returns the list of registered algorithms for (size_t i=0; i < algorithms.size(); i++)
cout << algorithms[i] << endl;
.. 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.
Algorithm::create Algorithm::create
----------------- -----------------
Creates algorithm instance by name 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()``. :param name: The algorithm name, one of the names returned by ``Algorithm::getList()``.
+5 -5
View File
@@ -7,17 +7,17 @@ kmeans
------ ------
Finds centers of clusters and groups input samples around the clusters. 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: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 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. :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. :param compactness: The returned value that is described below.
The function ``kmeans`` implements a k-means algorithm that finds the 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, around the clusters. As an output,
:math:`\texttt{labels}_i` contains a 0-based cluster index for :math:`\texttt{labels}_i` contains a 0-based cluster index for
the sample stored in the the sample stored in the
+117 -26
View File
@@ -30,11 +30,12 @@ circle
---------- ----------
Draws a 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: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 .. ocv:pyoldfunction:: cv.Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image where the circle is drawn. :param img: Image where the circle is drawn.
@@ -63,8 +64,9 @@ Clips the line against the image rectangle.
.. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2 .. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2
.. ocv:cfunction:: int cvClipLine( CvSize imgSize, CvPoint* pt1, CvPoint* pt2 ) .. ocv:cfunction:: int cvClipLine( CvSize img_size, CvPoint* pt1, CvPoint* pt2 )
.. ocv:pyoldfunction:: cv.ClipLine(imgSize, pt1, pt2) -> (clippedPt1, clippedPt2)
.. 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 imgSize: Image size. The image rectangle is ``Rect(0, 0, imgSize.width, imgSize.height)`` .
@@ -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, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:pyfunction:: cv2.ellipse(img, box, color[, thickness[, lineType]]) -> 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: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, startAngle, endAngle, color, thickness=1, lineType=8, shift=0)-> None
.. 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 .. ocv:pyoldfunction:: cv.EllipseBox(img, box, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image. :param img: Image.
@@ -130,7 +134,7 @@ ellipse2Poly
---------------- ----------------
Approximates an elliptic arc with a polyline. 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 .. ocv:pyfunction:: cv2.ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta) -> pts
@@ -140,9 +144,9 @@ Approximates an elliptic arc with a polyline.
:param angle: Rotation angle of the ellipse in degrees. 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 arcStart: Starting angle of the elliptic arc in degrees.
:param endAngle: Ending 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. :param delta: Angle between the subsequent polyline vertices. It defines the approximation accuracy.
@@ -157,11 +161,12 @@ fillConvexPoly
------------------ ------------------
Fills a convex polygon. 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: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 .. ocv:pyoldfunction:: cv.FillConvexPoly(img, pn, color, lineType=8, shift=0)-> None
:param img: Image. :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: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 .. ocv:pyoldfunction:: cv.FillPoly(img, polys, color, lineType=8, shift=0)-> None
:param img: Image. :param img: Image.
@@ -218,11 +224,12 @@ getTextSize
--------------- ---------------
Calculates the width and height of a text string. 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: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) .. ocv:pyoldfunction:: cv.GetTextSize(textString, font)-> (textSize, baseline)
:param text: Input text string. :param text: Input text string.
@@ -273,11 +280,11 @@ InitFont
-------- --------
Initializes font structure (OpenCV 1.x API). 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
@@ -310,7 +317,7 @@ Initializes font structure (OpenCV 1.x API).
: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. The function initializes the font structure that can be passed to text rendering functions.
@@ -327,7 +334,8 @@ Draws a line segment connecting two points.
.. ocv:pyfunction:: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None .. 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 .. ocv:pyoldfunction:: cv.Line(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image. :param img: Image.
@@ -402,13 +410,14 @@ rectangle
------------- -------------
Draws a simple, thick, or filled up-right 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: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 .. ocv:pyoldfunction:: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image. :param img: Image.
@@ -417,7 +426,7 @@ Draws a simple, thick, or filled up-right rectangle.
:param pt2: Vertex of the rectangle opposite to ``pt1`` . :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). :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: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. :param img: Image.
@@ -464,6 +473,88 @@ Draws several polygonal curves.
The function ``polylines`` draws one or more 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 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: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: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 .. ocv:pyoldfunction:: cv.PutText(img, text, org, font, color)-> None
+67 -66
View File
@@ -10,27 +10,27 @@ CvMemStorage
.. ocv:struct:: 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 - 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 ``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 .. 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_prev
.. ocv:member:: CvSeq* h_next .. ocv:member:: CvSeq* h_next
.. ocv:member:: CvSeq* v_prev .. ocv:member:: CvSeq* v_prev
.. ocv:member:: CvSeq* v_next .. 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. 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 There are two types of sequences - dense and sparse. The base type for dense
@@ -228,9 +228,9 @@ ClearSet
-------- --------
Clears a set. 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. The function removes all elements from set. It has O(1) time complexity.
@@ -362,11 +362,12 @@ CreateMemStorage
---------------- ----------------
Creates memory storage. 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 .. 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 The function creates an empty memory storage. See
:ocv:struct:`CvMemStorage` :ocv:struct:`CvMemStorage`
@@ -376,14 +377,14 @@ CreateSeq
--------- ---------
Creates a sequence. 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 :param storage: Sequence location
@@ -480,13 +481,13 @@ FindGraphEdgeByPtr
------------------ ------------------
Finds an edge in a graph by using its pointer. 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 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. 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 :param seq: Sequence
@@ -587,9 +588,9 @@ GetSetElem
---------- ----------
Finds a set element by its index. 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 :param index: Index of the set element within a sequence
@@ -723,11 +724,11 @@ GraphVtxDegree
-------------- --------------
Counts the number of edges incident to the vertex. 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 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: 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. 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 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 :param element: Inserted element
@@ -1037,13 +1038,13 @@ SeqInsertSlice
-------------- --------------
Inserts an array in the middle of a sequence. 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 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 The function inserts all
``fromArr`` ``fromArr``
@@ -1109,7 +1110,7 @@ SeqPush
------- -------
Adds an element to the end of a sequence. 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 :param seq: Sequence
@@ -1149,7 +1150,7 @@ SeqPushFront
------------ ------------
Adds an element to the beginning of a sequence. 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 :param seq: Sequence
@@ -1163,7 +1164,7 @@ SeqPushMulti
------------ ------------
Pushes several elements to either end of a sequence. 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 :param seq: Sequence
@@ -1216,7 +1217,7 @@ SeqSearch
--------- ---------
Searches for an element in a sequence. 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 :param seq: The sequence
@@ -1325,9 +1326,9 @@ SetAdd
------ ------
Occupies a node in the set. 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). :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). 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 The function is an inline lightweight variant of
:ocv:cfunc:`SetAdd` :ocv:cfunc:`SetAdd`
@@ -1358,9 +1359,9 @@ SetRemove
--------- ---------
Removes an element from a set. 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 :param index: Index of the removed element
@@ -1375,9 +1376,9 @@ SetRemoveByPtr
-------------- --------------
Removes a set element based on its pointer. 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 :param elem: Removed element
@@ -1389,23 +1390,23 @@ SetSeqBlockSize
--------------- ---------------
Sets up sequence block size. 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 seq: Sequence
:param deltaElems: Desirable sequence block size for elements :param delta_elems: Desirable sequence block size for elements
The function affects memory allocation The function affects memory allocation
granularity. When the free space in the sequence buffers has run out, granularity. When the free space in the sequence buffers has run out,
the function allocates the space for the function allocates the space for
``deltaElems`` ``delta_elems``
sequence sequence
elements. If this block immediately follows the one previously allocated, elements. If this block immediately follows the one previously allocated,
the two blocks are concatenated; otherwise, a new sequence block is the two blocks are concatenated; otherwise, a new sequence block is
created. Therefore, the bigger the parameter is, the lower the possible created. Therefore, the bigger the parameter is, the lower the possible
sequence fragmentation, but the more space in the storage block is wasted. When sequence fragmentation, but the more space in the storage block is wasted. When
the sequence is created, the parameter the sequence is created, the parameter
``deltaElems`` ``delta_elems``
is set to is set to
the default value of about 1K. The function can be called any time after the default value of about 1K. The function can be called any time after
the sequence is created and affects future allocations. The function the sequence is created and affects future allocations. The function
+234 -227
View File
@@ -10,21 +10,21 @@ CvPoint
.. ocv:struct:: CvPoint .. ocv:struct:: CvPoint
2D point with integer coordinates (usually zero-based). 2D point with integer coordinates (usually zero-based).
.. ocv:member:: int x .. ocv:member:: int x
x-coordinate x-coordinate
.. ocv:member:: int y .. ocv:member:: int y
y-coordinate y-coordinate
.. ocv:cfunction:: CvPoint cvPoint( int x, int y ) .. ocv:cfunction:: CvPoint cvPoint( int x, int y )
constructs ``CvPoint`` structure. constructs ``CvPoint`` structure.
.. ocv:cfunction:: CvPoint cvPointFrom32f( CvPoint32f pt ) .. ocv:cfunction:: CvPoint cvPointFrom32f( CvPoint2D32f point )
converts ``CvPoint2D32f`` to ``CvPoint``. converts ``CvPoint2D32f`` to ``CvPoint``.
@@ -35,21 +35,21 @@ CvPoint2D32f
.. ocv:struct:: CvPoint2D32f .. ocv:struct:: CvPoint2D32f
2D point with floating-point coordinates. 2D point with floating-point coordinates.
.. ocv:member:: float x .. ocv:member:: float x
x-coordinate x-coordinate
.. ocv:member:: float y .. ocv:member:: float y
y-coordinate y-coordinate
.. ocv:cfunction:: CvPoint2D32f cvPoint2D32f( float x, float y ) .. ocv:cfunction:: CvPoint2D32f cvPoint2D32f( double x, double y )
constructs ``CvPoint2D32f`` structure. constructs ``CvPoint2D32f`` structure.
.. ocv:cfunction:: CvPoint2D32f cvPointTo32f( CvPoint pt ) .. ocv:cfunction:: CvPoint2D32f cvPointTo32f( CvPoint point )
converts ``CvPoint`` to ``CvPoint2D32f``. converts ``CvPoint`` to ``CvPoint2D32f``.
@@ -60,21 +60,21 @@ CvPoint3D32f
.. ocv:struct:: CvPoint3D32f .. ocv:struct:: CvPoint3D32f
3D point with floating-point coordinates 3D point with floating-point coordinates
.. ocv:member:: float x .. ocv:member:: float x
x-coordinate x-coordinate
.. ocv:member:: float y .. ocv:member:: float y
y-coordinate y-coordinate
.. ocv:member:: float z .. ocv:member:: float z
z-coordinate z-coordinate
.. ocv:cfunction:: CvPoint3D32f cvPoint3D32f( float x, float y, float z ) .. ocv:cfunction:: CvPoint3D32f cvPoint3D32f( double x, double y, double z )
constructs ``CvPoint3D32f`` structure. constructs ``CvPoint3D32f`` structure.
@@ -85,15 +85,15 @@ CvPoint2D64f
.. ocv:struct:: CvPoint2D64f .. ocv:struct:: CvPoint2D64f
2D point with double-precision floating-point coordinates. 2D point with double-precision floating-point coordinates.
.. ocv:member:: double x .. ocv:member:: double x
x-coordinate x-coordinate
.. ocv:member:: double y .. ocv:member:: double y
y-coordinate y-coordinate
.. ocv:cfunction:: CvPoint2D64f cvPoint2D64f( double x, double y ) .. ocv:cfunction:: CvPoint2D64f cvPoint2D64f( double x, double y )
@@ -106,17 +106,17 @@ CvPoint3D64f
.. ocv:struct:: CvPoint3D64f .. ocv:struct:: CvPoint3D64f
3D point with double-precision floating-point coordinates. 3D point with double-precision floating-point coordinates.
.. ocv:member:: double x .. ocv:member:: double x
x-coordinate x-coordinate
.. ocv:member:: double y .. ocv:member:: double y
y-coordinate y-coordinate
.. ocv:member:: double z .. ocv:member:: double z
.. ocv:cfunction:: CvPoint3D64f cvPoint3D64f( double x, double y, double z ) .. ocv:cfunction:: CvPoint3D64f cvPoint3D64f( double x, double y, double z )
@@ -129,15 +129,15 @@ CvSize
.. ocv:struct:: CvSize .. ocv:struct:: CvSize
Size of a rectangle or an image. Size of a rectangle or an image.
.. ocv:member:: int width .. ocv:member:: int width
Width of the rectangle Width of the rectangle
.. ocv:member:: int height .. ocv:member:: int height
Height of the rectangle Height of the rectangle
.. ocv:cfunction:: CvSize cvSize( int width, int height ) .. ocv:cfunction:: CvSize cvSize( int width, int height )
@@ -150,17 +150,17 @@ CvSize2D32f
.. ocv:struct:: CvSize2D32f .. ocv:struct:: CvSize2D32f
Sub-pixel accurate size of a rectangle. Sub-pixel accurate size of a rectangle.
.. ocv:member:: float width .. ocv:member:: float width
Width of the rectangle Width of the rectangle
.. ocv:member:: float height .. ocv:member:: float height
Height of the rectangle Height of the rectangle
.. ocv:cfunction:: CvSize2D32f cvSize2D23f( float width, float height ) .. ocv:cfunction:: CvSize2D32f cvSize2D32f( double width, double height )
constructs ``CvSize2D32f`` structure. constructs ``CvSize2D32f`` structure.
@@ -171,23 +171,23 @@ CvRect
.. ocv:struct:: CvRect .. ocv:struct:: CvRect
Stores coordinates of a rectangle. Stores coordinates of a rectangle.
.. ocv:member:: int x .. ocv:member:: int x
x-coordinate of the top-left corner x-coordinate of the top-left corner
.. ocv:member:: int y .. ocv:member:: int y
y-coordinate of the top-left corner (sometimes bottom-left corner) y-coordinate of the top-left corner (sometimes bottom-left corner)
.. ocv:member:: int width .. ocv:member:: int width
Width of the rectangle Width of the rectangle
.. ocv:member:: int height .. ocv:member:: int height
Height of the rectangle Height of the rectangle
.. ocv:cfunction:: CvRect cvRect( int x, int y, int width, int height ) .. ocv:cfunction:: CvRect cvRect( int x, int y, int width, int height )
@@ -197,23 +197,23 @@ Stores coordinates of a rectangle.
CvBox2D CvBox2D
------ -------
.. ocv:struct:: CvBox2D .. ocv:struct:: CvBox2D
Stores coordinates of a rotated rectangle. Stores coordinates of a rotated rectangle.
.. ocv:member:: CvPoint2D32f center .. ocv:member:: CvPoint2D32f center
Center of the box Center of the box
.. ocv:member:: CvSize2D32f size .. ocv:member:: CvSize2D32f size
Box width and height Box width and height
.. ocv:member:: float angle .. ocv:member:: float angle
Angle between the horizontal axis and the first side (i.e. length) in degrees Angle between the horizontal axis and the first side (i.e. length) in degrees
.. seealso:: :ocv:class:`RotatedRect` .. seealso:: :ocv:class:`RotatedRect`
@@ -223,9 +223,9 @@ CvScalar
.. ocv:struct:: CvScalar .. ocv:struct:: CvScalar
A container for 1-,2-,3- or 4-tuples of doubles. A container for 1-,2-,3- or 4-tuples of doubles.
.. ocv:member:: double[4] val .. ocv:member:: double[4] val
.. ocv::cfunction:: CvScalar cvScalar( double val0, double val1=0, double val2=0, double val3=0 ) .. ocv::cfunction:: CvScalar cvScalar( double val0, double val1=0, double val2=0, double val3=0 )
@@ -246,25 +246,25 @@ CvTermCriteria
.. ocv:struct:: CvTermCriteria .. ocv:struct:: CvTermCriteria
Termination criteria for iterative algorithms. Termination criteria for iterative algorithms.
.. ocv:member:: int type .. ocv:member:: int type
type of the termination criteria, one of: type of the termination criteria, one of:
* ``CV_TERMCRIT_ITER`` - stop the algorithm after ``max_iter`` iterations at maximum. * ``CV_TERMCRIT_ITER`` - stop the algorithm after ``max_iter`` iterations at maximum.
* ``CV_TERMCRIT_EPS`` - stop the algorithm after the achieved algorithm-dependent accuracy becomes lower than ``epsilon``. * ``CV_TERMCRIT_EPS`` - stop the algorithm after the achieved algorithm-dependent accuracy becomes lower than ``epsilon``.
* ``CV_TERMCRIT_ITER+CV_TERMCRIT_EPS`` - stop the algorithm after ``max_iter`` iterations or when the achieved accuracy is lower than ``epsilon``, whichever comes the earliest. * ``CV_TERMCRIT_ITER+CV_TERMCRIT_EPS`` - stop the algorithm after ``max_iter`` iterations or when the achieved accuracy is lower than ``epsilon``, whichever comes the earliest.
.. ocv:member:: int max_iter .. ocv:member:: int max_iter
Maximum number of iterations Maximum number of iterations
.. ocv:member:: double epsilon .. ocv:member:: double epsilon
Required accuracy Required accuracy
.. seealso:: :ocv:class:`TermCriteria` .. seealso:: :ocv:class:`TermCriteria`
@@ -273,41 +273,41 @@ CvMat
.. ocv:struct:: CvMat .. ocv:struct:: CvMat
A multi-channel dense matrix. A multi-channel dense matrix.
.. ocv:member:: int type .. ocv:member:: int type
``CvMat`` signature (``CV_MAT_MAGIC_VAL``) plus type of the elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: :: ``CvMat`` signature (``CV_MAT_MAGIC_VAL``) plus type of the elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: ::
int type = CV_MAT_TYPE(matrix->type); int type = CV_MAT_TYPE(matrix->type);
For description of possible matrix elements, see :ocv:class:`Mat`. For description of possible matrix elements, see :ocv:class:`Mat`.
.. ocv:member:: int step .. ocv:member:: int step
Full row length in bytes Full row length in bytes
.. ocv:member:: int* refcount .. ocv:member:: int* refcount
Underlying data reference counter Underlying data reference counter
.. ocv:member:: union data .. ocv:member:: union data
Pointers to the actual matrix data: Pointers to the actual matrix data:
* ptr - pointer to 8-bit unsigned elements * ptr - pointer to 8-bit unsigned elements
* s - pointer to 16-bit signed elements * s - pointer to 16-bit signed elements
* i - pointer to 32-bit signed elements * i - pointer to 32-bit signed elements
* fl - pointer to 32-bit floating-point elements * fl - pointer to 32-bit floating-point elements
* db - pointer to 64-bit floating-point elements * db - pointer to 64-bit floating-point elements
.. ocv:member:: int rows .. ocv:member:: int rows
Number of rows Number of rows
.. ocv:member:: int cols .. ocv:member:: int cols
Number of columns Number of columns
Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column index) of a matrix can be retrieved or modified using ``CV_MAT_ELEM`` macro: :: Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column index) of a matrix can be retrieved or modified using ``CV_MAT_ELEM`` macro: ::
@@ -323,38 +323,38 @@ CvMatND
.. ocv:struct:: CvMatND .. ocv:struct:: CvMatND
Multi-dimensional dense multi-channel array. Multi-dimensional dense multi-channel array.
.. ocv:member:: int type .. ocv:member:: int type
A ``CvMatND`` signature (``CV_MATND_MAGIC_VAL``) plus the type of elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: :: A ``CvMatND`` signature (``CV_MATND_MAGIC_VAL``) plus the type of elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: ::
int type = CV_MAT_TYPE(ndmatrix->type); int type = CV_MAT_TYPE(ndmatrix->type);
.. ocv:member:: int dims .. ocv:member:: int dims
The number of array dimensions The number of array dimensions
.. ocv:member:: int* refcount .. ocv:member:: int* refcount
Underlying data reference counter Underlying data reference counter
.. ocv:member:: union data .. ocv:member:: union data
Pointers to the actual matrix data Pointers to the actual matrix data
* ptr - pointer to 8-bit unsigned elements * ptr - pointer to 8-bit unsigned elements
* s - pointer to 16-bit signed elements * s - pointer to 16-bit signed elements
* i - pointer to 32-bit signed elements * i - pointer to 32-bit signed elements
* fl - pointer to 32-bit floating-point elements * fl - pointer to 32-bit floating-point elements
* db - pointer to 64-bit floating-point elements * db - pointer to 64-bit floating-point elements
.. ocv:member:: array dim .. ocv:member:: array dim
Arrays of pairs (array size along the i-th dimension, distance between neighbor elements along i-th dimension): :: Arrays of pairs (array size along the i-th dimension, distance between neighbor elements along i-th dimension): ::
for(int i = 0; i < ndmatrix->dims; i++) for(int i = 0; i < ndmatrix->dims; i++)
printf("size[i] = %d, step[i] = %d\n", ndmatrix->dim[i].size, ndmatrix->dim[i].step); printf("size[i] = %d, step[i] = %d\n", ndmatrix->dim[i].size, ndmatrix->dim[i].step);
``CvMatND`` is now obsolete; consider using :ocv:class:`Mat` instead. ``CvMatND`` is now obsolete; consider using :ocv:class:`Mat` instead.
@@ -363,138 +363,138 @@ CvSparseMat
.. ocv:struct:: CvSparseMat .. ocv:struct:: CvSparseMat
Multi-dimensional sparse multi-channel array. Multi-dimensional sparse multi-channel array.
.. ocv:member:: int type .. ocv:member:: int type
A ``CvSparseMat`` signature (CV_SPARSE_MAT_MAGIC_VAL) plus the type of sparse matrix elements. Similarly to ``CvMat`` and ``CvMatND``, use ``CV_MAT_TYPE()`` to retrieve type of the elements. A ``CvSparseMat`` signature (CV_SPARSE_MAT_MAGIC_VAL) plus the type of sparse matrix elements. Similarly to ``CvMat`` and ``CvMatND``, use ``CV_MAT_TYPE()`` to retrieve type of the elements.
.. ocv:member:: int dims .. ocv:member:: int dims
Number of dimensions Number of dimensions
.. ocv:member:: int* refcount .. ocv:member:: int* refcount
Underlying reference counter. Not used. Underlying reference counter. Not used.
.. ocv:member:: CvSet* heap .. ocv:member:: CvSet* heap
A pool of hash table nodes A pool of hash table nodes
.. ocv:member:: void** hashtable .. ocv:member:: void** hashtable
The hash table. Each entry is a list of nodes. The hash table. Each entry is a list of nodes.
.. ocv:member:: int hashsize .. ocv:member:: int hashsize
Size of the hash table Size of the hash table
.. ocv:member:: int[] size .. ocv:member:: int[] size
Array of dimension sizes Array of dimension sizes
IplImage IplImage
-------- --------
.. ocv:struct:: IplImage .. ocv:struct:: IplImage
IPL image header IPL image header
.. ocv:member:: int nSize .. ocv:member:: int nSize
``sizeof(IplImage)`` ``sizeof(IplImage)``
.. ocv:member:: int ID .. ocv:member:: int ID
Version, always equals 0 Version, always equals 0
.. ocv:member:: int nChannels .. ocv:member:: int nChannels
Number of channels. Most OpenCV functions support 1-4 channels. Number of channels. Most OpenCV functions support 1-4 channels.
.. ocv:member:: int alphaChannel .. ocv:member:: int alphaChannel
Ignored by OpenCV Ignored by OpenCV
.. ocv:member:: int depth .. ocv:member:: int depth
Channel depth in bits + the optional sign bit ( ``IPL_DEPTH_SIGN`` ). The supported depths are: Channel depth in bits + the optional sign bit ( ``IPL_DEPTH_SIGN`` ). The supported depths are:
* ``IPL_DEPTH_8U`` - unsigned 8-bit integer. Equivalent to ``CV_8U`` in matrix types. * ``IPL_DEPTH_8U`` - unsigned 8-bit integer. Equivalent to ``CV_8U`` in matrix types.
* ``IPL_DEPTH_8S`` - signed 8-bit integer. Equivalent to ``CV_8S`` in matrix types. * ``IPL_DEPTH_8S`` - signed 8-bit integer. Equivalent to ``CV_8S`` in matrix types.
* ``IPL_DEPTH_16U`` - unsigned 16-bit integer. Equivalent to ``CV_16U`` in matrix types. * ``IPL_DEPTH_16U`` - unsigned 16-bit integer. Equivalent to ``CV_16U`` in matrix types.
* ``IPL_DEPTH_16S`` - signed 8-bit integer. Equivalent to ``CV_16S`` in matrix types. * ``IPL_DEPTH_16S`` - signed 8-bit integer. Equivalent to ``CV_16S`` in matrix types.
* ``IPL_DEPTH_32S`` - signed 32-bit integer. Equivalent to ``CV_32S`` in matrix types. * ``IPL_DEPTH_32S`` - signed 32-bit integer. Equivalent to ``CV_32S`` in matrix types.
* ``IPL_DEPTH_32F`` - single-precision floating-point number. Equivalent to ``CV_32F`` in matrix types. * ``IPL_DEPTH_32F`` - single-precision floating-point number. Equivalent to ``CV_32F`` in matrix types.
* ``IPL_DEPTH_64F`` - double-precision floating-point number. Equivalent to ``CV_64F`` in matrix types. * ``IPL_DEPTH_64F`` - double-precision floating-point number. Equivalent to ``CV_64F`` in matrix types.
.. ocv:member:: char[] colorModel .. ocv:member:: char[] colorModel
Ignored by OpenCV. Ignored by OpenCV.
.. ocv:member:: char[] channelSeq .. ocv:member:: char[] channelSeq
Ignored by OpenCV Ignored by OpenCV
.. ocv:member:: int dataOrder .. ocv:member:: int dataOrder
0 = ``IPL_DATA_ORDER_PIXEL`` - interleaved color channels, 1 - separate color channels. :ocv:cfunc:`CreateImage` only creates images with interleaved channels. For example, the usual layout of a color image is: :math:`b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...` 0 = ``IPL_DATA_ORDER_PIXEL`` - interleaved color channels, 1 - separate color channels. :ocv:cfunc:`CreateImage` only creates images with interleaved channels. For example, the usual layout of a color image is: :math:`b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...`
.. ocv:member:: int origin .. ocv:member:: int origin
0 - top-left origin, 1 - bottom-left origin (Windows bitmap style) 0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)
.. ocv:member:: int align .. ocv:member:: int align
Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead. Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead.
.. ocv:member:: int width .. ocv:member:: int width
Image width in pixels Image width in pixels
.. ocv:member:: int height .. ocv:member:: int height
Image height in pixels Image height in pixels
.. ocv:member:: IplROI* roi .. ocv:member:: IplROI* roi
Region Of Interest (ROI). If not NULL, only this image region will be processed. Region Of Interest (ROI). If not NULL, only this image region will be processed.
.. ocv:member:: IplImage* maskROI .. ocv:member:: IplImage* maskROI
Must be NULL in OpenCV Must be NULL in OpenCV
.. ocv:member:: void* imageId .. ocv:member:: void* imageId
Must be NULL in OpenCV Must be NULL in OpenCV
.. ocv:member:: void* tileInfo .. ocv:member:: void* tileInfo
Must be NULL in OpenCV Must be NULL in OpenCV
.. ocv:member:: int imageSize .. ocv:member:: int imageSize
Image data size in bytes. For interleaved data, this equals :math:`\texttt{image->height} \cdot \texttt{image->widthStep}` Image data size in bytes. For interleaved data, this equals :math:`\texttt{image->height} \cdot \texttt{image->widthStep}`
.. ocv:member:: char* imageData .. ocv:member:: char* imageData
A pointer to the aligned image data. Do not assign imageData directly. Use :ocv:cfunc:`SetData`. A pointer to the aligned image data. Do not assign imageData directly. Use :ocv:cfunc:`SetData`.
.. ocv:member:: int widthStep .. ocv:member:: int widthStep
The size of an aligned image row, in bytes. The size of an aligned image row, in bytes.
.. ocv:member:: int[] BorderMode .. ocv:member:: int[] BorderMode
Border completion mode, ignored by OpenCV Border completion mode, ignored by OpenCV
.. ocv:member:: int[] BorderConst .. ocv:member:: int[] BorderConst
Constant border value, ignored by OpenCV Constant border value, ignored by OpenCV
.. ocv:member:: char* imageDataOrigin .. ocv:member:: char* imageDataOrigin
A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation. A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation.
The ``IplImage`` is taken from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible ``IplImage`` formats, as outlined in the parameter list above. The ``IplImage`` is taken from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible ``IplImage`` formats, as outlined in the parameter list above.
@@ -511,7 +511,8 @@ ClearND
------- -------
Clears a specific array element. Clears a specific array element.
.. ocv:cfunction:: void cvClearND(CvArr* arr, int* idx) .. ocv:cfunction:: void cvClearND( CvArr* arr, const int* idx )
.. ocv:pyoldfunction:: cv.ClearND(arr, idx)-> None .. ocv:pyoldfunction:: cv.ClearND(arr, idx)-> None
:param arr: Input array :param arr: Input array
@@ -524,7 +525,7 @@ CloneImage
Makes a full copy of an image, including the header, data, and ROI. Makes a full copy of an image, including the header, data, and ROI.
.. ocv:cfunction:: IplImage* cvCloneImage(const IplImage* image) .. ocv:cfunction:: IplImage* cvCloneImage(const IplImage* image)
.. ocv:pyoldfunction:: cv.CloneImage(image)-> copy .. ocv:pyoldfunction:: cv.CloneImage(image) -> image
:param image: The original image :param image: The original image
@@ -533,7 +534,7 @@ CloneMat
Creates a full matrix copy. Creates a full matrix copy.
.. ocv:cfunction:: CvMat* cvCloneMat(const CvMat* mat) .. ocv:cfunction:: CvMat* cvCloneMat(const CvMat* mat)
.. ocv:pyoldfunction:: cv.CloneMat(mat)-> copy .. ocv:pyoldfunction:: cv.CloneMat(mat) -> mat
:param mat: Matrix to be copied :param mat: Matrix to be copied
@@ -544,7 +545,7 @@ CloneMatND
Creates full copy of a multi-dimensional array and returns a pointer to the copy. Creates full copy of a multi-dimensional array and returns a pointer to the copy.
.. ocv:cfunction:: CvMatND* cvCloneMatND(const CvMatND* mat) .. ocv:cfunction:: CvMatND* cvCloneMatND(const CvMatND* mat)
.. ocv:pyoldfunction:: cv.CloneMatND(mat)-> copy .. ocv:pyoldfunction:: cv.CloneMatND(mat) -> matND
:param mat: Input array :param mat: Input array
@@ -701,7 +702,7 @@ CreateMatND
Creates the header and allocates the data for a multi-dimensional dense array. Creates the header and allocates the data for a multi-dimensional dense array.
.. ocv:cfunction:: CvMatND* cvCreateMatND( int dims, const int* sizes, int type) .. ocv:cfunction:: CvMatND* cvCreateMatND( int dims, const int* sizes, int type)
.. ocv:pyoldfunction:: cv.CreateMatND(dims, type) -> None .. ocv:pyoldfunction:: cv.CreateMatND(dims, type) -> matND
:param dims: Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be changed at build time). :param dims: Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be changed at build time).
@@ -719,7 +720,7 @@ CreateMatNDHeader
Creates a new matrix header but does not allocate the matrix data. Creates a new matrix header but does not allocate the matrix data.
.. ocv:cfunction:: CvMatND* cvCreateMatNDHeader( int dims, const int* sizes, int type) .. ocv:cfunction:: CvMatND* cvCreateMatNDHeader( int dims, const int* sizes, int type)
.. ocv:pyoldfunction:: cv.CreateMatNDHeader(dims, type) -> None .. ocv:pyoldfunction:: cv.CreateMatNDHeader(dims, type) -> matND
:param dims: Number of array dimensions :param dims: Number of array dimensions
@@ -776,7 +777,7 @@ DotProduct
Calculates the dot product of two arrays in Euclidean metrics. Calculates the dot product of two arrays in Euclidean metrics.
.. ocv:cfunction:: double cvDotProduct(const CvArr* src1, const CvArr* src2) .. ocv:cfunction:: double cvDotProduct(const CvArr* src1, const CvArr* src2)
.. ocv:pyoldfunction:: cv.DotProduct(src1, src2)-> double .. ocv:pyoldfunction:: cv.DotProduct(src1, src2) -> float
:param src1: The first source array :param src1: The first source array
@@ -799,7 +800,7 @@ Get?D
.. ocv:cfunction:: CvScalar cvGet1D(const CvArr* arr, int idx0) .. ocv:cfunction:: CvScalar cvGet1D(const CvArr* arr, int idx0)
.. ocv:cfunction:: CvScalar cvGet2D(const CvArr* arr, int idx0, int idx1) .. ocv:cfunction:: CvScalar cvGet2D(const CvArr* arr, int idx0, int idx1)
.. ocv:cfunction:: CvScalar cvGet3D(const CvArr* arr, int idx0, int idx1, int idx2) .. ocv:cfunction:: CvScalar cvGet3D(const CvArr* arr, int idx0, int idx1, int idx2)
.. ocv:cfunction:: CvScalar cvGetND(const CvArr* arr, int* idx) .. ocv:cfunction:: CvScalar cvGetND( const CvArr* arr, const int* idx )
.. ocv:pyoldfunction:: cv.Get1D(arr, idx) -> scalar .. ocv:pyoldfunction:: cv.Get1D(arr, idx) -> scalar
.. ocv:pyoldfunction:: cv.Get2D(arr, idx0, idx1) -> scalar .. ocv:pyoldfunction:: cv.Get2D(arr, idx0, idx1) -> scalar
@@ -825,9 +826,11 @@ GetCol(s)
Returns one of more array columns. Returns one of more array columns.
.. ocv:cfunction:: CvMat* cvGetCol(const CvArr* arr, CvMat* submat, int col) .. ocv:cfunction:: CvMat* cvGetCol(const CvArr* arr, CvMat* submat, int col)
.. ocv:cfunction:: CvMat* cvGetCols(const CvArr* arr, CvMat* submat, int startCol, int endCol)
.. ocv:cfunction:: CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col )
.. ocv:pyoldfunction:: cv.GetCol(arr, col)-> submat .. ocv:pyoldfunction:: cv.GetCol(arr, col)-> submat
.. ocv:pyoldfunction:: cv.GetCols(arr, startCol, endCol)-> submat .. ocv:pyoldfunction:: cv.GetCols(arr, startCol, endCol)-> submat
:param arr: Input array :param arr: Input array
@@ -836,9 +839,9 @@ Returns one of more array columns.
:param col: Zero-based index of the selected column :param col: Zero-based index of the selected column
:param startCol: Zero-based index of the starting column (inclusive) of the span :param start_col: Zero-based index of the starting column (inclusive) of the span
:param endCol: Zero-based index of the ending column (exclusive) of the span :param end_col: Zero-based index of the ending column (exclusive) of the span
The functions return the header, corresponding to a specified column span of the input array. That is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. If you need to copy the columns, use :ocv:cfunc:`CloneMat`. ``cvGetCol(arr, submat, col)`` is a shortcut for ``cvGetCols(arr, submat, col, col+1)``. The functions return the header, corresponding to a specified column span of the input array. That is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. If you need to copy the columns, use :ocv:cfunc:`CloneMat`. ``cvGetCol(arr, submat, col)`` is a shortcut for ``cvGetCols(arr, submat, col, col+1)``.
@@ -862,7 +865,7 @@ GetDims
Return number of array dimensions Return number of array dimensions
.. ocv:cfunction:: int cvGetDims(const CvArr* arr, int* sizes=NULL) .. ocv:cfunction:: int cvGetDims(const CvArr* arr, int* sizes=NULL)
.. ocv:pyoldfunction:: cv.GetDims(arr)-> list .. ocv:pyoldfunction:: cv.GetDims(arr) -> (dim1, dim2, ...)
:param arr: Input array :param arr: Input array
@@ -907,21 +910,22 @@ GetImage
-------- --------
Returns image header for arbitrary array. Returns image header for arbitrary array.
.. ocv:cfunction:: IplImage* cvGetImage(const CvArr* arr, IplImage* imageHeader) .. ocv:cfunction:: IplImage* cvGetImage( const CvArr* arr, IplImage* image_header )
.. ocv:pyoldfunction:: cv.GetImage(arr) -> iplimage .. ocv:pyoldfunction:: cv.GetImage(arr) -> iplimage
:param arr: Input array :param arr: Input array
:param imageHeader: Pointer to ``IplImage`` structure used as a temporary buffer :param image_header: Pointer to ``IplImage`` structure used as a temporary buffer
The function returns the image header for the input array that can be a matrix (:ocv:struct:`CvMat`) or image (:ocv:struct:`IplImage`). In the case of an image the function simply returns the input pointer. In the case of ``CvMat`` it initializes an ``imageHeader`` structure with the parameters of the input matrix. Note that if we transform ``IplImage`` to ``CvMat`` using :ocv:cfunc:`GetMat` and then transform ``CvMat`` back to IplImage using this function, we will get different headers if the ROI is set in the original image. The function returns the image header for the input array that can be a matrix (:ocv:struct:`CvMat`) or image (:ocv:struct:`IplImage`). In the case of an image the function simply returns the input pointer. In the case of ``CvMat`` it initializes an ``image_header`` structure with the parameters of the input matrix. Note that if we transform ``IplImage`` to ``CvMat`` using :ocv:cfunc:`GetMat` and then transform ``CvMat`` back to IplImage using this function, we will get different headers if the ROI is set in the original image.
GetImageCOI GetImageCOI
----------- -----------
Returns the index of the channel of interest. Returns the index of the channel of interest.
.. ocv:cfunction:: int cvGetImageCOI(const IplImage* image) .. ocv:cfunction:: int cvGetImageCOI(const IplImage* image)
.. ocv:pyoldfunction:: cv.GetImageCOI(image)-> channel .. ocv:pyoldfunction:: cv.GetImageCOI(image) -> int
:param image: A pointer to the image header :param image: A pointer to the image header
@@ -944,7 +948,7 @@ GetMat
Returns matrix header for arbitrary array. Returns matrix header for arbitrary array.
.. ocv:cfunction:: CvMat* cvGetMat(const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0) .. ocv:cfunction:: CvMat* cvGetMat(const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0)
.. ocv:pyoldfunction:: cv.GetMat(arr, allowND=0) -> cvmat .. ocv:pyoldfunction:: cv.GetMat(arr, allowND=0) -> mat
:param arr: Input array :param arr: Input array
@@ -966,9 +970,9 @@ GetNextSparseNode
----------------- -----------------
Returns the next sparse matrix element Returns the next sparse matrix element
.. ocv:cfunction:: CvSparseNode* cvGetNextSparseNode(CvSparseMatIterator* matIterator) .. ocv:cfunction:: CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator )
:param matIterator: Sparse array iterator :param mat_iterator: Sparse array iterator
The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix: :: The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix: ::
@@ -999,7 +1003,7 @@ GetRawData
---------- ----------
Retrieves low-level information about the array. Retrieves low-level information about the array.
.. ocv:cfunction:: void cvGetRawData(const CvArr* arr, uchar** data, int* step=NULL, CvSize* roiSize=NULL) .. ocv:cfunction:: void cvGetRawData( const CvArr* arr, uchar** data, int* step=NULL, CvSize* roi_size=NULL )
:param arr: Array header :param arr: Array header
@@ -1007,7 +1011,7 @@ Retrieves low-level information about the array.
:param step: Output full row length in bytes :param step: Output full row length in bytes
:param roiSize: Output ROI size :param roi_size: Output ROI size
The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to ``NULL``. If the array is ``IplImage`` with ROI set, the parameters of ROI are returned. The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to ``NULL``. If the array is ``IplImage`` with ROI set, the parameters of ROI are returned.
@@ -1031,7 +1035,7 @@ Return a specific element of single-channel 1D, 2D, 3D or nD array.
.. ocv:cfunction:: double cvGetReal1D(const CvArr* arr, int idx0) .. ocv:cfunction:: double cvGetReal1D(const CvArr* arr, int idx0)
.. ocv:cfunction:: double cvGetReal2D(const CvArr* arr, int idx0, int idx1) .. ocv:cfunction:: double cvGetReal2D(const CvArr* arr, int idx0, int idx1)
.. ocv:cfunction:: double cvGetReal3D(const CvArr* arr, int idx0, int idx1, int idx2) .. ocv:cfunction:: double cvGetReal3D(const CvArr* arr, int idx0, int idx1, int idx2)
.. ocv:cfunction:: double cvGetRealND(const CvArr* arr, int* idx) .. ocv:cfunction:: double cvGetRealND( const CvArr* arr, const int* idx )
.. ocv:pyoldfunction:: cv.GetReal1D(arr, idx0)->float .. ocv:pyoldfunction:: cv.GetReal1D(arr, idx0)->float
.. ocv:pyoldfunction:: cv.GetReal2D(arr, idx0, idx1)->float .. ocv:pyoldfunction:: cv.GetReal2D(arr, idx0, idx1)->float
@@ -1059,7 +1063,7 @@ Returns array row or row span.
.. ocv:cfunction:: CvMat* cvGetRow(const CvArr* arr, CvMat* submat, int row) .. ocv:cfunction:: CvMat* cvGetRow(const CvArr* arr, CvMat* submat, int row)
.. ocv:cfunction:: CvMat* cvGetRows(const CvArr* arr, CvMat* submat, int startRow, int endRow, int deltaRow=1) .. ocv:cfunction:: CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row, int delta_row=1 )
.. ocv:pyoldfunction:: cv.GetRow(arr, row)-> submat .. ocv:pyoldfunction:: cv.GetRow(arr, row)-> submat
.. ocv:pyoldfunction:: cv.GetRows(arr, startRow, endRow, deltaRow=1)-> submat .. ocv:pyoldfunction:: cv.GetRows(arr, startRow, endRow, deltaRow=1)-> submat
@@ -1070,11 +1074,11 @@ Returns array row or row span.
:param row: Zero-based index of the selected row :param row: Zero-based index of the selected row
:param startRow: Zero-based index of the starting row (inclusive) of the span :param start_row: Zero-based index of the starting row (inclusive) of the span
:param endRow: Zero-based index of the ending row (exclusive) of the span :param end_row: Zero-based index of the ending row (exclusive) of the span
:param deltaRow: Index step in the row span. That is, the function extracts every ``deltaRow`` -th row from ``startRow`` and up to (but not including) ``endRow`` . :param delta_row: Index step in the row span. That is, the function extracts every ``delta_row`` -th row from ``start_row`` and up to (but not including) ``end_row`` .
The functions return the header, corresponding to a specified row/row span of the input array. ``cvGetRow(arr, submat, row)`` is a shortcut for ``cvGetRows(arr, submat, row, row+1)``. The functions return the header, corresponding to a specified row/row span of the input array. ``cvGetRow(arr, submat, row)`` is a shortcut for ``cvGetRows(arr, submat, row, row+1)``.
@@ -1209,11 +1213,11 @@ InitSparseMatIterator
--------------------- ---------------------
Initializes sparse array elements iterator. Initializes sparse array elements iterator.
.. ocv:cfunction:: CvSparseNode* cvInitSparseMatIterator(const CvSparseMat* mat, CvSparseMatIterator* matIterator) .. ocv:cfunction:: CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* mat_iterator )
:param mat: Input array :param mat: Input array
:param matIterator: Initialized iterator :param mat_iterator: Initialized iterator
The function initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty. The function initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty.
@@ -1250,7 +1254,7 @@ Return pointer to a particular array element.
.. ocv:cfunction:: uchar* cvPtr3D(const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL) .. ocv:cfunction:: uchar* cvPtr3D(const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL)
.. ocv:cfunction:: uchar* cvPtrND(const CvArr* arr, int* idx, int* type=NULL, int createNode=1, unsigned* precalcHashval=NULL) .. ocv:cfunction:: uchar* cvPtrND( const CvArr* arr, const int* idx, int* type=NULL, int create_node=1, unsigned* precalc_hashval=NULL )
:param arr: Input array :param arr: Input array
@@ -1264,9 +1268,9 @@ Return pointer to a particular array element.
:param type: Optional output parameter: type of matrix elements :param type: Optional output parameter: type of matrix elements
:param createNode: Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already. :param create_node: Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.
:param precalcHashval: Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example) :param precalc_hashval: Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)
The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for ``cvPtr1D`` function that can be used for sequential access to 1D, 2D or nD dense arrays. The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for ``cvPtr1D`` function that can be used for sequential access to 1D, 2D or nD dense arrays.
@@ -1403,16 +1407,17 @@ Reshape
------- -------
Changes shape of matrix/image without copying data. Changes shape of matrix/image without copying data.
.. ocv:cfunction:: CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn, int newRows=0) .. ocv:cfunction:: CvMat* cvReshape( const CvArr* arr, CvMat* header, int new_cn, int new_rows=0 )
.. ocv:pyoldfunction:: cv.Reshape(arr, newCn, newRows=0) -> cvmat
.. ocv:pyoldfunction:: cv.Reshape(arr, newCn, newRows=0) -> mat
:param arr: Input array :param arr: Input array
:param header: Output header to be filled :param header: Output header to be filled
:param newCn: New number of channels. 'newCn = 0' means that the number of channels remains unchanged. :param new_cn: New number of channels. 'new_cn = 0' means that the number of channels remains unchanged.
:param newRows: New number of rows. 'newRows = 0' means that the number of rows remains unchanged unless it needs to be changed according to ``newCn`` value. :param new_rows: New number of rows. 'new_rows = 0' means that the number of rows remains unchanged unless it needs to be changed according to ``new_cn`` value.
The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both. The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both.
@@ -1440,20 +1445,21 @@ ReshapeMatND
------------ ------------
Changes the shape of a multi-dimensional array without copying the data. Changes the shape of a multi-dimensional array without copying the data.
.. ocv:cfunction:: CvArr* cvReshapeMatND(const CvArr* arr, int sizeofHeader, CvArr* header, int newCn, int newDims, int* newSizes) .. ocv:cfunction:: CvArr* cvReshapeMatND( const CvArr* arr, int sizeof_header, CvArr* header, int new_cn, int new_dims, int* new_sizes )
.. ocv:pyoldfunction:: cv.ReshapeMatND(arr, newCn, newDims) -> cvmat
.. ocv:pyoldfunction:: cv.ReshapeMatND(arr, newCn, newDims) -> mat
:param arr: Input array :param arr: Input array
:param sizeofHeader: Size of output header to distinguish between IplImage, CvMat and CvMatND output headers :param sizeof_header: Size of output header to distinguish between IplImage, CvMat and CvMatND output headers
:param header: Output header to be filled :param header: Output header to be filled
:param newCn: New number of channels. ``newCn = 0`` means that the number of channels remains unchanged. :param new_cn: New number of channels. ``new_cn = 0`` means that the number of channels remains unchanged.
:param newDims: New number of dimensions. ``newDims = 0`` means that the number of dimensions remains the same. :param new_dims: New number of dimensions. ``new_dims = 0`` means that the number of dimensions remains the same.
:param newSizes: Array of new dimension sizes. Only ``newDims-1`` values are used, because the total number of elements must remain the same. Thus, if ``newDims = 1``, ``newSizes`` array is not used. :param new_sizes: Array of new dimension sizes. Only ``new_dims-1`` values are used, because the total number of elements must remain the same. Thus, if ``new_dims = 1``, ``new_sizes`` array is not used.
The function is an advanced version of :ocv:cfunc:`Reshape` that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions. The function is an advanced version of :ocv:cfunc:`Reshape` that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions.
@@ -1508,7 +1514,7 @@ Change the particular array element.
.. ocv:cfunction:: void cvSet3D(CvArr* arr, int idx0, int idx1, int idx2, CvScalar value) .. ocv:cfunction:: void cvSet3D(CvArr* arr, int idx0, int idx1, int idx2, CvScalar value)
.. ocv:cfunction:: void cvSetND(CvArr* arr, int* idx, CvScalar value) .. ocv:cfunction:: void cvSetND( CvArr* arr, const int* idx, CvScalar value )
.. ocv:pyoldfunction:: cv.Set1D(arr, idx, value) -> None .. ocv:pyoldfunction:: cv.Set1D(arr, idx, value) -> None
.. ocv:pyoldfunction:: cv.Set2D(arr, idx0, idx1, value) -> None .. ocv:pyoldfunction:: cv.Set2D(arr, idx0, idx1, value) -> None
@@ -1589,7 +1595,7 @@ Change a specific array element.
.. ocv:cfunction:: void cvSetReal3D(CvArr* arr, int idx0, int idx1, int idx2, double value) .. ocv:cfunction:: void cvSetReal3D(CvArr* arr, int idx0, int idx1, int idx2, double value)
.. ocv:cfunction:: void cvSetRealND(CvArr* arr, int* idx, double value) .. ocv:cfunction:: void cvSetRealND( CvArr* arr, const int* idx, double value )
.. ocv:pyoldfunction:: cv.SetReal1D(arr, idx, value) -> None .. ocv:pyoldfunction:: cv.SetReal1D(arr, idx, value) -> None
.. ocv:pyoldfunction:: cv.SetReal2D(arr, idx0, idx1, value) -> None .. ocv:pyoldfunction:: cv.SetReal2D(arr, idx0, idx1, value) -> None
@@ -1617,7 +1623,7 @@ SetZero
Clears the array. Clears the array.
.. ocv:cfunction:: void cvSetZero(CvArr* arr) .. ocv:cfunction:: void cvSetZero(CvArr* arr)
.. ocv:pyoldfunction:: cv.SetZero(arr)-> None .. ocv:pyoldfunction:: cv.SetZero(arr) -> None
:param arr: Array to be cleared :param arr: Array to be cleared
@@ -1628,7 +1634,7 @@ mGet
Returns the particular element of single-channel floating-point matrix. Returns the particular element of single-channel floating-point matrix.
.. ocv:cfunction:: double cvmGet(const CvMat* mat, int row, int col) .. ocv:cfunction:: double cvmGet(const CvMat* mat, int row, int col)
.. ocv:pyoldfunction:: cv.mGet(mat, row, col)-> double .. ocv:pyoldfunction:: cv.mGet(mat, row, col) -> float
:param mat: Input matrix :param mat: Input matrix
@@ -1687,14 +1693,15 @@ RandArr
------- -------
Fills an array with random numbers and updates the RNG state. Fills an array with random numbers and updates the RNG state.
.. ocv:cfunction:: void cvRandArr( CvRNG* rng, CvArr* arr, int distType, CvScalar param1, CvScalar param2) .. ocv:cfunction:: void cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, CvScalar param1, CvScalar param2 )
.. ocv:pyoldfunction:: cv.RandArr(rng, arr, distType, param1, param2)-> None .. ocv:pyoldfunction:: cv.RandArr(rng, arr, distType, param1, param2)-> None
:param rng: CvRNG state initialized by :ocv:cfunc:`RNG` :param rng: CvRNG state initialized by :ocv:cfunc:`RNG`
:param arr: The destination array :param arr: The destination array
:param distType: Distribution type :param dist_type: Distribution type
* **CV_RAND_UNI** uniform distribution * **CV_RAND_UNI** uniform distribution
@@ -1725,7 +1732,7 @@ RandReal
Returns a floating-point random number and updates RNG. Returns a floating-point random number and updates RNG.
.. ocv:cfunction:: double cvRandReal(CvRNG* rng) .. ocv:cfunction:: double cvRandReal(CvRNG* rng)
.. ocv:pyoldfunction:: cv.RandReal(rng)-> double .. ocv:pyoldfunction:: cv.RandReal(rng) -> float
:param rng: RNG state initialized by :ocv:cfunc:`RNG` :param rng: RNG state initialized by :ocv:cfunc:`RNG`
@@ -1736,7 +1743,7 @@ fromarray
--------- ---------
Create a CvMat from an object that supports the array interface. Create a CvMat from an object that supports the array interface.
.. ocv:pyoldfunction:: cv.fromarray(object, allowND=False) -> CvMat .. ocv:pyoldfunction:: cv.fromarray(array, allowND=False) -> mat
:param object: Any object that supports the array interface :param object: Any object that supports the array interface
+66 -64
View File
@@ -48,41 +48,41 @@ CvFileNode
.. ocv:struct:: 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 .. ocv:member:: int tag
type of the file node: type of the file node:
* CV_NODE_NONE - empty node * CV_NODE_NONE - empty node
* CV_NODE_INT - an integer * CV_NODE_INT - an integer
* CV_NODE_REAL - a floating-point number * CV_NODE_REAL - a floating-point number
* CV_NODE_STR - text string * CV_NODE_STR - text string
* CV_NODE_SEQ - a sequence * CV_NODE_SEQ - a sequence
* CV_NODE_MAP - a mapping * CV_NODE_MAP - a mapping
type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro. type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro.
.. ocv:member:: CvTypeInfo* info .. 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. 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 .. ocv:member:: union data
the node data, declared as: :: the node data, declared as: ::
union union
{ {
double f; /* scalar floating-point number */ double f; /* scalar floating-point number */
int i; /* scalar integer number */ int i; /* scalar integer number */
CvString str; /* text string */ CvString str; /* text string */
CvSeq* seq; /* sequence (ordered collection of file nodes) */ CvSeq* seq; /* sequence (ordered collection of file nodes) */
struct CvMap* map; /* map (collection of named file nodes) */ struct CvMap* map; /* map (collection of named file nodes) */
} data; } 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`. 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 CvAttrList
---------- ----------
@@ -151,11 +151,11 @@ Clone
----- -----
Makes a clone of an object. Makes a clone of an object.
.. ocv:cfunction:: void* cvClone( const void* structPtr ) .. ocv:cfunction:: void* cvClone( const void* struct_ptr )
:param structPtr: The object to clone :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, ``structPtr`` is ``CvMat*``, it is faster to call the specific function, like :ocv:cfunc:`CloneMat`. 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 EndWriteStruct
-------------- --------------
@@ -171,9 +171,9 @@ FindType
-------- --------
Finds a type by its name. Finds a type by its name.
.. ocv:cfunction:: CvTypeInfo* cvFindType(const char* typeName) .. ocv:cfunction:: CvTypeInfo* cvFindType( const char* type_name )
:param typeName: 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. The function finds a registered type by its name. It returns NULL if there is no type with the specified name.
@@ -189,7 +189,7 @@ GetFileNode
----------- -----------
Finds a node in a map or file storage. Finds a node in a map or file storage.
.. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int createMissing=0 ) .. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int create_missing=0 )
:param fs: File storage :param fs: File storage
@@ -197,7 +197,7 @@ Finds a node in a map or file storage.
:param key: Unique pointer to the node name, retrieved with :ocv:cfunc:`GetHashedKey` :param key: Unique pointer to the node name, retrieved with :ocv:cfunc:`GetHashedKey`
:param createMissing: Flag that specifies whether an absent node should be added to the map :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` 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. (see :ocv:cfunc:`GetHashedKey` discussion). Also, the function can insert a new node, if it is not in the map yet.
@@ -231,7 +231,7 @@ GetHashedKey
------------ ------------
Returns a unique pointer for a given name. 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
@@ -239,7 +239,7 @@ Returns a unique pointer for a given 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` 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. because it compares text strings by comparing pointers rather than the strings' content.
@@ -325,16 +325,17 @@ Load
---- ----
Loads an object from a file. 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 .. ocv:pyoldfunction:: cv.Load(filename, storage=None, name=None)-> generic
:param filename: File name :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 memstorage: Memory storage for dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` . It is not used for matrices or images.
:param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded. :param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded.
:param realName: Optional output parameter that will contain the name of the loaded object (useful if ``name=NULL`` ) :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. 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,7 +343,7 @@ OpenFileStorage
--------------- ---------------
Opens file storage for reading or writing data. 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
@@ -393,21 +394,21 @@ ReadInt
------- -------
Retrieves an integer value from a file node. 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 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`` ``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. is converted to an integer and returned. Otherwise the error is reported.
ReadIntByName ReadIntByName
------------- -------------
Finds a file node and returns its value. 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
@@ -415,7 +416,7 @@ Finds a file node and returns its value.
: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`. The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and :ocv:cfunc:`ReadInt`.
@@ -459,15 +460,15 @@ ReadReal
-------- --------
Retrieves a floating-point value from a file node. Retrieves a floating-point value from a file node.
.. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double defaultValue=0. ) .. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double 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 a floating-point value The function returns a floating-point value
that is represented by the file node. If the file node is NULL, the 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 is returned (thus, it is convenient to call
the function right after the function right after
:ocv:cfunc:`GetFileNode` :ocv:cfunc:`GetFileNode`
@@ -489,7 +490,7 @@ ReadRealByName
-------------- --------------
Finds a file node and returns its value. Finds a file node and returns its value.
.. ocv:cfunction:: double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double defaultValue=0.) .. ocv:cfunction:: double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double default_value=0. )
:param fs: File storage :param fs: File storage
@@ -497,7 +498,7 @@ Finds a file node and returns its value.
: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 The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName` :ocv:cfunc:`GetFileNodeByName`
@@ -510,15 +511,15 @@ ReadString
---------- ----------
Retrieves a text string from a file node. Retrieves a text string from a file node.
.. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* defaultValue=NULL ) .. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* default_value=NULL )
: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 a text string that is represented The function returns a text string that is represented
by the file node. If the file node is NULL, the 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 is returned (thus, it is convenient to call the function right after
:ocv:cfunc:`GetFileNode` :ocv:cfunc:`GetFileNode`
without checking for a NULL pointer). If without checking for a NULL pointer). If
@@ -533,7 +534,7 @@ ReadStringByName
---------------- ----------------
Finds a file node by its name and returns its value. 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 ) .. ocv:cfunction:: const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* default_value=NULL )
:param fs: File storage :param fs: File storage
@@ -541,7 +542,7 @@ Finds a file node by its name and returns its value.
: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 The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName` :ocv:cfunc:`GetFileNodeByName`
@@ -569,9 +570,9 @@ Release
------- -------
Releases an object. 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`` ``release``
@@ -593,12 +594,13 @@ Save
---- ----
Saves an object to a file. 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 .. ocv:pyoldfunction:: cv.Save(filename, structPtr, name=None, comment=None)-> None
:param filename: File name :param filename: File name
:param structPtr: Object to save :param struct_ptr: Object to save
:param name: Optional object name. If it is NULL, the name will be formed from ``filename`` . :param name: Optional object name. If it is NULL, the name will be formed from ``filename`` .
@@ -659,7 +661,7 @@ StartWriteStruct
---------------- ----------------
Starts writing a new structure. Starts writing a new structure.
.. ocv:cfunction:: void cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* typeName=NULL, CvAttrList attributes=cvAttrList()) .. ocv:cfunction:: void cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* type_name=NULL, CvAttrList attributes=cvAttrList() )
:param fs: File storage :param fs: File storage
@@ -675,7 +677,7 @@ Starts writing a new structure.
* **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_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 typeName: Optional parameter - the object type name. In :param type_name: Optional parameter - the object type name. In
case of XML it is written as a ``type_id`` attribute of the 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 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`
@@ -692,9 +694,9 @@ TypeOf
------ ------
Returns the type of an object. 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. 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. Unregisters the type.
.. ocv:cfunction:: void cvUnregisterType( const char* typeName ) .. ocv:cfunction:: void cvUnregisterType( const char* type_name )
:param typeName: Name of an unregistered type :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)``. 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)``.
@@ -774,13 +776,13 @@ WriteComment
------------ ------------
Writes a comment. 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. The function writes a comment into file storage. The comments are skipped when the storage is read.
+171 -151
View File
@@ -7,10 +7,11 @@ abs
--- ---
Computes an absolute value of each matrix element. Computes an absolute value of each matrix element.
.. ocv:function:: MatExpr abs(const Mat& src) .. ocv:function:: MatExpr abs( const Mat& m )
.. ocv:function:: MatExpr abs(const MatExpr& src) .. ocv:function:: MatExpr abs( const MatExpr& e )
:param src: Matrix or matrix expression. :param m: Matrix.
:param e: Matrix expression.
``abs`` is a meta-function that is expanded to one of :ocv:func:`absdiff` forms: ``abs`` is a meta-function that is expanded to one of :ocv:func:`absdiff` forms:
@@ -373,7 +374,8 @@ Calculates the covariance matrix of a set of vectors.
.. ocv:pyfunction:: cv2.calcCovarMatrix(samples, flags[, covar[, mean[, ctype]]]) -> covar, mean .. ocv:pyfunction:: cv2.calcCovarMatrix(samples, flags[, covar[, mean[, ctype]]]) -> covar, mean
.. ocv:cfunction:: void cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* covMat, CvArr* avg, int flags) .. ocv:cfunction:: void cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags )
.. ocv:pyoldfunction:: cv.CalcCovarMatrix(vects, covMat, avg, flags)-> None .. ocv:pyoldfunction:: cv.CalcCovarMatrix(vects, covMat, avg, flags)-> None
:param samples: Samples stored either as separate matrices or as rows/columns of a single matrix. :param samples: Samples stored either as separate matrices or as rows/columns of a single matrix.
@@ -428,7 +430,8 @@ Calculates the magnitude and angle of 2D vectors.
.. ocv:pyfunction:: cv2.cartToPolar(x, y[, magnitude[, angle[, angleInDegrees]]]) -> magnitude, angle .. ocv:pyfunction:: cv2.cartToPolar(x, y[, magnitude[, angle[, angleInDegrees]]]) -> magnitude, angle
.. ocv:cfunction:: void cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle=NULL, int angleInDegrees=0) .. ocv:cfunction:: void cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle=NULL, int angle_in_degrees=0 )
.. ocv:pyoldfunction:: cv.CartToPolar(x, y, magnitude, angle=None, angleInDegrees=0)-> None .. ocv:pyoldfunction:: cv.CartToPolar(x, y, magnitude, angle=None, angleInDegrees=0)-> None
:param x: Array of x-coordinates. This must be a single-precision or double-precision floating-point array. :param x: Array of x-coordinates. This must be a single-precision or double-precision floating-point array.
@@ -458,11 +461,11 @@ checkRange
---------- ----------
Checks every element of an input array for invalid values. Checks every element of an input array for invalid values.
.. ocv:function:: bool checkRange(InputArray src, bool quiet=true, Point* pos=0, double minVal=-DBL_MAX, double maxVal=DBL_MAX) .. ocv:function:: bool checkRange( InputArray a, bool quiet=true, Point* pos=0, double minVal=-DBL_MAX, double maxVal=DBL_MAX )
.. ocv:pyfunction:: cv2.checkRange(a[, quiet[, minVal[, maxVal]]]) -> retval, pt .. ocv:pyfunction:: cv2.checkRange(a[, quiet[, minVal[, maxVal]]]) -> retval, pos
:param src: Array to check. :param a: Array to check.
:param quiet: Flag indicating whether the functions quietly return false when the array elements are out of range or they throw an exception. :param quiet: Flag indicating whether the functions quietly return false when the array elements are out of range or they throw an exception.
@@ -487,13 +490,13 @@ Performs the per-element comparison of two arrays or an array and scalar value.
.. ocv:pyfunction:: cv2.compare(src1, src2, cmpop[, dst]) -> dst .. ocv:pyfunction:: cv2.compare(src1, src2, cmpop[, dst]) -> dst
.. ocv:cfunction:: void cvCmp(const CvArr* src1, const CvArr* src2, CvArr* dst, int cmpOp) .. ocv:cfunction:: void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op )
.. ocv:pyoldfunction:: cv.Cmp(src1, src2, dst, cmpOp)-> None .. ocv:pyoldfunction:: cv.Cmp(src1, src2, dst, cmpOp)-> None
.. ocv:cfunction:: void cvCmpS(const CvArr* src1, double src2, CvArr* dst, int cmpOp) .. ocv:cfunction:: void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op )
.. ocv:pyoldfunction:: cv.CmpS(src1, src2, dst, cmpOp)-> None .. ocv:pyoldfunction:: cv.CmpS(src, value, dst, cmpOp)-> None
:param src1: First source array or a scalar (in the case of ``cvCmp``, ``cv.Cmp``, ``cvCmpS``, ``cv.CmpS`` it is always an array). When it is array, it must have a single channel. :param src1: First source array or a scalar (in the case of ``cvCmp``, ``cv.Cmp``, ``cvCmpS``, ``cv.CmpS`` it is always an array). When it is array, it must have a single channel.
@@ -629,20 +632,21 @@ countNonZero
------------ ------------
Counts non-zero array elements. Counts non-zero array elements.
.. ocv:function:: int countNonZero( InputArray mtx ) .. ocv:function:: int countNonZero( InputArray src )
.. ocv:pyfunction:: cv2.countNonZero(src) -> retval .. ocv:pyfunction:: cv2.countNonZero(src) -> retval
.. ocv:cfunction:: int cvCountNonZero(const CvArr* arr) .. ocv:cfunction:: int cvCountNonZero(const CvArr* arr)
.. ocv:pyoldfunction:: cv.CountNonZero(arr)-> int .. ocv:pyoldfunction:: cv.CountNonZero(arr)-> int
:param mtx: Single-channel array. :param src: Single-channel array.
The function returns the number of non-zero elements in ``mtx`` : The function returns the number of non-zero elements in ``src`` :
.. math:: .. math::
\sum _{I: \; \texttt{mtx} (I) \ne0 } 1 \sum _{I: \; \texttt{src} (I) \ne0 } 1
.. seealso:: .. seealso::
@@ -658,9 +662,9 @@ cvarrToMat
---------- ----------
Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``. Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``.
.. ocv:function:: Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0) .. ocv:function:: Mat cvarrToMat( const CvArr* arr, bool copyData=false, bool allowND=true, int coiMode=0 )
:param src: Source ``CvMat``, ``IplImage`` , or ``CvMatND`` . :param arr: Source ``CvMat``, ``IplImage`` , or ``CvMatND`` .
:param copyData: When it is false (default value), no data is copied and only the new header is created. In this case, the original array should not be deallocated while the new matrix header is used. If the parameter is true, all the data is copied and you may deallocate the original array right after the conversion. :param copyData: When it is false (default value), no data is copied and only the new header is created. In this case, the original array should not be deallocated while the new matrix header is used. If the parameter is true, all the data is copied and you may deallocate the original array right after the conversion.
@@ -675,7 +679,7 @@ Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``.
The function ``cvarrToMat`` converts ``CvMat``, ``IplImage`` , or ``CvMatND`` header to The function ``cvarrToMat`` converts ``CvMat``, ``IplImage`` , or ``CvMatND`` header to
:ocv:class:`Mat` header, and optionally duplicates the underlying data. The constructed header is returned by the function. :ocv:class:`Mat` header, and optionally duplicates the underlying data. The constructed header is returned by the function.
When ``copyData=false`` , the conversion is done really fast (in O(1) time) and the newly created matrix header will have ``refcount=0`` , which means that no reference counting is done for the matrix data. In this case, you have to preserve the data until the new header is destructed. Otherwise, when ``copyData=true`` , the new buffer is allocated and managed as if you created a new matrix from scratch and copied the data there. That is, ``cvarrToMat(src, true)`` is equivalent to ``cvarrToMat(src, false).clone()`` (assuming that COI is not set). The function provides a uniform way of supporting When ``copyData=false`` , the conversion is done really fast (in O(1) time) and the newly created matrix header will have ``refcount=0`` , which means that no reference counting is done for the matrix data. In this case, you have to preserve the data until the new header is destructed. Otherwise, when ``copyData=true`` , the new buffer is allocated and managed as if you created a new matrix from scratch and copied the data there. That is, ``cvarrToMat(arr, true)`` is equivalent to ``cvarrToMat(arr, false).clone()`` (assuming that COI is not set). The function provides a uniform way of supporting
``CvArr`` paradigm in the code that is migrated to use new-style data structures internally. The reverse transformation, from ``CvArr`` paradigm in the code that is migrated to use new-style data structures internally. The reverse transformation, from
``Mat`` to ``Mat`` to
``CvMat`` or ``CvMat`` or
@@ -819,7 +823,8 @@ Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-
.. ocv:pyfunction:: cv2.dft(src[, dst[, flags[, nonzeroRows]]]) -> dst .. ocv:pyfunction:: cv2.dft(src[, dst[, flags[, nonzeroRows]]]) -> dst
.. ocv:cfunction:: void cvDFT(const CvArr* src, CvArr* dst, int flags, int nonzeroRows=0) .. ocv:cfunction:: void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero_rows=0 )
.. ocv:pyoldfunction:: cv.DFT(src, dst, flags, nonzeroRows=0)-> None .. ocv:pyoldfunction:: cv.DFT(src, dst, flags, nonzeroRows=0)-> None
:param src: Source array that could be real or complex. :param src: Source array that could be real or complex.
@@ -976,7 +981,7 @@ Performs per-element division of two arrays or a scalar by an array.
.. ocv:pyfunction:: cv2.divide(scale, src2[, dst[, dtype]]) -> dst .. ocv:pyfunction:: cv2.divide(scale, src2[, dst[, dtype]]) -> dst
.. ocv:cfunction:: void cvDiv(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1) .. ocv:cfunction:: void cvDiv(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1)
.. ocv:pyoldfunction:: cv.Div(src1, src2, dst, scale)-> None .. ocv:pyoldfunction:: cv.Div(src1, src2, dst, scale=1) -> None
:param src1: First source array. :param src1: First source array.
@@ -1021,8 +1026,9 @@ Returns the determinant of a square floating-point matrix.
.. ocv:pyfunction:: cv2.determinant(mtx) -> retval .. ocv:pyfunction:: cv2.determinant(mtx) -> retval
.. ocv:cfunction:: double cvDet(const CvArr* mtx) .. ocv:cfunction:: double cvDet( const CvArr* mat )
.. ocv:pyoldfunction:: cv.Det(mtx)-> double
.. ocv:pyoldfunction:: cv.Det(mat) -> float
:param mtx: Input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type and square size. :param mtx: Input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type and square size.
@@ -1043,18 +1049,17 @@ For symmetric positively-determined matrices, it is also possible to use :ocv:fu
eigen eigen
----- -----
Computes eigenvalues and eigenvectors of a symmetric matrix.
.. ocv:function:: bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1, int highindex=-1) .. ocv:function:: bool eigen(InputArray src, OutputArray eigenvalues, int lowindex=-1, int highindex=-1)
.. ocv:function:: bool eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors, int lowindex=-1,int highindex=-1) .. ocv:function:: bool eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors, int lowindex=-1,int highindex=-1)
.. ocv:cfunction:: void cvEigenVV( CvArr* src, CvArr* eigenvectors, CvArr* eigenvalues, double eps=0, int lowindex=-1, int highindex=-1) .. ocv:pyfunction:: cv2.eigen(src, computeEigenvectors[, eigenvalues[, eigenvectors]]) -> retval, eigenvalues, eigenvectors
.. ocv:pyoldfunction:: cv.EigenVV(src, eigenvectors, eigenvalues, eps, lowindex=-1, highindex=-1)-> None .. ocv:cfunction:: void cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps=0, int lowindex=-1, int highindex=-1 )
Computes eigenvalues and eigenvectors of a symmetric matrix. .. ocv:pyoldfunction:: cv.EigenVV(mat, evects, evals, eps, lowindex=-1, highindex=-1)-> None
.. ocv:pyfunction:: cv2.eigen(src, computeEigenvectors[, eigenvalues[, eigenvectors[, lowindex[, highindex]]]]) -> retval, eigenvalues, eigenvectors
:param src: Input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type, square size and be symmetrical (``src`` :sup:`T` == ``src``). :param src: Input matrix that must have ``CV_32FC1`` or ``CV_64FC1`` type, square size and be symmetrical (``src`` :sup:`T` == ``src``).
@@ -1107,13 +1112,13 @@ extractImageCOI
--------------- ---------------
Extracts the selected image channel. Extracts the selected image channel.
.. ocv:function:: void extractImageCOI(const CvArr* src, OutputArray dst, int coi=-1) .. ocv:function:: void extractImageCOI( const CvArr* arr, OutputArray coiimg, int coi=-1 )
:param src: Source array. It should be a pointer to ``CvMat`` or ``IplImage`` . :param arr: Source array. It should be a pointer to ``CvMat`` or ``IplImage`` .
:param dst: Destination array with a single channel and the same size and depth as ``src`` . :param coiimg: Destination array with a single channel and the same size and depth as ``arr`` .
:param coi: If the parameter is ``>=0`` , it specifies the channel to extract. If it is ``<0`` and ``src`` is a pointer to ``IplImage`` with a valid COI set, the selected COI is extracted. :param coi: If the parameter is ``>=0`` , it specifies the channel to extract. If it is ``<0`` and ``arr`` is a pointer to ``IplImage`` with a valid COI set, the selected COI is extracted.
The function ``extractImageCOI`` is used to extract an image COI from an old-style array and put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated using ``Mat::create`` if needed. The function ``extractImageCOI`` is used to extract an image COI from an old-style array and put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated using ``Mat::create`` if needed.
@@ -1128,13 +1133,13 @@ insertImageCOI
--------------- ---------------
Copies the selected image channel from a new-style C++ matrix to the old-style C array. Copies the selected image channel from a new-style C++ matrix to the old-style C array.
.. ocv:function:: void insertImageCOI(InputArray src, CvArr* dst, int coi=-1) .. ocv:function:: void insertImageCOI( InputArray coiimg, CvArr* arr, int coi=-1 )
:param src: Source array with a single channel and the same size and depth as ``dst``. :param coiimg: Source array with a single channel and the same size and depth as ``arr``.
:param dst: Destination array, it should be a pointer to ``CvMat`` or ``IplImage``. :param arr: Destination array, it should be a pointer to ``CvMat`` or ``IplImage``.
:param coi: If the parameter is ``>=0`` , it specifies the channel to insert. If it is ``<0`` and ``dst`` is a pointer to ``IplImage`` with a valid COI set, the selected COI is extracted. :param coi: If the parameter is ``>=0`` , it specifies the channel to insert. If it is ``<0`` and ``arr`` is a pointer to ``IplImage`` with a valid COI set, the selected COI is extracted.
The function ``insertImageCOI`` is used to extract an image COI from a new-style C++ matrix and put the result to the old-style array. The function ``insertImageCOI`` is used to extract an image COI from a new-style C++ matrix and put the result to the old-style array.
@@ -1164,7 +1169,8 @@ Flips a 2D array around vertical, horizontal, or both axes.
.. ocv:pyfunction:: cv2.flip(src, flipCode[, dst]) -> dst .. ocv:pyfunction:: cv2.flip(src, flipCode[, dst]) -> dst
.. ocv:cfunction:: void cvFlip(const CvArr* src, CvArr* dst=NULL, int flipMode=0) .. ocv:cfunction:: void cvFlip( const CvArr* src, CvArr* dst=NULL, int flip_mode=0 )
.. ocv:pyoldfunction:: cv.Flip(src, dst=None, flipMode=0)-> None .. ocv:pyoldfunction:: cv.Flip(src, dst=None, flipMode=0)-> None
:param src: Source array. :param src: Source array.
@@ -1208,7 +1214,7 @@ gemm
---- ----
Performs generalized matrix multiplication. Performs generalized matrix multiplication.
.. ocv:function:: void gemm(InputArray src1, InputArray src2, double alpha, InputArray src3, double beta, OutputArray dst, int flags=0) .. ocv:function:: void gemm( InputArray src1, InputArray src2, double alpha, InputArray src3, double gamma, OutputArray dst, int flags=0 )
.. ocv:pyfunction:: cv2.gemm(src1, src2, alpha, src3, gamma[, dst[, flags]]) -> dst .. ocv:pyfunction:: cv2.gemm(src1, src2, alpha, src3, gamma[, dst[, flags]]) -> dst
@@ -1415,9 +1421,9 @@ Finds the inverse or pseudo-inverse of a matrix.
.. ocv:pyfunction:: cv2.invert(src[, dst[, flags]]) -> retval, dst .. ocv:pyfunction:: cv2.invert(src[, dst[, flags]]) -> retval, dst
.. ocv:cfunction:: double cvInvert(const CvArr* src, CvArr* dst, int flags=CV_LU) .. ocv:cfunction:: double cvInvert( const CvArr* src, CvArr* dst, int method=CV_LU )
.. ocv:pyoldfunction:: cv.Invert(src, dst, flags=CV_LU)-> double .. ocv:pyoldfunction:: cv.Invert(src, dst, method=CV_LU) -> float
:param src: Source floating-point ``M x N`` matrix. :param src: Source floating-point ``M x N`` matrix.
@@ -1434,7 +1440,7 @@ Finds the inverse or pseudo-inverse of a matrix.
The function ``invert`` inverts the matrix ``src`` and stores the result in ``dst`` . The function ``invert`` inverts the matrix ``src`` and stores the result in ``dst`` .
When the matrix ``src`` is singular or non-square, the function computes the pseudo-inverse matrix (the ``dst`` matrix) so that ``norm(src*dst - I)`` is minimal, where I is an identity matrix. When the matrix ``src`` is singular or non-square, the function computes the pseudo-inverse matrix (the ``dst`` matrix) so that ``norm(src*dst - I)`` is minimal, where I is an identity matrix.
In case of the ``DECOMP_LU`` method, the function returns the ``src`` determinant ( ``src`` must be square). If it is 0, the matrix is not inverted and ``dst`` is filled with zeros. In case of the ``DECOMP_LU`` method, the function returns non-zero value if the inverse has been successfully computed and 0 if ``src`` is singular.
In case of the ``DECOMP_SVD`` method, the function returns the inverse condition number of ``src`` (the ratio of the smallest singular value to the largest singular value) and 0 if ``src`` is singular. The SVD method calculates a pseudo-inverse matrix if ``src`` is singular. In case of the ``DECOMP_SVD`` method, the function returns the inverse condition number of ``src`` (the ratio of the smallest singular value to the largest singular value) and 0 if ``src`` is singular. The SVD method calculates a pseudo-inverse matrix if ``src`` is singular.
@@ -1487,7 +1493,7 @@ LUT
--- ---
Performs a look-up table transform of an array. Performs a look-up table transform of an array.
.. ocv:function:: void LUT(InputArray src, InputArray lut, OutputArray dst) .. ocv:function:: void LUT( InputArray src, InputArray lut, OutputArray dst, int interpolation=0 )
.. ocv:pyfunction:: cv2.LUT(src, lut[, dst[, interpolation]]) -> dst .. ocv:pyfunction:: cv2.LUT(src, lut[, dst[, interpolation]]) -> dst
@@ -1552,13 +1558,13 @@ Mahalanobis
----------- -----------
Calculates the Mahalanobis distance between two vectors. Calculates the Mahalanobis distance between two vectors.
.. ocv:function:: double Mahalanobis(InputArray vec1, InputArray vec2, InputArray icovar) .. ocv:function:: double Mahalanobis( InputArray v1, InputArray v2, InputArray icovar )
.. ocv:pyfunction:: cv2.Mahalanobis(v1, v2, icovar) -> retval .. ocv:pyfunction:: cv2.Mahalanobis(v1, v2, icovar) -> retval
.. ocv:cfunction:: double cvMahalanobis( const CvArr* vec1, const CvArr* vec2, CvArr* icovar) .. ocv:cfunction:: double cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat )
.. ocv:pyoldfunction:: cv.Mahalanobis(vec1, vec2, icovar)-> None .. ocv:pyoldfunction:: cv.Mahalonobis(vec1, vec2, mat) -> None
:param vec1: First 1D source vector. :param vec1: First 1D source vector.
@@ -1582,17 +1588,17 @@ max
--- ---
Calculates per-element maximum of two arrays or an array and a scalar. Calculates per-element maximum of two arrays or an array and a scalar.
.. ocv:function:: MatExpr max(const Mat& src1, const Mat& src2) .. ocv:function:: MatExpr max( const Mat& a, const Mat& b )
.. ocv:function:: MatExpr max(const Mat& src1, double value) .. ocv:function:: MatExpr max( const Mat& a, double s )
.. ocv:function:: MatExpr max(double value, const Mat& src1) .. ocv:function:: MatExpr max( double s, const Mat& a )
.. ocv:function:: void max(InputArray src1, InputArray src2, OutputArray dst) .. ocv:function:: void max(InputArray src1, InputArray src2, OutputArray dst)
.. ocv:function:: void max(const Mat& src1, const Mat& src2, Mat& dst) .. ocv:function:: void max(const Mat& src1, const Mat& src2, Mat& dst)
.. ocv:function:: void max(const Mat& src1, double value, Mat& dst) .. ocv:function:: void max( const Mat& src1, double src2, Mat& dst )
.. ocv:pyfunction:: cv2.max(src1, src2[, dst]) -> dst .. ocv:pyfunction:: cv2.max(src1, src2[, dst]) -> dst
@@ -1643,8 +1649,9 @@ Calculates an average (mean) of array elements.
.. ocv:pyfunction:: cv2.mean(src[, mask]) -> retval .. ocv:pyfunction:: cv2.mean(src[, mask]) -> retval
.. ocv:cfunction:: CvScalar cvAvg(const CvArr* src, const CvArr* mask=NULL) .. ocv:cfunction:: CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL )
.. ocv:pyoldfunction:: cv.Avg(src, mask=None)-> CvScalar
.. ocv:pyoldfunction:: cv.Avg(arr, mask=None) -> scalar
:param src: Source array that should have from 1 to 4 channels so that the result can be stored in :ocv:class:`Scalar_` . :param src: Source array that should have from 1 to 4 channels so that the result can be stored in :ocv:class:`Scalar_` .
@@ -1675,8 +1682,9 @@ Calculates a mean and standard deviation of array elements.
.. ocv:pyfunction:: cv2.meanStdDev(src[, mean[, stddev[, mask]]]) -> mean, stddev .. ocv:pyfunction:: cv2.meanStdDev(src[, mean[, stddev[, mask]]]) -> mean, stddev
.. ocv:cfunction:: void cvAvgSdv(const CvArr* src, CvScalar* mean, CvScalar* stdDev, const CvArr* mask=NULL) .. ocv:cfunction:: void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask=NULL )
.. ocv:pyoldfunction:: cv.AvgSdv(src, mask=None)-> (mean, stdDev)
.. ocv:pyoldfunction:: cv.AvgSdv(arr, mask=None) -> (mean, stdDev)
:param src: Source array that should have from 1 to 4 channels so that the results can be stored in :ocv:class:`Scalar_` 's. :param src: Source array that should have from 1 to 4 channels so that the results can be stored in :ocv:class:`Scalar_` 's.
@@ -1712,7 +1720,7 @@ Composes a multi-channel array from several single-channel arrays.
.. ocv:function:: void merge(const Mat* mv, size_t count, OutputArray dst) .. ocv:function:: void merge(const Mat* mv, size_t count, OutputArray dst)
.. ocv:function:: void merge(const vector<Mat>& mv, OutputArray dst) .. ocv:function:: void merge( const vector<Mat>& mv, OutputArray dst )
.. ocv:pyfunction:: cv2.merge(mv[, dst]) -> dst .. ocv:pyfunction:: cv2.merge(mv[, dst]) -> dst
@@ -1743,17 +1751,17 @@ min
--- ---
Calculates per-element minimum of two arrays or array and a scalar. Calculates per-element minimum of two arrays or array and a scalar.
.. ocv:function:: MatExpr min(const Mat& src1, const Mat& src2) .. ocv:function:: MatExpr min( const Mat& a, const Mat& b )
.. ocv:function:: MatExpr min(const Mat& src1, double value) .. ocv:function:: MatExpr min( const Mat& a, double s )
.. ocv:function:: MatExpr min(double value, const Mat& src1) .. ocv:function:: MatExpr min( double s, const Mat& a )
.. ocv:function:: void min(InputArray src1, InputArray src2, OutputArray dst) .. ocv:function:: void min(InputArray src1, InputArray src2, OutputArray dst)
.. ocv:function:: void min(const Mat& src1, const Mat& src2, Mat& dst) .. ocv:function:: void min(const Mat& src1, const Mat& src2, Mat& dst)
.. ocv:function:: void min(const Mat& src1, double value, Mat& dst) .. ocv:function:: void min( const Mat& src1, double src2, Mat& dst )
.. ocv:pyfunction:: cv2.min(src1, src2[, dst]) -> dst .. ocv:pyfunction:: cv2.min(src1, src2[, dst]) -> dst
@@ -1834,11 +1842,12 @@ Finds the global minimum and maximum in an array.
.. ocv:function:: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray()) .. ocv:function:: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())
.. ocv:function:: void minMaxLoc(const SparseMat& src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0) .. ocv:function:: void minMaxLoc( const SparseMat& a, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0 )
.. ocv:pyfunction:: cv2.minMaxLoc(src[, mask]) -> minVal, maxVal, minLoc, maxLoc .. ocv:pyfunction:: cv2.minMaxLoc(src[, mask]) -> minVal, maxVal, minLoc, maxLoc
.. ocv:cfunction:: void cvMinMaxLoc(const CvArr* arr, double* minVal, double* maxVal, CvPoint* minLoc=NULL, CvPoint* maxLoc=NULL, const CvArr* mask=NULL) .. ocv:cfunction:: void cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, CvPoint* min_loc=NULL, CvPoint* max_loc=NULL, const CvArr* mask=NULL )
.. ocv:pyoldfunction:: cv.MinMaxLoc(arr, mask=None)-> (minVal, maxVal, minLoc, maxLoc) .. ocv:pyoldfunction:: cv.MinMaxLoc(arr, mask=None)-> (minVal, maxVal, minLoc, maxLoc)
:param src: Source single-channel array. :param src: Source single-channel array.
@@ -1879,22 +1888,23 @@ mixChannels
----------- -----------
Copies specified channels from input arrays to the specified channels of output arrays. Copies specified channels from input arrays to the specified channels of output arrays.
.. ocv:function:: void mixChannels(const Mat* src, int nsrc, Mat* dst, int ndst, const int* fromTo, size_t npairs) .. ocv:function:: void mixChannels( const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, const int* fromTo, size_t npairs )
.. ocv:function:: void mixChannels(const vector<Mat>& src, vector<Mat>& dst, const int* fromTo, int npairs) .. ocv:function:: void mixChannels( const vector<Mat>& src, vector<Mat>& dst, const int* fromTo, size_t npairs )
.. ocv:pyfunction:: cv2.mixChannels(src, dst, fromTo) -> None .. ocv:pyfunction:: cv2.mixChannels(src, dst, fromTo) -> None
.. ocv:cfunction:: void cvMixChannels(const CvArr** src, int srcCount, CvArr** dst, int dstCount, const int* fromTo, int pairCount) .. ocv:cfunction:: void cvMixChannels( const CvArr** src, int src_count, CvArr** dst, int dst_count, const int* from_to, int pair_count )
.. ocv:pyoldfunction:: cv.MixChannels(src, dst, fromTo) -> None .. ocv:pyoldfunction:: cv.MixChannels(src, dst, fromTo) -> None
:param src: Input array or vector of matrices. All the matrices must have the same size and the same depth. :param src: Input array or vector of matrices. All the matrices must have the same size and the same depth.
:param nsrc: Number of matrices in ``src`` . :param nsrcs: Number of matrices in ``src`` .
:param dst: Output array or vector of matrices. All the matrices *must be allocated* . Their size and depth must be the same as in ``src[0]`` . :param dst: Output array or vector of matrices. All the matrices *must be allocated* . Their size and depth must be the same as in ``src[0]`` .
:param ndst: Number of matrices in ``dst`` . :param ndsts: Number of matrices in ``dst`` .
:param fromTo: Array of index pairs specifying which channels are copied and where. ``fromTo[k*2]`` is a 0-based index of the input channel in ``src`` . ``fromTo[k*2+1]`` is an index of the output channel in ``dst`` . The continuous channel numbering is used: the first input image channels are indexed from ``0`` to ``src[0].channels()-1`` , the second input image channels are indexed from ``src[0].channels()`` to ``src[0].channels() + src[1].channels()-1``, and so on. The same scheme is used for the output image channels. As a special case, when ``fromTo[k*2]`` is negative, the corresponding output channel is filled with zero . :param fromTo: Array of index pairs specifying which channels are copied and where. ``fromTo[k*2]`` is a 0-based index of the input channel in ``src`` . ``fromTo[k*2+1]`` is an index of the output channel in ``dst`` . The continuous channel numbering is used: the first input image channels are indexed from ``0`` to ``src[0].channels()-1`` , the second input image channels are indexed from ``src[0].channels()`` to ``src[0].channels() + src[1].channels()-1``, and so on. The same scheme is used for the output image channels. As a special case, when ``fromTo[k*2]`` is negative, the corresponding output channel is filled with zero .
@@ -1935,7 +1945,7 @@ mulSpectrums
------------ ------------
Performs the per-element multiplication of two Fourier spectrums. Performs the per-element multiplication of two Fourier spectrums.
.. ocv:function:: void mulSpectrums(InputArray src1, InputArray src2, OutputArray dst, int flags, bool conj=false) .. ocv:function:: void mulSpectrums( InputArray a, InputArray b, OutputArray c, int flags, bool conjB=false )
.. ocv:pyfunction:: cv2.mulSpectrums(a, b, flags[, c[, conjB]]) -> c .. ocv:pyfunction:: cv2.mulSpectrums(a, b, flags[, c[, conjB]]) -> c
@@ -1950,13 +1960,13 @@ Performs the per-element multiplication of two Fourier spectrums.
:param flags: Operation flags. Currently, the only supported flag is ``DFT_ROWS``, which indicates that each row of ``src1`` and ``src2`` is an independent 1D Fourier spectrum. :param flags: Operation flags. Currently, the only supported flag is ``DFT_ROWS``, which indicates that each row of ``src1`` and ``src2`` is an independent 1D Fourier spectrum.
:param conj: Optional flag that conjugates the second source array before the multiplication (true) or not (false). :param conjB: Optional flag that conjugates the second source array before the multiplication (true) or not (false).
The function ``mulSpectrums`` performs the per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform. The function ``mulSpectrums`` performs the per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
The function, together with The function, together with
:ocv:func:`dft` and :ocv:func:`dft` and
:ocv:func:`idft` , may be used to calculate convolution (pass ``conj=false`` ) or correlation (pass ``conj=false`` ) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per element) with an optional conjugation of the second-array elements. When the arrays are real, they are assumed to be CCS-packed (see :ocv:func:`idft` , may be used to calculate convolution (pass ``conjB=false`` ) or correlation (pass ``conjB=true`` ) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per element) with an optional conjugation of the second-array elements. When the arrays are real, they are assumed to be CCS-packed (see
:ocv:func:`dft` for details). :ocv:func:`dft` for details).
@@ -1965,12 +1975,12 @@ multiply
-------- --------
Calculates the per-element scaled product of two arrays. Calculates the per-element scaled product of two arrays.
.. ocv:function:: void multiply(InputArray src1, InputArray src2, OutputArray dst, double scale=1) .. ocv:function:: void multiply( InputArray src1, InputArray src2, OutputArray dst, double scale=1, int dtype=-1 )
.. ocv:pyfunction:: cv2.multiply(src1, src2[, dst[, scale[, dtype]]]) -> dst .. ocv:pyfunction:: cv2.multiply(src1, src2[, dst[, scale[, dtype]]]) -> dst
.. ocv:cfunction:: void cvMul(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1) .. ocv:cfunction:: void cvMul(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1)
.. ocv:pyoldfunction:: cv.Mul(src1, src2, dst, scale)-> None .. ocv:pyoldfunction:: cv.Mul(src1, src2, dst, scale=1) -> None
:param src1: First source array. :param src1: First source array.
@@ -2014,12 +2024,13 @@ mulTransposed
------------- -------------
Calculates the product of a matrix and its transposition. Calculates the product of a matrix and its transposition.
.. ocv:function:: void mulTransposed(InputArray src, OutputArray dst, bool aTa, InputArray delta=noArray(), double scale=1, int rtype=-1) .. ocv:function:: void mulTransposed( InputArray src, OutputArray dst, bool aTa, InputArray delta=noArray(), double scale=1, int dtype=-1 )
.. ocv:pyfunction:: cv2.mulTransposed(src, aTa[, dst[, delta[, scale[, dtype]]]]) -> dst .. ocv:pyfunction:: cv2.mulTransposed(src, aTa[, dst[, delta[, scale[, dtype]]]]) -> dst
.. ocv:cfunction:: void cvMulTransposed(const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0) .. ocv:cfunction:: void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1. )
.. ocv:pyoldfunction:: cv.MulTransposed(src, dst, order, delta=None, scale)-> None
.. ocv:pyoldfunction:: cv.MulTransposed(src, dst, order, delta=None, scale=1.0) -> None
:param src: Source single-channel matrix. Note that unlike :ocv:func:`gemm`, the function can multiply not only floating-point matrices. :param src: Source single-channel matrix. Note that unlike :ocv:func:`gemm`, the function can multiply not only floating-point matrices.
@@ -2027,11 +2038,11 @@ Calculates the product of a matrix and its transposition.
:param aTa: Flag specifying the multiplication ordering. See the description below. :param aTa: Flag specifying the multiplication ordering. See the description below.
:param delta: Optional delta matrix subtracted from ``src`` before the multiplication. When the matrix is empty ( ``delta=noArray()`` ), it is assumed to be zero, that is, nothing is subtracted. If it has the same size as ``src`` , it is simply subtracted. Otherwise, it is "repeated" (see :ocv:func:`repeat` ) to cover the full ``src`` and then subtracted. Type of the delta matrix, when it is not empty, must be the same as the type of created destination matrix. See the ``rtype`` parameter description below. :param delta: Optional delta matrix subtracted from ``src`` before the multiplication. When the matrix is empty ( ``delta=noArray()`` ), it is assumed to be zero, that is, nothing is subtracted. If it has the same size as ``src`` , it is simply subtracted. Otherwise, it is "repeated" (see :ocv:func:`repeat` ) to cover the full ``src`` and then subtracted. Type of the delta matrix, when it is not empty, must be the same as the type of created destination matrix. See the ``dtype`` parameter description below.
:param scale: Optional scale factor for the matrix product. :param scale: Optional scale factor for the matrix product.
:param rtype: Optional type of the destination matrix. When it is negative, the destination matrix will have the same type as ``src`` . Otherwise, it will be ``type=CV_MAT_DEPTH(rtype)`` that should be either ``CV_32F`` or ``CV_64F`` . :param dtype: Optional type of the destination matrix. When it is negative, the destination matrix will have the same type as ``src`` . Otherwise, it will be ``type=CV_MAT_DEPTH(dtype)`` that should be either ``CV_32F`` or ``CV_64F`` .
The function ``mulTransposed`` calculates the product of ``src`` and its transposition: The function ``mulTransposed`` calculates the product of ``src`` and its transposition:
@@ -2062,15 +2073,16 @@ Calculates an absolute array norm, an absolute difference norm, or a relative di
.. ocv:function:: double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray()) .. ocv:function:: double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray())
.. ocv:function:: double norm(InputArray src1, InputArray src2, int normType, InputArray mask=noArray()) .. ocv:function:: double norm( InputArray src1, InputArray src2, int normType=NORM_L2, InputArray mask=noArray() )
.. ocv:function:: double norm( const SparseMat& src, int normType ) .. ocv:function:: double norm( const SparseMat& src, int normType )
.. ocv:pyfunction:: cv2.norm(src1[, normType[, mask]]) -> retval .. ocv:pyfunction:: cv2.norm(src1[, normType[, mask]]) -> retval
.. ocv:pyfunction:: cv2.norm(src1, src2[, normType[, mask]]) -> retval .. ocv:pyfunction:: cv2.norm(src1, src2[, normType[, mask]]) -> retval
.. ocv:cfunction:: double cvNorm(const CvArr* arr1, const CvArr* arr2=NULL, int normType=CV_L2, const CvArr* mask=NULL) .. ocv:cfunction:: double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm_type=CV_L2, const CvArr* mask=NULL )
.. ocv:pyoldfunction:: cv.Norm(arr1, arr2, normType=CV_L2, mask=None)-> double
.. ocv:pyoldfunction:: cv.Norm(arr1, arr2, normType=CV_L2, mask=None) -> float
:param src1: First source array. :param src1: First source array.
@@ -2116,7 +2128,7 @@ normalize
--------- ---------
Normalizes the norm or value range of an array. Normalizes the norm or value range of an array.
.. ocv:function:: void normalize(const InputArray src, OutputArray dst, double alpha=1, double beta=0, int normType=NORM_L2, int rtype=-1, InputArray mask=noArray()) .. ocv:function:: void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0, int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray() )
.. ocv:function:: void normalize(const SparseMat& src, SparseMat& dst, double alpha, int normType) .. ocv:function:: void normalize(const SparseMat& src, SparseMat& dst, double alpha, int normType)
@@ -2132,7 +2144,7 @@ Normalizes the norm or value range of an array.
:param normType: Normalization type. See the details below. :param normType: Normalization type. See the details below.
:param rtype: When the parameter is negative, the destination array has the same type as ``src``. Otherwise, it has the same number of channels as ``src`` and the depth ``=CV_MAT_DEPTH(rtype)`` . :param dtype: When the parameter is negative, the destination array has the same type as ``src``. Otherwise, it has the same number of channels as ``src`` and the depth ``=CV_MAT_DEPTH(dtype)`` .
:param mask: Optional operation mask. :param mask: Optional operation mask.
@@ -2279,7 +2291,7 @@ Projects vector(s) to the principal component subspace.
.. ocv:function:: void PCA::project(InputArray vec, OutputArray result) const .. ocv:function:: void PCA::project(InputArray vec, OutputArray result) const
.. ocv:pyfunction:: cv2.PCAProject(vec, mean, eigenvectors[, result]) -> result .. ocv:pyfunction:: cv2.PCAProject(data, mean, eigenvectors[, result]) -> result
:param vec: Input vector(s). They must have the same dimensionality and the same layout as the input data used at PCA phase. That is, if ``CV_PCA_DATA_AS_ROW`` are specified, then ``vec.cols==data.cols`` (vector dimensionality) and ``vec.rows`` is the number of vectors to project. The same is true for the ``CV_PCA_DATA_AS_COL`` case. :param vec: Input vector(s). They must have the same dimensionality and the same layout as the input data used at PCA phase. That is, if ``CV_PCA_DATA_AS_ROW`` are specified, then ``vec.cols==data.cols`` (vector dimensionality) and ``vec.rows`` is the number of vectors to project. The same is true for the ``CV_PCA_DATA_AS_COL`` case.
@@ -2297,7 +2309,7 @@ Reconstructs vectors from their PC projections.
.. ocv:function:: void PCA::backProject(InputArray vec, OutputArray result) const .. ocv:function:: void PCA::backProject(InputArray vec, OutputArray result) const
.. ocv:pyfunction:: cv2.PCABackProject(vec, mean, eigenvectors[, result]) -> result .. ocv:pyfunction:: cv2.PCABackProject(data, mean, eigenvectors[, result]) -> result
:param vec: Coordinates of the vectors in the principal component subspace. The layout and size are the same as of ``PCA::project`` output vectors. :param vec: Coordinates of the vectors in the principal component subspace. The layout and size are the same as of ``PCA::project`` output vectors.
@@ -2312,7 +2324,7 @@ perspectiveTransform
-------------------- --------------------
Performs the perspective matrix transformation of vectors. Performs the perspective matrix transformation of vectors.
.. ocv:function:: void perspectiveTransform(InputArray src, OutputArray dst, InputArray mtx) .. ocv:function:: void perspectiveTransform( InputArray src, OutputArray dst, InputArray m )
.. ocv:pyfunction:: cv2.perspectiveTransform(src, m[, dst]) -> dst .. ocv:pyfunction:: cv2.perspectiveTransform(src, m[, dst]) -> dst
@@ -2323,7 +2335,7 @@ Performs the perspective matrix transformation of vectors.
:param dst: Destination array of the same size and type as ``src`` . :param dst: Destination array of the same size and type as ``src`` .
:param mtx: ``3x3`` or ``4x4`` floating-point transformation matrix. :param m: ``3x3`` or ``4x4`` floating-point transformation matrix.
The function ``perspectiveTransform`` transforms every element of ``src`` by treating it as a 2D or 3D vector, in the following way: The function ``perspectiveTransform`` transforms every element of ``src`` by treating it as a 2D or 3D vector, in the following way:
@@ -2389,7 +2401,8 @@ Computes x and y coordinates of 2D vectors from their magnitude and angle.
.. ocv:pyfunction:: cv2.polarToCart(magnitude, angle[, x[, y[, angleInDegrees]]]) -> x, y .. ocv:pyfunction:: cv2.polarToCart(magnitude, angle[, x[, y[, angleInDegrees]]]) -> x, y
.. ocv:cfunction:: void cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angleInDegrees=0) .. ocv:cfunction:: void cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angle_in_degrees=0 )
.. ocv:pyoldfunction:: cv.PolarToCart(magnitude, angle, x, y, angleInDegrees=0)-> None .. ocv:pyoldfunction:: cv.PolarToCart(magnitude, angle, x, y, angleInDegrees=0)-> None
:param magnitude: Source floating-point array of magnitudes of 2D vectors. It can be an empty matrix ( ``=Mat()`` ). In this case, the function assumes that all the magnitudes are =1. If it is not empty, it must have the same size and type as ``angle`` . :param magnitude: Source floating-point array of magnitudes of 2D vectors. It can be an empty matrix ( ``=Mat()`` ). In this case, the function assumes that all the magnitudes are =1. If it is not empty, it must have the same size and type as ``angle`` .
@@ -2426,7 +2439,7 @@ pow
--- ---
Raises every array element to a power. Raises every array element to a power.
.. ocv:function:: void pow(InputArray src, double p, OutputArray dst) .. ocv:function:: void pow( InputArray src, double power, OutputArray dst )
.. ocv:pyfunction:: cv2.pow(src, power[, dst]) -> dst .. ocv:pyfunction:: cv2.pow(src, power[, dst]) -> dst
@@ -2435,15 +2448,15 @@ Raises every array element to a power.
:param src: Source array. :param src: Source array.
:param p: Exponent of power. :param power: Exponent of power.
:param dst: Destination array of the same size and type as ``src`` . :param dst: Destination array of the same size and type as ``src`` .
The function ``pow`` raises every element of the input array to ``p`` : The function ``pow`` raises every element of the input array to ``power`` :
.. math:: .. math::
\texttt{dst} (I) = \fork{\texttt{src}(I)^p}{if \texttt{p} is integer}{|\texttt{src}(I)|^p}{otherwise} \texttt{dst} (I) = \fork{\texttt{src}(I)^power}{if \texttt{power} is integer}{|\texttt{src}(I)|^power}{otherwise}
So, for a non-integer power exponent, the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations. In the example below, computing the 5th root of array ``src`` shows: :: So, for a non-integer power exponent, the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations. In the example below, computing the 5th root of array ``src`` shows: ::
@@ -2452,7 +2465,7 @@ So, for a non-integer power exponent, the absolute values of input array element
subtract(Scalar::all(0), dst, dst, mask); subtract(Scalar::all(0), dst, dst, mask);
For some values of ``p`` , such as integer values, 0.5 and -0.5, specialized faster algorithms are used. For some values of ``power`` , such as integer values, 0.5 and -0.5, specialized faster algorithms are used.
Special values (NaN, Inf) are not handled. Special values (NaN, Inf) are not handled.
@@ -2617,11 +2630,11 @@ Generates a single uniformly-distributed random number or an array of random num
.. ocv:function:: template<typename _Tp> _Tp randu() .. ocv:function:: template<typename _Tp> _Tp randu()
.. ocv:function:: void randu(InputOutputArray mtx, InputArray low, InputArray high) .. ocv:function:: void randu( InputOutputArray dst, InputArray low, InputArray high )
.. ocv:pyfunction:: cv2.randu(dst, low, high) -> None .. ocv:pyfunction:: cv2.randu(dst, low, high) -> None
:param mtx: Output array of random numbers. The array must be pre-allocated. :param dst: Output array of random numbers. The array must be pre-allocated.
:param low: Inclusive lower boundary of the generated random numbers. :param low: Inclusive lower boundary of the generated random numbers.
@@ -2630,11 +2643,11 @@ Generates a single uniformly-distributed random number or an array of random num
The template functions ``randu`` generate and return the next uniformly-distributed random value of the specified type. ``randu<int>()`` is an equivalent to ``(int)theRNG();`` , and so on. See The template functions ``randu`` generate and return the next uniformly-distributed random value of the specified type. ``randu<int>()`` is an equivalent to ``(int)theRNG();`` , and so on. See
:ocv:class:`RNG` description. :ocv:class:`RNG` description.
The second non-template variant of the function fills the matrix ``mtx`` with uniformly-distributed random numbers from the specified range: The second non-template variant of the function fills the matrix ``dst`` with uniformly-distributed random numbers from the specified range:
.. math:: .. math::
\texttt{low} _c \leq \texttt{mtx} (I)_c < \texttt{high} _c \texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c
.. seealso:: .. seealso::
@@ -2648,17 +2661,17 @@ randn
----- -----
Fills the array with normally distributed random numbers. Fills the array with normally distributed random numbers.
.. ocv:function:: void randn(InputOutputArray mtx, InputArray mean, InputArray stddev) .. ocv:function:: void randn( InputOutputArray dst, InputArray mean, InputArray stddev )
.. ocv:pyfunction:: cv2.randn(dst, mean, stddev) -> None .. ocv:pyfunction:: cv2.randn(dst, mean, stddev) -> None
:param mtx: Output array of random numbers. The array must be pre-allocated and have 1 to 4 channels. :param dst: Output array of random numbers. The array must be pre-allocated and have 1 to 4 channels.
:param mean: Mean value (expectation) of the generated random numbers. :param mean: Mean value (expectation) of the generated random numbers.
:param stddev: Standard deviation of the generated random numbers. It can be either a vector (in which case a diagonal standard deviation matrix is assumed) or a square matrix. :param stddev: Standard deviation of the generated random numbers. It can be either a vector (in which case a diagonal standard deviation matrix is assumed) or a square matrix.
The function ``randn`` fills the matrix ``mtx`` with normally distributed random numbers with the specified mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the value range of the destination array data type. The function ``randn`` fills the matrix ``dst`` with normally distributed random numbers with the specified mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the value range of the destination array data type.
.. seealso:: .. seealso::
@@ -2671,17 +2684,17 @@ randShuffle
----------- -----------
Shuffles the array elements randomly. Shuffles the array elements randomly.
.. ocv:function:: void randShuffle(InputOutputArray mtx, double iterFactor=1., RNG* rng=0) .. ocv:function:: void randShuffle( InputOutputArray dst, double iterFactor=1., RNG* rng=0 )
.. ocv:pyfunction:: cv2.randShuffle(src[, dst[, iterFactor]]) -> dst .. ocv:pyfunction:: cv2.randShuffle(dst[, iterFactor]) -> None
:param mtx: Input/output numerical 1D array. :param dst: Input/output numerical 1D array.
:param iterFactor: Scale factor that determines the number of random swap operations. See the details below. :param iterFactor: Scale factor that determines the number of random swap operations. See the details below.
:param rng: Optional random number generator used for shuffling. If it is zero, :ocv:func:`theRNG` () is used instead. :param rng: Optional random number generator used for shuffling. If it is zero, :ocv:func:`theRNG` () is used instead.
The function ``randShuffle`` shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be ``mtx.rows*mtx.cols*iterFactor`` . The function ``randShuffle`` shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be ``dst.rows*dst.cols*iterFactor`` .
.. seealso:: .. seealso::
@@ -2694,20 +2707,20 @@ reduce
------ ------
Reduces a matrix to a vector. Reduces a matrix to a vector.
.. ocv:function:: void reduce(InputArray mtx, OutputArray vec, int dim, int reduceOp, int dtype=-1) .. ocv:function:: void reduce( InputArray src, OutputArray dst, int dim, int rtype, int dtype=-1 )
.. ocv:pyfunction:: cv2.reduce(src, dim, rtype[, dst[, dtype]]) -> dst .. ocv:pyfunction:: cv2.reduce(src, dim, rtype[, dst[, dtype]]) -> dst
.. ocv:cfunction:: void cvReduce(const CvArr* src, CvArr* dst, int dim=-1, int op=CV_REDUCE_SUM) .. ocv:cfunction:: void cvReduce(const CvArr* src, CvArr* dst, int dim=-1, int op=CV_REDUCE_SUM)
.. ocv:pyoldfunction:: cv.Reduce(src, dst, dim=-1, op=CV_REDUCE_SUM)-> None .. ocv:pyoldfunction:: cv.Reduce(src, dst, dim=-1, op=CV_REDUCE_SUM)-> None
:param mtx: Source 2D matrix. :param src: Source 2D matrix.
:param vec: Destination vector. Its size and type is defined by ``dim`` and ``dtype`` parameters. :param dst: Destination vector. Its size and type is defined by ``dim`` and ``dtype`` parameters.
:param dim: Dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row. 1 means that the matrix is reduced to a single column. :param dim: Dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row. 1 means that the matrix is reduced to a single column.
:param reduceOp: Reduction operation that could be one of the following: :param rtype: Reduction operation that could be one of the following:
* **CV_REDUCE_SUM** The output is the sum of all rows/columns of the matrix. * **CV_REDUCE_SUM** The output is the sum of all rows/columns of the matrix.
@@ -2717,7 +2730,7 @@ Reduces a matrix to a vector.
* **CV_REDUCE_MIN** The output is the minimum (column/row-wise) of all rows/columns of the matrix. * **CV_REDUCE_MIN** The output is the minimum (column/row-wise) of all rows/columns of the matrix.
:param dtype: When it is negative, the destination vector will have the same type as the source matrix. Otherwise, its type will be ``CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), mtx.channels())`` . :param dtype: When it is negative, the destination vector will have the same type as the source matrix. Otherwise, its type will be ``CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels())`` .
The function ``reduce`` reduces the matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of a raster image. In case of ``CV_REDUCE_SUM`` and ``CV_REDUCE_AVG`` , the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes. The function ``reduce`` reduces the matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of a raster image. In case of ``CV_REDUCE_SUM`` and ``CV_REDUCE_AVG`` , the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
@@ -2731,11 +2744,12 @@ Fills the destination array with repeated copies of the source array.
.. ocv:function:: void repeat(InputArray src, int ny, int nx, OutputArray dst) .. ocv:function:: void repeat(InputArray src, int ny, int nx, OutputArray dst)
.. ocv:function:: Mat repeat(InputArray src, int ny, int nx) .. ocv:function:: Mat repeat( const Mat& src, int ny, int nx )
.. ocv:pyfunction:: cv2.repeat(src, ny, nx[, dst]) -> dst .. ocv:pyfunction:: cv2.repeat(src, ny, nx[, dst]) -> dst
.. ocv:cfunction:: void cvRepeat(const CvArr* src, CvArr* dst) .. ocv:cfunction:: void cvRepeat(const CvArr* src, CvArr* dst)
.. ocv:pyoldfunction:: cv.Repeat(src, dst)-> None .. ocv:pyoldfunction:: cv.Repeat(src, dst)-> None
:param src: Source array to replicate. :param src: Source array to replicate.
@@ -2767,7 +2781,7 @@ scaleAdd
-------- --------
Calculates the sum of a scaled array and another array. Calculates the sum of a scaled array and another array.
.. ocv:function:: void scaleAdd(InputArray src1, double scale, InputArray src2, OutputArray dst) .. ocv:function:: void scaleAdd( InputArray src1, double alpha, InputArray src2, OutputArray dst )
.. ocv:pyfunction:: cv2.scaleAdd(src1, alpha, src2[, dst]) -> dst .. ocv:pyfunction:: cv2.scaleAdd(src1, alpha, src2[, dst]) -> dst
@@ -2810,14 +2824,15 @@ setIdentity
----------- -----------
Initializes a scaled identity matrix. Initializes a scaled identity matrix.
.. ocv:function:: void setIdentity(InputOutputArray dst, const Scalar& value=Scalar(1)) .. ocv:function:: void setIdentity( InputOutputArray mtx, const Scalar& s=Scalar(1) )
.. ocv:pyfunction:: cv2.setIdentity(mtx[, s]) -> None .. ocv:pyfunction:: cv2.setIdentity(mtx[, s]) -> None
.. ocv:cfunction:: void cvSetIdentity(CvArr* mat, CvScalar value=cvRealScalar(1)) .. ocv:cfunction:: void cvSetIdentity(CvArr* mat, CvScalar value=cvRealScalar(1))
.. ocv:pyoldfunction:: cv.SetIdentity(mat, value=1)-> None .. ocv:pyoldfunction:: cv.SetIdentity(mat, value=1)-> None
:param dst: Matrix to initialize (not necessarily square). :param mtx: Matrix to initialize (not necessarily square).
:param value: Value to assign to diagonal elements. :param value: Value to assign to diagonal elements.
@@ -2826,7 +2841,7 @@ The function
.. math:: .. math::
\texttt{dst} (i,j)= \fork{\texttt{value}}{ if $i=j$}{0}{otherwise} \texttt{mtx} (i,j)= \fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
The function can also be emulated using the matrix initializers and the matrix expressions: :: The function can also be emulated using the matrix initializers and the matrix expressions: ::
@@ -2898,11 +2913,12 @@ solveCubic
-------------- --------------
Finds the real roots of a cubic equation. Finds the real roots of a cubic equation.
.. ocv:function:: void solveCubic(InputArray coeffs, OutputArray roots) .. ocv:function:: int solveCubic( InputArray coeffs, OutputArray roots )
.. ocv:pyfunction:: cv2.solveCubic(coeffs[, roots]) -> retval, roots .. ocv:pyfunction:: cv2.solveCubic(coeffs[, roots]) -> retval, roots
.. ocv:cfunction:: void cvSolveCubic(const CvArr* coeffs, CvArr* roots) .. ocv:cfunction:: int cvSolveCubic( const CvMat* coeffs, CvMat* roots )
.. ocv:pyoldfunction:: cv.SolveCubic(coeffs, roots)-> None .. ocv:pyoldfunction:: cv.SolveCubic(coeffs, roots)-> None
:param coeffs: Equation coefficients, an array of 3 or 4 elements. :param coeffs: Equation coefficients, an array of 3 or 4 elements.
@@ -2931,7 +2947,7 @@ solvePoly
--------- ---------
Finds the real or complex roots of a polynomial equation. Finds the real or complex roots of a polynomial equation.
.. ocv:function:: void solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300) .. ocv:function:: double solvePoly( InputArray coeffs, OutputArray roots, int maxIters=300 )
.. ocv:pyfunction:: cv2.solvePoly(coeffs[, roots[, maxIters]]) -> retval, roots .. ocv:pyfunction:: cv2.solvePoly(coeffs[, roots[, maxIters]]) -> retval, roots
@@ -3022,24 +3038,25 @@ split
----- -----
Divides a multi-channel array into several single-channel arrays. Divides a multi-channel array into several single-channel arrays.
.. ocv:function:: void split(const Mat& mtx, Mat* mv) .. ocv:function:: void split( const Mat& src, Mat* mvbegin )
.. ocv:function:: void split(const Mat& mtx, vector<Mat>& mv) .. ocv:function:: void split( const Mat& m, vector<Mat>& mv )
.. ocv:pyfunction:: cv2.split(m, mv) -> None .. ocv:pyfunction:: cv2.split(m[, mv]) -> mv
.. ocv:cfunction:: void cvSplit(const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3) .. ocv:cfunction:: void cvSplit(const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3)
.. ocv:pyoldfunction:: cv.Split(src, dst0, dst1, dst2, dst3)-> None .. ocv:pyoldfunction:: cv.Split(src, dst0, dst1, dst2, dst3)-> None
:param mtx: Source multi-channel array. :param src: Source multi-channel array.
:param mv: Destination array or vector of arrays. In the first variant of the function the number of arrays must match ``mtx.channels()`` . The arrays themselves are reallocated, if needed. :param mv: Destination array or vector of arrays. In the first variant of the function the number of arrays must match ``src.channels()`` . The arrays themselves are reallocated, if needed.
The functions ``split`` split a multi-channel array into separate single-channel arrays: The functions ``split`` split a multi-channel array into separate single-channel arrays:
.. math:: .. math::
\texttt{mv} [c](I) = \texttt{mtx} (I)_c \texttt{mv} [c](I) = \texttt{src} (I)_c
If you need to extract a single channel or do some other sophisticated channel permutation, use If you need to extract a single channel or do some other sophisticated channel permutation, use
:ocv:func:`mixChannels` . :ocv:func:`mixChannels` .
@@ -3085,12 +3102,12 @@ Calculates the per-element difference between two arrays or array and a scalar.
.. ocv:pyfunction:: cv2.subtract(src1, src2[, dst[, mask[, dtype]]]) -> dst .. ocv:pyfunction:: cv2.subtract(src1, src2[, dst[, mask[, dtype]]]) -> dst
.. ocv:cfunction:: void cvSub(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL) .. ocv:cfunction:: void cvSub(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
.. ocv:cfunction:: void cvSubRS(const CvArr* src1, CvScalar src2, CvArr* dst, const CvArr* mask=NULL) .. ocv:cfunction:: void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL )
.. ocv:cfunction:: void cvSubS(const CvArr* src1, CvScalar src2, CvArr* dst, const CvArr* mask=NULL) .. ocv:cfunction:: void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL )
.. ocv:pyoldfunction:: cv.Sub(src1, src2, dst, mask=None)-> None .. ocv:pyoldfunction:: cv.Sub(src1, src2, dst, mask=None) -> None
.. ocv:pyoldfunction:: cv.SubRS(src1, src2, dst, mask=None)-> None .. ocv:pyoldfunction:: cv.SubRS(src, value, dst, mask=None) -> None
.. ocv:pyoldfunction:: cv.SubS(src1, src2, dst, mask=None)-> None .. ocv:pyoldfunction:: cv.SubS(src, value, dst, mask=None) -> None
:param src1: First source array or a scalar. :param src1: First source array or a scalar.
@@ -3176,9 +3193,9 @@ The constructors.
.. ocv:function:: SVD::SVD() .. ocv:function:: SVD::SVD()
.. ocv:function:: SVD::SVD( InputArray A, int flags=0 ) .. ocv:function:: SVD::SVD( InputArray src, int flags=0 )
:param A: Decomposed matrix. :param src: Decomposed matrix.
:param flags: Operation flags. :param flags: Operation flags.
@@ -3222,9 +3239,9 @@ Performs SVD of a matrix
.. ocv:pyfunction:: cv2.SVDecomp(src[, w[, u[, vt[, flags]]]]) -> w, u, vt .. ocv:pyfunction:: cv2.SVDecomp(src[, w[, u[, vt[, flags]]]]) -> w, u, vt
.. ocv:cfunction:: void cvSVD( CvArr* src, CvArr* w, CvArr* u=NULL, CvArr* v=NULL, int flags=0) .. ocv:cfunction:: void cvSVD( CvArr* A, CvArr* W, CvArr* U=NULL, CvArr* V=NULL, int flags=0 )
.. ocv:pyoldfunction:: cv.SVD(src, w, u=None, v=None, flags=0)-> None .. ocv:pyoldfunction:: cv.SVD(A, W, U=None, V=None, flags=0) -> None
:param src: Decomposed matrix :param src: Decomposed matrix
@@ -3232,7 +3249,7 @@ Performs SVD of a matrix
:param u: Computed left singular vectors :param u: Computed left singular vectors
:param v: Computed right singular vectors :param V: Computed right singular vectors
:param vt: Transposed matrix of right singular values :param vt: Transposed matrix of right singular values
@@ -3272,15 +3289,15 @@ Performs a singular value back substitution.
.. ocv:pyfunction:: cv2.SVBackSubst(w, u, vt, rhs[, dst]) -> dst .. ocv:pyfunction:: cv2.SVBackSubst(w, u, vt, rhs[, dst]) -> dst
.. ocv:cfunction:: void cvSVBkSb( const CvArr* w, const CvArr* u, const CvArr* v, const CvArr* rhs, CvArr* dst, int flags) .. ocv:cfunction:: void cvSVBkSb( const CvArr* W, const CvArr* U, const CvArr* V, const CvArr* B, CvArr* X, int flags )
.. ocv:pyoldfunction:: cv.SVBkSb(w, u, v, rhs, dst, flags)-> None .. ocv:pyoldfunction:: cv.SVBkSb(W, U, V, B, X, flags) -> None
:param w: Singular values :param w: Singular values
:param u: Left singular vectors :param u: Left singular vectors
:param v: Right singular vectors :param V: Right singular vectors
:param vt: Transposed matrix of right singular vectors. :param vt: Transposed matrix of right singular vectors.
@@ -3304,12 +3321,13 @@ sum
--- ---
Calculates the sum of array elements. Calculates the sum of array elements.
.. ocv:function:: Scalar sum(InputArray arr) .. ocv:function:: Scalar sum( InputArray src )
.. ocv:pyfunction:: cv2.sumElems(arr) -> retval .. ocv:pyfunction:: cv2.sumElems(src) -> retval
.. ocv:cfunction:: CvScalar cvSum(const CvArr* arr) .. ocv:cfunction:: CvScalar cvSum(const CvArr* arr)
.. ocv:pyoldfunction:: cv.Sum(arr)-> CvScalar
.. ocv:pyoldfunction:: cv.Sum(arr) -> scalar
:param arr: Source array that must have from 1 to 4 channels. :param arr: Source array that must have from 1 to 4 channels.
@@ -3348,12 +3366,13 @@ trace
----- -----
Returns the trace of a matrix. Returns the trace of a matrix.
.. ocv:function:: Scalar trace(InputArray mat) .. ocv:function:: Scalar trace( InputArray mtx )
.. ocv:pyfunction:: cv2.trace(mat) -> retval .. ocv:pyfunction:: cv2.trace(mtx) -> retval
.. ocv:cfunction:: CvScalar cvTrace(const CvArr* mat) .. ocv:cfunction:: CvScalar cvTrace(const CvArr* mat)
.. ocv:pyoldfunction:: cv.Trace(mat)-> CvScalar
.. ocv:pyoldfunction:: cv.Trace(mat) -> scalar
:param mat: Source matrix. :param mat: Source matrix.
@@ -3369,37 +3388,38 @@ transform
--------- ---------
Performs the matrix transformation of every array element. Performs the matrix transformation of every array element.
.. ocv:function:: void transform(InputArray src, OutputArray dst, InputArray mtx ) .. ocv:function:: void transform( InputArray src, OutputArray dst, InputArray m )
.. ocv:pyfunction:: cv2.transform(src, mtx [, dst]) -> dst .. ocv:pyfunction:: cv2.transform(src, m[, dst]) -> dst
.. ocv:cfunction:: void cvTransform(const CvArr* src, CvArr* dst, const CvMat* mtx, const CvMat* shiftvec=NULL) .. ocv:cfunction:: void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL )
.. ocv:pyoldfunction:: cv.Transform(src, dst, mtx, shiftvec=None)-> None
:param src: Source array that must have as many channels (1 to 4) as ``mtx.cols`` or ``mtx.cols-1``. .. ocv:pyoldfunction:: cv.Transform(src, dst, transmat, shiftvec=None)-> None
:param dst: Destination array of the same size and depth as ``src`` . It has as many channels as ``mtx.rows`` . :param src: Source array that must have as many channels (1 to 4) as ``m.cols`` or ``m.cols-1``.
:param mtx: Transformation ``2x2`` or ``2x3`` floating-point matrix. :param dst: Destination array of the same size and depth as ``src`` . It has as many channels as ``m.rows`` .
:param shiftvec: Optional translation vector (when ``mtx`` is ``2x2``) :param m: Transformation ``2x2`` or ``2x3`` floating-point matrix.
:param shiftvec: Optional translation vector (when ``m`` is ``2x2``)
The function ``transform`` performs the matrix transformation of every element of the array ``src`` and stores the results in ``dst`` : The function ``transform`` performs the matrix transformation of every element of the array ``src`` and stores the results in ``dst`` :
.. math:: .. math::
\texttt{dst} (I) = \texttt{mtx} \cdot \texttt{src} (I) \texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)
(when ``mtx.cols=src.channels()`` ), or (when ``m.cols=src.channels()`` ), or
.. math:: .. math::
\texttt{dst} (I) = \texttt{mtx} \cdot [ \texttt{src} (I); 1] \texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]
(when ``mtx.cols=src.channels()+1`` ) (when ``m.cols=src.channels()+1`` )
Every element of the ``N`` -channel array ``src`` is interpreted as ``N`` -element vector that is transformed using Every element of the ``N`` -channel array ``src`` is interpreted as ``N`` -element vector that is transformed using
the ``M x N`` or ``M x (N+1)`` matrix ``mtx`` the ``M x N`` or ``M x (N+1)`` matrix ``m``
to ``M``-element vector - the corresponding element of the destination array ``dst`` . to ``M``-element vector - the corresponding element of the destination array ``dst`` .
The function may be used for geometrical transformation of The function may be used for geometrical transformation of
@@ -93,9 +93,9 @@ Computes the cube root of an argument.
.. ocv:pyfunction:: cv2.cubeRoot(val) -> retval .. 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. :param val: A function argument.
@@ -182,7 +182,7 @@ Signals an error and raises an exception.
.. ocv:function:: void error( const Exception& exc ) .. 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 exc: Exception to throw.
@@ -209,7 +209,7 @@ The macro ``CV_Error_`` can be used to construct an error message on-fly to incl
Exception Exception
--------- ---------
.. ocv:class:: Exception .. ocv:class:: Exception : public std::exception
Exception class passed to an error. :: Exception class passed to an error. ::
@@ -244,7 +244,8 @@ fastMalloc
-------------- --------------
Allocates an aligned memory buffer. 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 ) .. ocv:cfunction:: void* cvAlloc( size_t size )
:param size: Allocated buffer size. :param size: Allocated buffer size.
@@ -276,7 +277,7 @@ Returns a text string formatted using the ``printf``\ -like expression.
:param fmt: ``printf`` -compatible formatting specifiers. :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 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,7 +287,7 @@ Returns true if the specified feature is supported by the host hardware.
.. ocv:function:: bool checkHardwareSupport(int feature) .. ocv:function:: bool checkHardwareSupport(int feature)
.. ocv:cfunction:: int cvCheckHardwareSupport(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: :param feature: The feature of interest, one of:
@@ -419,13 +420,13 @@ setUseOptimized
----------------- -----------------
Enables or disables the optimized code. 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: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. 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.
+15 -4
View File
@@ -156,9 +156,9 @@ The constructors.
.. ocv:function:: FileStorage::FileStorage() .. 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: :param flags: Mode of operation. Possible values are:
@@ -168,6 +168,8 @@ The constructors.
* **FileStorage::APPEND** Open the file for appending. * **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. :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.
The full constructor opens the file. Alternatively you can use the default constructor and then call :ocv:func:`FileStorage::open`. The full constructor opens the file. Alternatively you can use the default constructor and then call :ocv:func:`FileStorage::open`.
@@ -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. 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 FileStorage::getFirstTopLevelNode
--------------------------------- ---------------------------------
Returns the first element of the top-level mapping. Returns the first element of the top-level mapping.
@@ -663,7 +674,7 @@ FileNodeIterator::operator +=
----------------------------- -----------------------------
Moves iterator forward by the specified offset. 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. :param ofs: Offset (possibly negative) to move the iterator.
@@ -672,7 +683,7 @@ FileNodeIterator::operator -=
----------------------------- -----------------------------
Moves iterator backward by the specified offset (possibly negative). 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. :param ofs: Offset (possibly negative) to move the iterator.
+43 -35
View File
@@ -897,7 +897,7 @@ class CV_EXPORTS RotatedRect
public: public:
//! various constructors //! various constructors
RotatedRect(); RotatedRect();
RotatedRect(const Point2f& _center, const Size2f& _size, float _angle); RotatedRect(const Point2f& center, const Size2f& size, float angle);
RotatedRect(const CvBox2D& box); RotatedRect(const CvBox2D& box);
//! returns 4 vertices of the rectangle //! returns 4 vertices of the rectangle
@@ -1305,6 +1305,7 @@ public:
template<typename _Tp> _InputArray(const vector<_Tp>& vec); template<typename _Tp> _InputArray(const vector<_Tp>& vec);
template<typename _Tp> _InputArray(const vector<vector<_Tp> >& vec); template<typename _Tp> _InputArray(const vector<vector<_Tp> >& vec);
_InputArray(const vector<Mat>& vec); _InputArray(const vector<Mat>& vec);
template<typename _Tp> _InputArray(const vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputArray(const Mat_<_Tp>& m); template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx); template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
_InputArray(const Scalar& s); _InputArray(const Scalar& s);
@@ -1360,6 +1361,7 @@ public:
template<typename _Tp> _OutputArray(vector<_Tp>& vec); template<typename _Tp> _OutputArray(vector<_Tp>& vec);
template<typename _Tp> _OutputArray(vector<vector<_Tp> >& vec); template<typename _Tp> _OutputArray(vector<vector<_Tp> >& vec);
_OutputArray(vector<Mat>& vec); _OutputArray(vector<Mat>& vec);
template<typename _Tp> _OutputArray(vector<Mat_<_Tp> >& vec);
template<typename _Tp> _OutputArray(Mat_<_Tp>& m); template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx); template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
template<typename _Tp> _OutputArray(_Tp* vec, int n); template<typename _Tp> _OutputArray(_Tp* vec, int n);
@@ -1368,6 +1370,7 @@ public:
template<typename _Tp> _OutputArray(const vector<_Tp>& vec); template<typename _Tp> _OutputArray(const vector<_Tp>& vec);
template<typename _Tp> _OutputArray(const vector<vector<_Tp> >& vec); template<typename _Tp> _OutputArray(const vector<vector<_Tp> >& vec);
_OutputArray(const vector<Mat>& vec); _OutputArray(const vector<Mat>& vec);
template<typename _Tp> _OutputArray(const vector<Mat_<_Tp> >& vec);
template<typename _Tp> _OutputArray(const Mat_<_Tp>& m); template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx); template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
template<typename _Tp> _OutputArray(const _Tp* vec, int n); template<typename _Tp> _OutputArray(const _Tp* vec, int n);
@@ -1631,22 +1634,22 @@ public:
Mat(); Mat();
//! constructs 2D matrix of the specified size and type //! constructs 2D matrix of the specified size and type
// (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
Mat(int _rows, int _cols, int _type); Mat(int rows, int cols, int type);
Mat(Size _size, int _type); Mat(Size size, int type);
//! constucts 2D matrix and fills it with the specified value _s. //! constucts 2D matrix and fills it with the specified value _s.
Mat(int _rows, int _cols, int _type, const Scalar& _s); Mat(int rows, int cols, int type, const Scalar& s);
Mat(Size _size, int _type, const Scalar& _s); Mat(Size size, int type, const Scalar& s);
//! constructs n-dimensional matrix //! constructs n-dimensional matrix
Mat(int _ndims, const int* _sizes, int _type); Mat(int ndims, const int* sizes, int type);
Mat(int _ndims, const int* _sizes, int _type, const Scalar& _s); Mat(int ndims, const int* sizes, int type, const Scalar& s);
//! copy constructor //! copy constructor
Mat(const Mat& m); Mat(const Mat& m);
//! constructor for matrix headers pointing to user-allocated data //! constructor for matrix headers pointing to user-allocated data
Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP); Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP); Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
Mat(int _ndims, const int* _sizes, int _type, void* _data, const size_t* _steps=0); Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
//! creates a matrix header for a part of the bigger matrix //! creates a matrix header for a part of the bigger matrix
Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
@@ -1661,11 +1664,9 @@ public:
//! builds matrix from std::vector with or without copying the data //! builds matrix from std::vector with or without copying the data
template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false); template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false);
//! builds matrix from cv::Vec; the data is copied by default //! builds matrix from cv::Vec; the data is copied by default
template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
bool copyData=true);
//! builds matrix from cv::Matx; the data is copied by default //! builds matrix from cv::Matx; the data is copied by default
template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
bool copyData=true);
//! builds matrix from a 2D point //! builds matrix from a 2D point
template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true); template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
//! builds matrix from a 3D point //! builds matrix from a 3D point
@@ -1718,8 +1719,8 @@ public:
Mat& setTo(InputArray value, InputArray mask=noArray()); Mat& setTo(InputArray value, InputArray mask=noArray());
//! creates alternative matrix header for the same data, with different //! creates alternative matrix header for the same data, with different
// number of channels and/or different number of rows. see cvReshape. // number of channels and/or different number of rows. see cvReshape.
Mat reshape(int _cn, int _rows=0) const; Mat reshape(int cn, int rows=0) const;
Mat reshape(int _cn, int _newndims, const int* _newsz) const; Mat reshape(int cn, int newndims, const int* newsz) const;
//! matrix transposition by means of matrix expressions //! matrix transposition by means of matrix expressions
MatExpr t() const; MatExpr t() const;
@@ -1745,9 +1746,9 @@ public:
//! allocates new matrix data unless the matrix already has specified size and type. //! allocates new matrix data unless the matrix already has specified size and type.
// previous data is unreferenced if needed. // previous data is unreferenced if needed.
void create(int _rows, int _cols, int _type); void create(int rows, int cols, int type);
void create(Size _size, int _type); void create(Size size, int type);
void create(int _ndims, const int* _sizes, int _type); void create(int ndims, const int* sizes, int type);
//! increases the reference counter; use with care to avoid memleaks //! increases the reference counter; use with care to avoid memleaks
void addref(); void addref();
@@ -1963,7 +1964,7 @@ public:
enum { UNIFORM=0, NORMAL=1 }; enum { UNIFORM=0, NORMAL=1 };
RNG(); RNG();
RNG(uint64 _state); RNG(uint64 state);
//! updates the state and returns the next 32-bit unsigned integer random number //! updates the state and returns the next 32-bit unsigned integer random number
unsigned next(); unsigned next();
@@ -1973,7 +1974,7 @@ public:
operator short(); operator short();
operator unsigned(); operator unsigned();
//! returns a random integer sampled uniformly from [0, N). //! returns a random integer sampled uniformly from [0, N).
unsigned operator()(unsigned N); unsigned operator ()(unsigned N);
unsigned operator ()(); unsigned operator ()();
operator int(); operator int();
operator float(); operator float();
@@ -2247,10 +2248,10 @@ CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
enum enum
{ {
SORT_EVERY_ROW=0, SORT_EVERY_ROW=0,
SORT_EVERY_COLUMN=1, SORT_EVERY_COLUMN=1,
SORT_ASCENDING=0, SORT_ASCENDING=0,
SORT_DESCENDING=16 SORT_DESCENDING=16
}; };
//! sorts independently each matrix row or each matrix column //! sorts independently each matrix row or each matrix column
@@ -2273,12 +2274,12 @@ CV_EXPORTS_W bool eigen(InputArray src, bool computeEigenvectors,
enum enum
{ {
COVAR_SCRAMBLED=0, COVAR_SCRAMBLED=0,
COVAR_NORMAL=1, COVAR_NORMAL=1,
COVAR_USE_AVG=2, COVAR_USE_AVG=2,
COVAR_SCALE=4, COVAR_SCALE=4,
COVAR_ROWS=8, COVAR_ROWS=8,
COVAR_COLS=16 COVAR_COLS=16
}; };
//! computes covariation matrix of a set of samples //! computes covariation matrix of a set of samples
@@ -3940,7 +3941,12 @@ public:
{ {
READ=0, //! read mode READ=0, //! read mode
WRITE=1, //! write mode WRITE=1, //! write mode
APPEND=2 //! append mode APPEND=2, //! append mode
MEMORY=4,
FORMAT_MASK=(7<<3),
FORMAT_AUTO=0,
FORMAT_XML=(1<<3),
FORMAT_YAML=(2<<3)
}; };
enum enum
{ {
@@ -3952,7 +3958,7 @@ public:
//! the default constructor //! the default constructor
CV_WRAP FileStorage(); CV_WRAP FileStorage();
//! the full constructor that opens file storage for reading or writing //! the full constructor that opens file storage for reading or writing
CV_WRAP FileStorage(const string& filename, int flags, const string& encoding=string()); CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
//! the constructor that takes pointer to the C FileStorage structure //! the constructor that takes pointer to the C FileStorage structure
FileStorage(CvFileStorage* fs); FileStorage(CvFileStorage* fs);
//! the destructor. calls release() //! the destructor. calls release()
@@ -3964,6 +3970,8 @@ public:
CV_WRAP virtual bool isOpened() const; CV_WRAP virtual bool isOpened() const;
//! closes the file and releases all the memory buffers //! closes the file and releases all the memory buffers
CV_WRAP virtual void release(); CV_WRAP virtual void release();
//! closes the file, releases all the memory buffers and returns the text string
CV_WRAP string releaseAndGetString();
//! returns the first element of the top-level mapping //! returns the first element of the top-level mapping
CV_WRAP FileNode getFirstTopLevelNode() const; CV_WRAP FileNode getFirstTopLevelNode() const;
@@ -4118,9 +4126,9 @@ public:
//! moves iterator to the previous node //! moves iterator to the previous node
FileNodeIterator operator -- (int); FileNodeIterator operator -- (int);
//! moves iterator forward by the specified offset (possibly negative) //! moves iterator forward by the specified offset (possibly negative)
FileNodeIterator& operator += (int); FileNodeIterator& operator += (int ofs);
//! moves iterator backward by the specified offset (possibly negative) //! moves iterator backward by the specified offset (possibly negative)
FileNodeIterator& operator -= (int); FileNodeIterator& operator -= (int ofs);
//! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format
FileNodeIterator& readRaw( const string& fmt, uchar* vec, FileNodeIterator& readRaw( const string& fmt, uchar* vec,
@@ -233,6 +233,34 @@ CV_INLINE IppiSize ippiSize(int width, int height)
} }
#endif #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 #endif
/* maximal size of vector to run matrix operations on it inline (i.e. w/o ipp calls) */ /* maximal size of vector to run matrix operations on it inline (i.e. w/o ipp calls) */
+31 -11
View File
@@ -322,7 +322,10 @@ inline Mat Mat::diag(const Mat& d)
CV_Assert( d.cols == 1 || d.rows == 1 ); CV_Assert( d.cols == 1 || d.rows == 1 );
int len = d.rows + d.cols - 1; int len = d.rows + d.cols - 1;
Mat m(len, len, d.type(), Scalar(0)), md = m.diag(); 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; 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) template<typename _Tp> inline _InputArray::_InputArray(const vector<vector<_Tp> >& vec)
: flags(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&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) 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) {} : 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) template<typename _Tp> inline _InputArray::_InputArray(const Mat_<_Tp>& m)
: flags(FIXED_TYPE + MAT + DataType<_Tp>::type), obj((void*)&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<_Tp>& vec)
template<typename _Tp> inline _OutputArray::_OutputArray(vector<vector<_Tp> >& vec) : _InputArray(vec) {} : _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(Mat_<_Tp>& m) : _InputArray(m) {} template<typename _Tp> inline _OutputArray::_OutputArray(vector<vector<_Tp> >& vec)
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) : _InputArray(mtx) {} : _InputArray(vec) {}
template<typename _Tp> inline _OutputArray::_OutputArray(_Tp* vec, int n) : _InputArray(vec, n) {} 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 vector<Mat_<_Tp> >& vec)
: _InputArray(vec) {flags |= FIXED_SIZE;}
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<_Tp>& vec) : _InputArray(vec) {flags |= FIXED_SIZE;} template<typename _Tp> inline _OutputArray::_OutputArray(const Mat_<_Tp>& m)
template<typename _Tp> inline _OutputArray::_OutputArray(const vector<vector<_Tp> >& vec) : _InputArray(vec) {flags |= FIXED_SIZE;} : _InputArray(m) {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)
template<typename _Tp, int m, int n> inline _OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) : _InputArray(mtx) {} : _InputArray(mtx) {}
template<typename _Tp> inline _OutputArray::_OutputArray(const _Tp* vec, int n) : _InputArray(vec, n) {} template<typename _Tp> inline _OutputArray::_OutputArray(const _Tp* vec, int n)
: _InputArray(vec, n) {}
//////////////////////////////////// Matrix Expressions ///////////////////////////////////////// //////////////////////////////////// Matrix Expressions /////////////////////////////////////////
+6 -1
View File
@@ -1130,7 +1130,7 @@ CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z )
/******************************** CvSize's & CvBox **************************************/ /******************************** CvSize's & CvBox **************************************/
typedef struct typedef struct CvSize
{ {
int width; int width;
int height; int height;
@@ -1740,6 +1740,11 @@ typedef struct CvFileStorage CvFileStorage;
#define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE #define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE
#define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE #define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE
#define CV_STORAGE_APPEND 2 #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: */ /* List of attributes: */
typedef struct CvAttrList typedef struct CvAttrList
@@ -49,7 +49,7 @@
#define CV_MAJOR_VERSION 2 #define CV_MAJOR_VERSION 2
#define CV_MINOR_VERSION 4 #define CV_MINOR_VERSION 4
#define CV_SUBMINOR_VERSION 0 #define CV_SUBMINOR_VERSION 1
#define CVAUX_STR_EXP(__A) #__A #define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__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); 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[] = static BinaryFunc addWeightedTab[] =
{ {
(BinaryFunc)addWeighted8u, (BinaryFunc)addWeighted8s, (BinaryFunc)addWeighted16u, (BinaryFunc)GET_OPTIMIZED(addWeighted8u), (BinaryFunc)GET_OPTIMIZED(addWeighted8s), (BinaryFunc)GET_OPTIMIZED(addWeighted16u),
(BinaryFunc)addWeighted16s, (BinaryFunc)addWeighted32s, (BinaryFunc)addWeighted32f, (BinaryFunc)GET_OPTIMIZED(addWeighted16s), (BinaryFunc)GET_OPTIMIZED(addWeighted32s), (BinaryFunc)addWeighted32f,
(BinaryFunc)addWeighted64f, 0 (BinaryFunc)addWeighted64f, 0
}; };
@@ -2504,8 +2504,8 @@ typedef void (*InRangeFunc)( const uchar* src1, size_t step1, const uchar* src2,
static InRangeFunc inRangeTab[] = static InRangeFunc inRangeTab[] =
{ {
(InRangeFunc)inRange8u, (InRangeFunc)inRange8s, (InRangeFunc)inRange16u, (InRangeFunc)GET_OPTIMIZED(inRange8u), (InRangeFunc)GET_OPTIMIZED(inRange8s), (InRangeFunc)GET_OPTIMIZED(inRange16u),
(InRangeFunc)inRange16s, (InRangeFunc)inRange32s, (InRangeFunc)inRange32f, (InRangeFunc)GET_OPTIMIZED(inRange16s), (InRangeFunc)GET_OPTIMIZED(inRange32s), (InRangeFunc)GET_OPTIMIZED(inRange32f),
(InRangeFunc)inRange64f, 0 (InRangeFunc)inRange64f, 0
}; };
+50 -50
View File
@@ -619,28 +619,28 @@ cvtScale_<short, short, float>( const short* src, size_t sstep,
sstep /= sizeof(src[0]); sstep /= sizeof(src[0]);
dstep /= sizeof(dst[0]); dstep /= sizeof(dst[0]);
for( ; size.height--; src += sstep, dst += dstep ) for( ; size.height--; src += sstep, dst += dstep )
{ {
int x = 0; int x = 0;
#if CV_SSE2 #if CV_SSE2
if(USE_SSE2) if(USE_SSE2)
{ {
__m128 scale128 = _mm_set1_ps (scale); __m128 scale128 = _mm_set1_ps (scale);
__m128 shift128 = _mm_set1_ps (shift); __m128 shift128 = _mm_set1_ps (shift);
for(; x <= size.width - 8; x += 8 ) for(; x <= size.width - 8; x += 8 )
{ {
__m128i r0 = _mm_loadl_epi64((const __m128i*)(src + x)); __m128i r0 = _mm_loadl_epi64((const __m128i*)(src + x));
__m128i r1 = _mm_loadl_epi64((const __m128i*)(src + x + 4)); __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)); __m128 rf1 =_mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(r1, r1), 16));
rf0 = _mm_add_ps(_mm_mul_ps(rf0, scale128), shift128); rf0 = _mm_add_ps(_mm_mul_ps(rf0, scale128), shift128);
rf1 = _mm_add_ps(_mm_mul_ps(rf1, scale128), shift128); rf1 = _mm_add_ps(_mm_mul_ps(rf1, scale128), shift128);
r0 = _mm_cvtps_epi32(rf0); r0 = _mm_cvtps_epi32(rf0);
r1 = _mm_cvtps_epi32(rf1); r1 = _mm_cvtps_epi32(rf1);
r0 = _mm_packs_epi32(r0, r1); r0 = _mm_packs_epi32(r0, r1);
_mm_storeu_si128((__m128i*)(dst + x), r0); _mm_storeu_si128((__m128i*)(dst + x), r0);
} }
} }
#endif #endif
for(; x < size.width; x++ ) for(; x < size.width; x++ )
@@ -659,17 +659,17 @@ cvt_( const T* src, size_t sstep,
for( ; size.height--; src += sstep, dst += dstep ) for( ; size.height--; src += sstep, dst += dstep )
{ {
int x = 0; int x = 0;
#if CV_ENABLE_UNROLLED #if CV_ENABLE_UNROLLED
for( ; x <= size.width - 4; x += 4 ) for( ; x <= size.width - 4; x += 4 )
{ {
DT t0, t1; DT t0, t1;
t0 = saturate_cast<DT>(src[x]); t0 = saturate_cast<DT>(src[x]);
t1 = saturate_cast<DT>(src[x+1]); t1 = saturate_cast<DT>(src[x+1]);
dst[x] = t0; dst[x+1] = t1; dst[x] = t0; dst[x+1] = t1;
t0 = saturate_cast<DT>(src[x+2]); t0 = saturate_cast<DT>(src[x+2]);
t1 = saturate_cast<DT>(src[x+3]); t1 = saturate_cast<DT>(src[x+3]);
dst[x+2] = t0; dst[x+3] = t1; dst[x+2] = t0; dst[x+3] = t1;
} }
#endif #endif
for( ; x < size.width; x++ ) for( ; x < size.width; x++ )
dst[x] = saturate_cast<DT>(src[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 ) for( ; size.height--; src += sstep, dst += dstep )
{ {
int x = 0; int x = 0;
#if CV_SSE2 #if CV_SSE2
if(USE_SSE2){ if(USE_SSE2){
for( ; x <= size.width - 8; x += 8 ) for( ; x <= size.width - 8; x += 8 )
{ {
__m128 src128 = _mm_loadu_ps (src + x); __m128 src128 = _mm_loadu_ps (src + x);
__m128i src_int128 = _mm_cvtps_epi32 (src128); __m128i src_int128 = _mm_cvtps_epi32 (src128);
src128 = _mm_loadu_ps (src + x + 4); src128 = _mm_loadu_ps (src + x + 4);
__m128i src1_int128 = _mm_cvtps_epi32 (src128); __m128i src1_int128 = _mm_cvtps_epi32 (src128);
src1_int128 = _mm_packs_epi32(src_int128, src1_int128); src1_int128 = _mm_packs_epi32(src_int128, src1_int128);
_mm_storeu_si128((__m128i*)(dst + x),src1_int128); _mm_storeu_si128((__m128i*)(dst + x),src1_int128);
} }
} }
#endif #endif
for( ; x < size.width; x++ ) for( ; x < size.width; x++ )
dst[x] = saturate_cast<short>(src[x]); dst[x] = saturate_cast<short>(src[x]);
@@ -876,33 +876,33 @@ static BinaryFunc cvtScaleAbsTab[] =
static BinaryFunc cvtScaleTab[][8] = static BinaryFunc cvtScaleTab[][8] =
{ {
{ {
(BinaryFunc)cvtScale8u, (BinaryFunc)cvtScale8s8u, (BinaryFunc)cvtScale16u8u, (BinaryFunc)GET_OPTIMIZED(cvtScale8u), (BinaryFunc)GET_OPTIMIZED(cvtScale8s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale16u8u),
(BinaryFunc)cvtScale16s8u, (BinaryFunc)cvtScale32s8u, (BinaryFunc)cvtScale32f8u, (BinaryFunc)GET_OPTIMIZED(cvtScale16s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale32s8u), (BinaryFunc)GET_OPTIMIZED(cvtScale32f8u),
(BinaryFunc)cvtScale64f8u, 0 (BinaryFunc)cvtScale64f8u, 0
}, },
{ {
(BinaryFunc)cvtScale8u8s, (BinaryFunc)cvtScale8s, (BinaryFunc)cvtScale16u8s, (BinaryFunc)GET_OPTIMIZED(cvtScale8u8s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u8s),
(BinaryFunc)cvtScale16s8s, (BinaryFunc)cvtScale32s8s, (BinaryFunc)cvtScale32f8s, (BinaryFunc)GET_OPTIMIZED(cvtScale16s8s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s8s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f8s),
(BinaryFunc)cvtScale64f8s, 0 (BinaryFunc)cvtScale64f8s, 0
}, },
{ {
(BinaryFunc)cvtScale8u16u, (BinaryFunc)cvtScale8s16u, (BinaryFunc)cvtScale16u, (BinaryFunc)GET_OPTIMIZED(cvtScale8u16u), (BinaryFunc)GET_OPTIMIZED(cvtScale8s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale16u),
(BinaryFunc)cvtScale16s16u, (BinaryFunc)cvtScale32s16u, (BinaryFunc)cvtScale32f16u, (BinaryFunc)GET_OPTIMIZED(cvtScale16s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale32s16u), (BinaryFunc)GET_OPTIMIZED(cvtScale32f16u),
(BinaryFunc)cvtScale64f16u, 0 (BinaryFunc)cvtScale64f16u, 0
}, },
{ {
(BinaryFunc)cvtScale8u16s, (BinaryFunc)cvtScale8s16s, (BinaryFunc)cvtScale16u16s, (BinaryFunc)GET_OPTIMIZED(cvtScale8u16s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s16s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u16s),
(BinaryFunc)cvtScale16s, (BinaryFunc)cvtScale32s16s, (BinaryFunc)cvtScale32f16s, (BinaryFunc)GET_OPTIMIZED(cvtScale16s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s16s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f16s),
(BinaryFunc)cvtScale64f16s, 0 (BinaryFunc)cvtScale64f16s, 0
}, },
{ {
(BinaryFunc)cvtScale8u32s, (BinaryFunc)cvtScale8s32s, (BinaryFunc)cvtScale16u32s, (BinaryFunc)GET_OPTIMIZED(cvtScale8u32s), (BinaryFunc)GET_OPTIMIZED(cvtScale8s32s), (BinaryFunc)GET_OPTIMIZED(cvtScale16u32s),
(BinaryFunc)cvtScale16s32s, (BinaryFunc)cvtScale32s, (BinaryFunc)cvtScale32f32s, (BinaryFunc)GET_OPTIMIZED(cvtScale16s32s), (BinaryFunc)GET_OPTIMIZED(cvtScale32s), (BinaryFunc)GET_OPTIMIZED(cvtScale32f32s),
(BinaryFunc)cvtScale64f32s, 0 (BinaryFunc)cvtScale64f32s, 0
}, },
{ {
(BinaryFunc)cvtScale8u32f, (BinaryFunc)cvtScale8s32f, (BinaryFunc)cvtScale16u32f, (BinaryFunc)GET_OPTIMIZED(cvtScale8u32f), (BinaryFunc)GET_OPTIMIZED(cvtScale8s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale16u32f),
(BinaryFunc)cvtScale16s32f, (BinaryFunc)cvtScale32s32f, (BinaryFunc)cvtScale32f, (BinaryFunc)GET_OPTIMIZED(cvtScale16s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale32s32f), (BinaryFunc)GET_OPTIMIZED(cvtScale32f),
(BinaryFunc)cvtScale64f32f, 0 (BinaryFunc)cvtScale64f32f, 0
}, },
{ {
@@ -918,7 +918,7 @@ static BinaryFunc cvtScaleTab[][8] =
static BinaryFunc cvtTab[][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(cvt16s8u), (BinaryFunc)GET_OPTIMIZED(cvt32s8u), (BinaryFunc)GET_OPTIMIZED(cvt32f8u),
(BinaryFunc)GET_OPTIMIZED(cvt64f8u), 0 (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(cvt8u64f), (BinaryFunc)GET_OPTIMIZED(cvt8s64f), (BinaryFunc)GET_OPTIMIZED(cvt16u64f),
(BinaryFunc)GET_OPTIMIZED(cvt16s64f), (BinaryFunc)GET_OPTIMIZED(cvt32s64f), (BinaryFunc)GET_OPTIMIZED(cvt32f64f), (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 0, 0, 0, 0, 0, 0, 0, 0
+15 -2
View File
@@ -320,7 +320,8 @@ namespace
template <class T> void getCudaAttribute(T *attribute, CUdevice_attribute device_attribute, int device) template <class T> void getCudaAttribute(T *attribute, CUdevice_attribute device_attribute, int device)
{ {
*attribute = T(); *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 ) if( CUDA_SUCCESS == error )
return; return;
@@ -336,7 +337,7 @@ namespace
int Cores; int Cores;
} SMtoCores; } 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; int index = 0;
while (gpuArchCoresPerSM[index].SM != -1) 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 // CudaFuncTable
@@ -1164,6 +1170,13 @@ namespace
CV_Error(CV_StsUnsupportedFormat, "The device doesn't support double"); 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]; const func_t func = funcs[src.depth()][dst.depth()][src.channels() - 1];
CV_DbgAssert(func != 0); CV_DbgAssert(func != 0);
+4 -1
View File
@@ -947,6 +947,9 @@ double cv::invert( InputArray _src, OutputArray _dst, int method )
bool result = false; bool result = false;
Mat src = _src.getMat(); Mat src = _src.getMat();
int type = src.type(); int type = src.type();
CV_Assert(type == CV_32F || type == CV_64F);
size_t esz = CV_ELEM_SIZE(type); size_t esz = CV_ELEM_SIZE(type);
int m = src.rows, n = src.cols; 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); ((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 ) 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[] = static DotProdFunc dotProdTab[] =
{ {
(DotProdFunc)GET_OPTIMIZED(dotProd_8u), (DotProdFunc)dotProd_8s, (DotProdFunc)dotProd_16u, (DotProdFunc)GET_OPTIMIZED(dotProd_8u), (DotProdFunc)GET_OPTIMIZED(dotProd_8s),
(DotProdFunc)dotProd_16s, (DotProdFunc)dotProd_32s, (DotProdFunc)GET_OPTIMIZED(dotProd_32f), (DotProdFunc)dotProd_16u, (DotProdFunc)dotProd_16s,
(DotProdFunc)dotProd_32s, (DotProdFunc)GET_OPTIMIZED(dotProd_32f),
(DotProdFunc)dotProd_64f, 0 (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 ) if(CV_MAT_CN(type) == m.channels() && ((1 << CV_MAT_TYPE(flags)) & fixedDepthMask) != 0 )
type = m.type(); type = m.type();
else 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()) if(fixedSize())
{ {
@@ -1470,10 +1470,21 @@ void _OutputArray::create(int dims, const int* size, int type, int i, bool allow
if( i < 0 ) if( i < 0 )
{ {
CV_Assert( dims == 2 && (size[0] == 1 || size[1] == 1 || size[0]*size[1] == 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); 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; return;
} }
@@ -2886,8 +2897,16 @@ cvKMeans2( const CvArr* _samples, int cluster_count, CvArr* _labels,
namespace cv 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, ""); CV_Error(CV_StsNotImplemented, "");
// TBD // TBD
return Mat(); return Mat();
+1 -1
View File
@@ -1269,7 +1269,7 @@ void cv::GlFont::draw(const char* str, int len) const
glPushAttrib(GL_LIST_BIT); glPushAttrib(GL_LIST_BIT);
glListBase(base_); glListBase(base_);
glCallLists(len, GL_UNSIGNED_BYTE, str); glCallLists(static_cast<GLsizei>(len), GL_UNSIGNED_BYTE, str);
glPopAttrib(); glPopAttrib();
+194 -86
View File
@@ -41,7 +41,10 @@
//M*/ //M*/
#include "precomp.hpp" #include "precomp.hpp"
#include <ctype.h> #include <ctype.h>
#include <deque>
#include <iterator>
#include <wchar.h> #include <wchar.h>
#include <zlib.h> #include <zlib.h>
@@ -208,7 +211,7 @@ typedef void (*CvStartNextStream)( struct CvFileStorage* fs );
typedef struct CvFileStorage typedef struct CvFileStorage
{ {
int flags; int flags;
int is_xml; int fmt;
int write_mode; int write_mode;
int is_first; int is_first;
CvMemStorage* memstorage; CvMemStorage* memstorage;
@@ -240,52 +243,86 @@ typedef struct CvFileStorage
CvWriteString write_string; CvWriteString write_string;
CvWriteComment write_comment; CvWriteComment write_comment;
CvStartNextStream start_next_stream; CvStartNextStream start_next_stream;
//CvParse parse;
const char* strbuf;
size_t strbufsize, strbufpos;
std::deque<char>* outbuf;
bool is_opened;
} }
CvFileStorage; CvFileStorage;
static void icvPuts( CvFileStorage* fs, const char* str ) static void icvPuts( CvFileStorage* fs, const char* str )
{ {
CV_Assert( fs->file || fs->gzfile ); if( fs->outbuf )
if( fs->file ) std::copy(str, str + strlen(str), std::back_inserter(*fs->outbuf));
else if( fs->file )
fputs( str, fs->file ); fputs( str, fs->file );
else else if( fs->gzfile )
gzputs( fs->gzfile, str ); gzputs( fs->gzfile, str );
else
CV_Error( CV_StsError, "The storage is not opened" );
} }
static char* icvGets( CvFileStorage* fs, char* str, int maxCount ) 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 ) if( fs->file )
return fgets( str, maxCount, 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 ) static int icvEof( CvFileStorage* fs )
{ {
CV_Assert( fs->file || fs->gzfile ); if( fs->strbuf )
return fs->strbufpos >= fs->strbufsize;
if( fs->file ) if( fs->file )
return feof(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 ) if( fs->file )
fclose( fs->file ); fclose( fs->file );
if( fs->gzfile ) else if( fs->gzfile )
gzclose( fs->gzfile ); gzclose( fs->gzfile );
fs->file = 0; fs->file = 0;
fs->gzfile = 0; fs->gzfile = 0;
fs->strbuf = 0;
fs->strbufpos = 0;
fs->is_opened = false;
} }
static void icvRewind( CvFileStorage* fs ) static void icvRewind( CvFileStorage* fs )
{ {
CV_Assert( fs->file || fs->gzfile );
if( fs->file ) if( fs->file )
rewind(fs->file); rewind(fs->file);
else else if( fs->gzfile )
gzrewind(fs->gzfile); gzrewind(fs->gzfile);
fs->strbufpos = 0;
} }
#define CV_YML_INDENT 3 #define CV_YML_INDENT 3
@@ -373,7 +410,7 @@ icvFSCreateCollection( CvFileStorage* fs, int tag, CvFileNode* collection )
{ {
if( collection->tag != CV_NODE_NONE ) 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 <_></_>)" ); CV_PARSE_ERROR( "Sequence element should not have name (use <_></_>)" );
} }
@@ -477,6 +514,40 @@ icvFSFlush( CvFileStorage* fs )
} }
static void
icvClose( CvFileStorage* fs, std::string* out )
{
if( out )
out->clear();
if( !fs )
CV_Error( CV_StsNullPtr, "NULL double pointer to file storage" );
if( fs->is_opened )
{
if( fs->write_mode && (fs->file || fs->gzfile || fs->outbuf) )
{
if( fs->write_stack )
{
while( fs->write_stack->total > 0 )
cvEndWriteStruct(fs);
}
icvFSFlush(fs);
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());
}
}
/* closes file storage and deallocates buffers */ /* closes file storage and deallocates buffers */
CV_IMPL void CV_IMPL void
cvReleaseFileStorage( CvFileStorage** p_fs ) cvReleaseFileStorage( CvFileStorage** p_fs )
@@ -489,27 +560,15 @@ cvReleaseFileStorage( CvFileStorage** p_fs )
CvFileStorage* fs = *p_fs; CvFileStorage* fs = *p_fs;
*p_fs = 0; *p_fs = 0;
if( fs->write_mode && (fs->file || fs->gzfile) ) icvClose(fs, 0);
{
if( fs->write_stack )
{
while( fs->write_stack->total > 0 )
cvEndWriteStruct(fs);
}
icvFSFlush(fs);
if( fs->is_xml )
icvPuts( fs, "</opencv_storage>\n" );
}
//icvFSReleaseCollection( fs->roots ); // delete all the user types recursively
icvClose(fs);
cvReleaseMemStorage( &fs->strstorage ); cvReleaseMemStorage( &fs->strstorage );
cvFree( &fs->buffer_start ); cvFree( &fs->buffer_start );
cvReleaseMemStorage( &fs->memstorage ); cvReleaseMemStorage( &fs->memstorage );
if( fs->outbuf )
delete fs->outbuf;
memset( fs, 0, sizeof(*fs) ); memset( fs, 0, sizeof(*fs) );
cvFree( &fs ); cvFree( &fs );
} }
@@ -2601,10 +2660,22 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
char* xml_buf = 0; char* xml_buf = 0;
int default_block_size = 1 << 18; int default_block_size = 1 << 18;
bool append = (flags & 3) == CV_STORAGE_APPEND; bool append = (flags & 3) == CV_STORAGE_APPEND;
bool mem = (flags & CV_STORAGE_MEMORY) != 0;
bool write_mode = (flags & 3) != 0;
bool isGZ = false; bool isGZ = false;
size_t fnamelen = 0;
if( !filename ) if( !filename || filename[0] == '\0' )
CV_Error( CV_StsNullPtr, "NULL filename" ); {
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) ); fs = (CvFileStorage*)cvAlloc( sizeof(*fs) );
memset( fs, 0, sizeof(*fs)); memset( fs, 0, sizeof(*fs));
@@ -2612,42 +2683,41 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
fs->memstorage = cvCreateMemStorage( default_block_size ); fs->memstorage = cvCreateMemStorage( default_block_size );
fs->dststorage = dststorage ? dststorage : fs->memstorage; 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->flags = CV_FILE_STORAGE;
fs->write_mode = (flags & 3) != 0; fs->write_mode = write_mode;
if( !isGZ ) if( !mem )
{ {
fs->file = fopen(fs->filename, !fs->write_mode ? "rt" : !append ? "wt" : "a+t" ); fs->filename = (char*)cvMemStorageAlloc( fs->memstorage, fnamelen+1 );
if( !fs->file ) strcpy( fs->filename, filename );
goto _exit_;
} char* dot_pos = strrchr(fs->filename, '.');
else char compression = '\0';
{
char mode[] = { fs->write_mode ? 'w' : 'r', 'b', compression ? compression : '3', '\0' }; if( dot_pos && dot_pos[1] == 'g' && dot_pos[2] == 'z' &&
fs->gzfile = gzopen(fs->filename, mode); (dot_pos[3] == '\0' || (cv_isdigit(dot_pos[3]) && dot_pos[4] == '\0')) )
if( !fs->gzfile ) {
goto _exit_; 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->roots = 0;
@@ -2657,27 +2727,38 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
if( fs->write_mode ) 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;) // 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)) // 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; int buf_size = CV_FS_MAX_LEN*(fs->fmt == CV_STORAGE_FORMAT_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);
if( append ) if( append )
fseek( fs->file, 0, SEEK_END ); 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 ); sizeof(CvXMLStackRecord) : sizeof(int), fs->memstorage );
fs->is_first = 1; fs->is_first = 1;
fs->struct_indent = 0; fs->struct_indent = 0;
fs->struct_flags = CV_NODE_EMPTY; fs->struct_flags = CV_NODE_EMPTY;
fs->buffer_start = fs->buffer = (char*)cvAlloc( buf_size + 1024 ); fs->buffer_start = fs->buffer = (char*)cvAlloc( buf_size + 1024 );
fs->buffer_end = fs->buffer_start + buf_size; 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 ); fs->strstorage = cvCreateChildMemStorage( fs->memstorage );
if( !append || file_size == 0 ) if( !append || file_size == 0 )
{ {
@@ -2702,7 +2783,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
int xml_buf_size = 1 << 10; int xml_buf_size = 1 << 10;
char substr[] = "</opencv_storage>"; char substr[] = "</opencv_storage>";
int last_occurence = -1; 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 ); fseek( fs->file, -xml_buf_size, SEEK_END );
xml_buf = (char*)cvAlloc( xml_buf_size+2 ); xml_buf = (char*)cvAlloc( xml_buf_size+2 );
// find the last occurence of </opencv_storage> // find the last occurence of </opencv_storage>
@@ -2724,7 +2805,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
} }
if( last_occurence < 0 ) if( last_occurence < 0 )
CV_Error( CV_StsError, "Could not find </opencv_storage> in the end of file.\n" ); 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" ); fs->file = fopen( fs->filename, "r+t" );
fseek( fs->file, last_occurence, SEEK_SET ); fseek( fs->file, last_occurence, SEEK_SET );
// replace the last "</opencv_storage>" with " <!-- resumed -->", which has the same length // 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 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:"; const char* yaml_signature = "%YAML:";
char buf[16]; char buf[16];
icvGets( fs, buf, sizeof(buf)-2 ); 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 ) if( !isGZ )
{ {
fseek( fs->file, 0, SEEK_END ); if( !mem )
buf_size = ftell( fs->file ); {
buf_size = MIN( buf_size, (1 << 20) ); fseek( fs->file, 0, SEEK_END );
buf_size = MAX( buf_size, CV_FS_MAX_LEN*2 + 1024 ); 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); icvRewind(fs);
@@ -2785,7 +2878,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
//mode = cvGetErrMode(); //mode = cvGetErrMode();
//cvSetErrMode( CV_ErrModeSilent ); //cvSetErrMode( CV_ErrModeSilent );
if( fs->is_xml ) if( fs->fmt == CV_STORAGE_FORMAT_XML )
icvXMLParse( fs ); icvXMLParse( fs );
else else
icvYMLParse( fs ); icvYMLParse( fs );
@@ -2795,16 +2888,21 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
cvFree( &fs->buffer_start ); cvFree( &fs->buffer_start );
fs->buffer = fs->buffer_end = 0; fs->buffer = fs->buffer_end = 0;
} }
fs->is_opened = true;
_exit_: _exit_:
if( fs ) if( fs )
{ {
if( cvGetErrStatus() < 0 || (!fs->file && !fs->gzfile) ) if( cvGetErrStatus() < 0 || (!fs->file && !fs->gzfile && !fs->outbuf && !fs->strbuf) )
{ {
cvReleaseFileStorage( &fs ); cvReleaseFileStorage( &fs );
} }
else if( !fs->write_mode ) 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; return;
} }
if( fs->is_xml ) if( fs->fmt == CV_STORAGE_FORMAT_XML )
{ {
int buf_len = (int)strlen(ptr); int buf_len = (int)strlen(ptr);
icvXMLWriteScalar( fs, 0, ptr, buf_len ); 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 bool FileStorage::isOpened() const
{ {
return !fs.empty(); return !fs.empty() && fs.obj->is_opened;
} }
void FileStorage::release() void FileStorage::release()
@@ -5064,6 +5162,16 @@ void FileStorage::release()
state = UNDEFINED; 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 FileNode FileStorage::root(int streamidx) const
{ {
return isOpened() ? FileNode(fs, cvGetRootFileNode(fs, streamidx)) : FileNode(); 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] = static NormFunc normTab[3][8] =
{ {
{ {
(NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)normInf_8s, (NormFunc)normInf_16u, (NormFunc)normInf_16s, (NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)GET_OPTIMIZED(normInf_8s), (NormFunc)GET_OPTIMIZED(normInf_16u), (NormFunc)GET_OPTIMIZED(normInf_16s),
(NormFunc)normInf_32s, (NormFunc)GET_OPTIMIZED(normInf_32f), (NormFunc)normInf_64f, 0 (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)GET_OPTIMIZED(normL1_8u), (NormFunc)GET_OPTIMIZED(normL1_8s), (NormFunc)GET_OPTIMIZED(normL1_16u), (NormFunc)GET_OPTIMIZED(normL1_16s),
(NormFunc)normL1_32s, (NormFunc)GET_OPTIMIZED(normL1_32f), (NormFunc)normL1_64f, 0 (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)GET_OPTIMIZED(normL2_8u), (NormFunc)GET_OPTIMIZED(normL2_8s), (NormFunc)GET_OPTIMIZED(normL2_16u), (NormFunc)GET_OPTIMIZED(normL2_16s),
(NormFunc)normL2_32s, (NormFunc)GET_OPTIMIZED(normL2_32f), (NormFunc)normL2_64f, 0 (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); d.convertTo(d1, depth);
CV_Assert( norm(c, d1, CV_C) <= DBL_EPSILON ); 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(...) catch(...)
{ {
+8 -7
View File
@@ -91,7 +91,7 @@ protected:
{-1000000, 1000000}, {-10, 10}, {-10, 10}}; {-1000000, 1000000}, {-10, 10}, {-10, 10}};
RNG& rng = ts->get_rng(); RNG& rng = ts->get_rng();
RNG rng0; RNG rng0;
test_case_count = 2; test_case_count = 4;
int progress = 0; int progress = 0;
MemStorage storage(cvCreateMemStorage(0)); MemStorage storage(cvCreateMemStorage(0));
@@ -102,9 +102,10 @@ protected:
cvClearMemStorage(storage); cvClearMemStorage(storage);
bool mem = (idx % 4) >= 2;
string filename = tempfile(idx % 2 ? ".yml" : ".xml"); 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); int test_int = (int)cvtest::randInt(rng);
double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9); 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); fs.writeObj("test_graph",graph);
CvGraph* graph2 = (CvGraph*)cvClone(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 ); ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
return; return;
} }
@@ -310,7 +311,6 @@ protected:
int real_width = (int)tm["width"]; int real_width = (int)tm["width"];
int real_height = (int)tm["height"]; int real_height = (int)tm["height"];
int real_lbp_val = 0; int real_lbp_val = 0;
FileNodeIterator it; FileNodeIterator it;
it = tm_lbp.begin(); it = tm_lbp.begin();
@@ -370,7 +370,8 @@ protected:
} }
fs.release(); 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_create1(A.row(0)), cv::Exception );
EXPECT_THROW( OutputArray_create2(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 DescriptorExtractor
------------------- -------------------
.. ocv:class:: DescriptorExtractor .. ocv:class:: DescriptorExtractor : public Algorithm
Abstract base class for computing descriptors for image keypoints. :: 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. :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 DescriptorExtractor::create
------------------------------- -------------------------------
@@ -107,7 +88,7 @@ for example: ``"OpponentSIFT"`` .
OpponentColorDescriptorExtractor OpponentColorDescriptorExtractor
-------------------------------- --------------------------------
.. ocv:class:: OpponentColorDescriptorExtractor .. ocv:class:: OpponentColorDescriptorExtractor : public DescriptorExtractor
Class adapting a descriptor extractor to compute descriptors in the Opponent Color Space 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*). (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 BriefDescriptorExtractor
------------------------ ------------------------
.. ocv:class:: BriefDescriptorExtractor .. ocv:class:: BriefDescriptorExtractor : public DescriptorExtractor
Class for computing BRIEF descriptors described in a paper of Calonder M., Lepetit V., Class for computing BRIEF descriptors described in a paper of Calonder M., Lepetit V.,
Strecha C., Fua P. *BRIEF: Binary Robust Independent Elementary Features* , Strecha C., Fua P. *BRIEF: Binary Robust Independent Elementary Features* ,
@@ -11,7 +11,7 @@ descriptor matchers inherit the
DMatch DMatch
------ ------
.. ocv:class:: DMatch .. ocv:struct:: DMatch
Class for matching keypoint descriptors: query descriptor index, Class for matching keypoint descriptors: query descriptor index,
train descriptor index, train image index, and distance between descriptors. :: 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 DescriptorMatcher
----------------- -----------------
.. ocv:class:: DescriptorMatcher .. ocv:class:: DescriptorMatcher : public Algorithm
Abstract base class for matching keypoint descriptors. It has two groups Abstract base class for matching keypoint descriptors. It has two groups
of match methods: for matching descriptors of an image with another image or of match methods: for matching descriptors of an image with another image or
@@ -227,7 +227,7 @@ DescriptorMatcher::clone
---------------------------- ----------------------------
Clones the matcher. 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. :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.
@@ -258,25 +258,25 @@ Creates a descriptor matcher of a given type with the default parameters (using
BFMatcher 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 BFMatcher::BFMatcher
-------------------- --------------------
Brute-force matcher constructor. Brute-force matcher constructor.
.. ocv:function:: BFMatcher::BFMatcher( int distanceType, bool crossCheck=false ) .. ocv:function:: BFMatcher::BFMatcher( int normType, bool crossCheck=false )
: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 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 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. :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 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. :: 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 .. 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 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: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 :param x: x-coordinate of the keypoint
@@ -69,7 +69,7 @@ The keypoint constructors
FeatureDetector FeatureDetector
--------------- ---------------
.. ocv:class:: FeatureDetector .. ocv:class:: FeatureDetector : public Algorithm
Abstract base class for 2D image feature detectors. :: 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]``. :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 FeatureDetector::create
--------------------------- ---------------------------
Creates a feature detector by its name. Creates a feature detector by its name.
@@ -156,7 +140,7 @@ for example: ``"GridFAST"``, ``"PyramidSTAR"`` .
FastFeatureDetector FastFeatureDetector
------------------- -------------------
.. ocv:class:: FastFeatureDetector .. ocv:class:: FastFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the Wrapping class for feature detection using the
:ocv:func:`FAST` method. :: :ocv:func:`FAST` method. ::
@@ -173,7 +157,7 @@ Wrapping class for feature detection using the
GoodFeaturesToTrackDetector GoodFeaturesToTrackDetector
--------------------------- ---------------------------
.. ocv:class:: GoodFeaturesToTrackDetector .. ocv:class:: GoodFeaturesToTrackDetector : public FeatureDetector
Wrapping class for feature detection using the Wrapping class for feature detection using the
:ocv:func:`goodFeaturesToTrack` function. :: :ocv:func:`goodFeaturesToTrack` function. ::
@@ -211,7 +195,7 @@ Wrapping class for feature detection using the
MserFeatureDetector MserFeatureDetector
------------------- -------------------
.. ocv:class:: MserFeatureDetector .. ocv:class:: MserFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the Wrapping class for feature detection using the
:ocv:class:`MSER` class. :: :ocv:class:`MSER` class. ::
@@ -233,7 +217,7 @@ Wrapping class for feature detection using the
StarFeatureDetector StarFeatureDetector
------------------- -------------------
.. ocv:class:: StarFeatureDetector .. ocv:class:: StarFeatureDetector : public FeatureDetector
Wrapping class for feature detection using the Wrapping class for feature detection using the
:ocv:class:`StarDetector` class. :: :ocv:class:`StarDetector` class. ::
@@ -252,7 +236,7 @@ Wrapping class for feature detection using the
DenseFeatureDetector DenseFeatureDetector
-------------------- --------------------
.. ocv:class:: DenseFeatureDetector .. ocv:class:: DenseFeatureDetector : public FeatureDetector
Class for generation of image features which are distributed densely and regularly over the image. :: 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 SimpleBlobDetector
------------------- -------------------
.. ocv:class:: SimpleBlobDetector .. ocv:class:: SimpleBlobDetector : public FeatureDetector
Class for extracting blobs from an image. :: Class for extracting blobs from an image. ::
@@ -344,7 +328,7 @@ Default values of parameters are tuned to extract dark circular blobs.
GridAdaptedFeatureDetector 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. :: 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 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. :: 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 DynamicAdaptedFeatureDetector
----------------------------- -----------------------------
.. ocv:class:: DynamicAdaptedFeatureDetector .. ocv:class:: DynamicAdaptedFeatureDetector : public FeatureDetector
Adaptively adjusting detector that iteratively detects features until the desired number is found. :: Adaptively adjusting detector that iteratively detects features until the desired number is found. ::
@@ -431,7 +415,7 @@ DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector
---------------------------------------------------------------- ----------------------------------------------------------------
The constructor 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. :param adjuster: :ocv:class:`AdjusterAdapter` that detects features and adjusts parameters.
@@ -443,7 +427,7 @@ The constructor
AdjusterAdapter 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. :: 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 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. :: :ocv:class:`AdjusterAdapter` for :ocv:class:`FastFeatureDetector`. This class decreases or increases the threshold value by 1. ::
@@ -535,7 +519,7 @@ FastAdjuster
StarAdjuster StarAdjuster
------------ ------------
.. ocv:class:: StarAdjuster .. ocv:class:: StarAdjuster : public AdjusterAdapter
:ocv:class:`AdjusterAdapter` for :ocv:class:`StarFeatureDetector`. This class adjusts the ``responseThreshhold`` of ``StarFeatureDetector``. :: :ocv:class:`AdjusterAdapter` for :ocv:class:`StarFeatureDetector`. This class adjusts the ``responseThreshhold`` of ``StarFeatureDetector``. ::
@@ -130,7 +130,7 @@ GenericDescriptorMatcher::isMaskSupported
--------------------------------------------- ---------------------------------------------
Returns ``true`` if a generic descriptor matcher supports masking permissible matches. Returns ``true`` if a generic descriptor matcher supports masking permissible matches.
.. ocv:function:: void GenericDescriptorMatcher::isMaskSupported() .. ocv:function:: bool GenericDescriptorMatcher::isMaskSupported()
@@ -231,7 +231,7 @@ GenericDescriptorMatcher::clone
----------------------------------- -----------------------------------
Clones the matcher. 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 :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 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 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. :: 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. 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. :param img1: First source image.
@@ -65,13 +65,13 @@ drawKeypoints
----------------- -----------------
Draws keypoints. 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 image: Source image.
:param keypoints: Keypoints from the 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. :param color: Color of keypoints.
@@ -24,7 +24,7 @@ Detects corners using the FAST algorithm by [Rosten06]_.
MSER MSER
---- ----
.. ocv:class:: MSER .. ocv:class:: MSER : public FeatureDetector
Maximally stable extremal region extractor. :: Maximally stable extremal region extractor. ::
@@ -50,7 +50,7 @@ http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http:/
ORB 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). 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,8 +60,6 @@ ORB::ORB
-------- --------
The ORB constructor 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) .. 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 nfeatures: The maximum number of features to retain.
@@ -54,7 +54,7 @@ BOWTrainer::descripotorsCount
--------------------------------- ---------------------------------
Returns the count of all descriptors stored in the training set. 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 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. :ocv:func:`kmeans` -based class to train visual vocabulary using the *bag of visual words* approach.
:: ::
@@ -276,7 +276,7 @@ public:
enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 }; enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 };
explicit ORB(int nfeatures = 500, float scaleFactor = 1.2f, int nlevels = 8, int edgeThreshold = 31, 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 // returns the descriptor size in bytes
int descriptorSize() const; int descriptorSize() const;
@@ -324,13 +324,13 @@ class CV_EXPORTS_W MSER : public FeatureDetector
{ {
public: public:
//! the full constructor //! 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, double _max_variation=0.25, double _min_diversity=.2,
int _max_evolution=200, double _area_threshold=1.01, int _max_evolution=200, double _area_threshold=1.01,
double _min_margin=0.003, int _edge_blur_size=5 ); 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 //! 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, CV_WRAP_AS(detect) void operator()( const Mat& image, CV_OUT vector<vector<Point> >& msers,
const Mat& mask=Mat() ) const; const Mat& mask=Mat() ) const;
AlgorithmInfo* info() const; AlgorithmInfo* info() const;
@@ -508,13 +508,15 @@ public:
* gridRows Grid rows count. * gridRows Grid rows count.
* gridCols Grid column count. * gridCols Grid column count.
*/ */
CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector, CV_WRAP GridAdaptedFeatureDetector( const Ptr<FeatureDetector>& detector=0,
int maxTotalKeypoints=1000, int maxTotalKeypoints=1000,
int gridRows=4, int gridCols=4 ); int gridRows=4, int gridCols=4 );
// TODO implement read/write // TODO implement read/write
virtual bool empty() const; virtual bool empty() const;
AlgorithmInfo* info() const;
protected: protected:
virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const; virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
@@ -588,13 +590,13 @@ class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector
{ {
public: 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_features the maximum desired number of features
* \param max_iters the maximum number of times to try to adjust the feature detector params * \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 * for the FastAdjuster this can be high, but with Star or Surf this can get time consuming
* \param min_features the minimum desired features * \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; virtual bool empty() const;
@@ -1158,9 +1160,9 @@ public:
const vector<Mat>& masks=vector<Mat>(), bool compactResult=false ); const vector<Mat>& masks=vector<Mat>(), bool compactResult=false );
// Reads matcher object from a file node // 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 // 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) // Return true if matching object is empty (e.g. feature detector or descriptor matcher are empty)
virtual bool empty() const; virtual bool empty() const;
+74 -182
View File
@@ -52,211 +52,103 @@ namespace cv
Otherwise, linker may throw away some seemingly unused stuff. Otherwise, linker may throw away some seemingly unused stuff.
*/ */
static Algorithm* createBRIEF() { return new BriefDescriptorExtractor; } CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
static AlgorithmInfo& brief_info() obj.info()->addParam(obj, "bytes", obj.bytes_));
{
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; } CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
static AlgorithmInfo& fast_info() obj.info()->addParam(obj, "threshold", obj.threshold);
{ obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression));
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; } CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
static AlgorithmInfo& star_info() obj.info()->addParam(obj, "maxSize", obj.maxSize);
{ obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
static AlgorithmInfo star_info_var("Feature2D.STAR", createStarDetector); obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
return star_info_var; obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
} obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));
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; } CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
static AlgorithmInfo& mser_info() obj.info()->addParam(obj, "delta", obj.delta);
{ obj.info()->addParam(obj, "minArea", obj.minArea);
static AlgorithmInfo mser_info_var("Feature2D.MSER", createMSER); obj.info()->addParam(obj, "maxArea", obj.maxArea);
return mser_info_var; obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
} obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
static AlgorithmInfo& mser_info_auto = mser_info(); obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
obj.info()->addParam(obj, "minMargin", obj.minMargin);
AlgorithmInfo* MSER::info() const obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));
{
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();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
static Algorithm* createORB() { return new ORB; } CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
static AlgorithmInfo& orb_info() 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 AlgorithmInfo orb_info_var("Feature2D.ORB", createORB); public:
return orb_info_var; 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;
};
static AlgorithmInfo& orb_info_auto = orb_info(); 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));
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; CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
} obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
return &orb_info(); 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));
static Algorithm* createGFTT() { return new GFTTDetector; } CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
static Algorithm* createHarris() obj.info()->addParam(obj, "detector", (Ptr<Algorithm>&)obj.detector);
{ obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
GFTTDetector* d = new GFTTDetector; obj.info()->addParam(obj, "gridRows", obj.gridRows);
d->set("useHarris", true); obj.info()->addParam(obj, "gridCols", obj.gridCols));
return d;
}
static AlgorithmInfo gftt_info("Feature2D.GFTT", createGFTT);
static AlgorithmInfo harris_info("Feature2D.HARRIS", createHarris);
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);
AlgorithmInfo* DenseFeatureDetector::info() const
{
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;
}
bool initModule_features2d(void) bool initModule_features2d(void)
{ {
Ptr<Algorithm> brief = createBRIEF(), orb = createORB(), Ptr<Algorithm> brief = createBriefDescriptorExtractor(), orb = createORB(),
star = createStarDetector(), fastd = createFAST(), mser = createMSER(), star = createStarDetector(), fastd = createFastFeatureDetector(), mser = createMSER(),
dense = createDense(), gftt = createGFTT(), harris = createHarris(); dense = createDenseFeatureDetector(), gftt = createGFTTDetector(),
harris = createHarrisDetector(), grid = createGridAdaptedFeatureDetector();
return brief->info() != 0 && orb->info() != 0 && star->info() != 0 && return brief->info() != 0 && orb->info() != 0 && star->info() != 0 &&
fastd->info() != 0 && mser->info() != 0 && dense->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;
} }
} }
+15 -16
View File
@@ -778,35 +778,34 @@ void ORB::operator()( InputArray _image, InputArray _mask, vector<KeyPoint>& _ke
{ {
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()) if (!mask.empty())
resize(mask, maskPyramid[level], sz, scale, scale, INTER_LINEAR); resize(mask, maskPyramid[level], sz, 0, 0, INTER_LINEAR);
copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
BORDER_REFLECT_101+BORDER_ISOLATED);
} }
else else
{ {
resize(imagePyramid[level-1], imagePyramid[level], sz, resize(imagePyramid[level-1], imagePyramid[level], sz, 0, 0, INTER_LINEAR);
1./scaleFactor, 1./scaleFactor, INTER_LINEAR);
if (!mask.empty()) if (!mask.empty())
resize(maskPyramid[level-1], maskPyramid[level], sz, {
1./scaleFactor, 1./scaleFactor, INTER_LINEAR); resize(maskPyramid[level-1], maskPyramid[level], sz, 0, 0, INTER_LINEAR);
copyMakeBorder(imagePyramid[level], temp, border, border, border, border, threshold(maskPyramid[level], maskPyramid[level], 254, 0, THRESH_TOZERO);
BORDER_REFLECT_101+BORDER_ISOLATED); }
} }
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 else
{ {
copyMakeBorder(image, temp, border, border, border, border, copyMakeBorder(image, temp, border, border, border, border,
BORDER_REFLECT_101); BORDER_REFLECT_101);
image.copyTo(imagePyramid[level]);
if( !mask.empty() ) 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 // Pre-compute the keypoints (we keep the best over all scales, so this has to be done beforehand
@@ -1091,3 +1091,51 @@ TEST( Features2d_DescriptorMatcher_FlannBased, regression )
CV_DescriptorMatcherTest test( "descriptor-matcher-flann-based", new FlannBasedMatcher, 0.04f ); CV_DescriptorMatcherTest test( "descriptor-matcher-flann-based", new FlannBasedMatcher, 0.04f );
test.safe_run(); 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:: 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. :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 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. :: 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. 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``. 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 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. :: 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<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`` . :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. 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. :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. 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. :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. 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. :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<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 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. :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. 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. :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. 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`` . :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. 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. :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. 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. :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. 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. :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. 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 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 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`. :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. 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 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 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`. :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. 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. :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. 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. :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. 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. :param a: First spectrum.
@@ -181,7 +181,7 @@ gpu::mulAndScaleSpectrums
----------------------------- -----------------------------
Performs a per-element multiplication of two Fourier spectrums and scales the result. 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. :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. 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). :param src: Source matrix (real or complex).
@@ -238,7 +238,7 @@ The source matrix should be continuous, otherwise reallocation and data copying
gpu::ConvolveBuf 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. :: 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 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. 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=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. :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 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. :param stream: Stream for the asynchronous version.
@@ -290,7 +290,7 @@ Computes a convolution (or cross-correlation) of two images.
gpu::MatchTemplateBuf 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. :: 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 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. :param stream: Stream for the asynchronous version.
@@ -346,7 +346,7 @@ gpu::remap
-------------- --------------
Applies a generic geometrical transformation to an image. 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. :param src: Source image.
@@ -477,7 +477,7 @@ gpu::warpAffine
------------------- -------------------
Applies an affine transformation to an image. 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. :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. 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. :param M: *2x3* transformation matrix.
@@ -521,7 +521,7 @@ gpu::warpPerspective
------------------------ ------------------------
Applies a perspective transformation to an image. 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. :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. 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. :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, 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. :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, 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 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. :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. 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. :param stream: Stream for the asynchronous version.
@@ -757,7 +753,7 @@ gpu::buildWarpCylindricalMaps
----------------------------- -----------------------------
Builds cylindrical warping maps. 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. :param stream: Stream for the asynchronous version.
@@ -767,7 +763,7 @@ gpu::buildWarpSphericalMaps
--------------------------- ---------------------------
Builds spherical warping maps. 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. :param stream: Stream for the asynchronous version.
@@ -47,7 +47,6 @@ Any subsequent API call to this device will reinitialize the device.
gpu::FeatureSet gpu::FeatureSet
--------------- ---------------
.. ocv:class:: gpu::FeatureSet
Class providing GPU computing features. :: Class providing GPU computing features. ::
@@ -74,9 +73,9 @@ Class providing a set of static methods to check what NVIDIA* card architecture
The following method checks whether the module was built with the support of the given feature: The following method checks whether the module was built with the support of the given feature:
.. ocv:function:: static bool gpu::TargetArchs::builtWith(FeatureSet feature) .. ocv:function:: static bool gpu::TargetArchs::builtWith( FeatureSet feature_set )
:param feature: Feature to be checked. See :ocv:class:`gpu::FeatureSet`. :param feature_set: Features to be checked. See :ocv:class:`gpu::FeatureSet`.
There is a set of methods to check whether the module contains intermediate (PTX) or binary GPU code for the given architecture(s): There is a set of methods to check whether the module contains intermediate (PTX) or binary GPU code for the given architecture(s):
@@ -150,7 +149,7 @@ gpu::DeviceInfo::name
------------------------- -------------------------
Returns the device name. Returns the device name.
.. ocv:function:: string gpu::DeviceInfo::name() .. ocv:function:: string gpu::DeviceInfo::name() const
@@ -198,9 +197,9 @@ gpu::DeviceInfo::supports
----------------------------- -----------------------------
Provides information on GPU feature support. Provides information on GPU feature support.
.. ocv:function:: bool gpu::DeviceInfo::supports(FeatureSet feature) .. ocv:function:: bool gpu::DeviceInfo::supports( FeatureSet feature_set ) const
:param feature: Feature to be checked. See :ocv:class:`gpu::FeatureSet`. :param feature_set: Features to be checked. See :ocv:class:`gpu::FeatureSet`.
This function returns ``true`` if the device has the specified GPU feature. Otherwise, it returns ``false`` . This function returns ``true`` if the device has the specified GPU feature. Otherwise, it returns ``false`` .
+1 -1
View File
@@ -32,7 +32,7 @@ By default, the OpenCV GPU module includes:
PTX code for compute capabilities 1.1 and 1.3 (controlled by ``CUDA_ARCH_PTX`` in ``CMake``) PTX code for compute capabilities 1.1 and 1.3 (controlled by ``CUDA_ARCH_PTX`` in ``CMake``)
This means that for devices with CC 1.3 and 2.0 binary images are ready to run. For all newer platforms, the PTX code for 1.3 is JIT'ed to a binary image. For devices with CC 1.1 and 1.2, the PTX for 1.1 is JIT'ed. For devices with CC 1.0, no code is available and the functions throw This means that for devices with CC 1.3 and 2.0 binary images are ready to run. For all newer platforms, the PTX code for 1.3 is JIT'ed to a binary image. For devices with CC 1.1 and 1.2, the PTX for 1.1 is JIT'ed. For devices with CC 1.0, no code is available and the functions throw
:ocv:func:`Exception`. For platforms where JIT compilation is performed first, the run is slow. :ocv:class:`Exception`. For platforms where JIT compilation is performed first, the run is slow.
On a GPU with CC 1.0, you can still compile the GPU module and most of the functions will run flawlessly. To achieve this, add "1.0" to the list of binaries, for example, ``CUDA_ARCH_BIN="1.0 1.3 2.0"`` . The functions that cannot be run on CC 1.0 GPUs throw an exception. On a GPU with CC 1.0, you can still compile the GPU module and most of the functions will run flawlessly. To achieve this, add "1.0" to the list of binaries, for example, ``CUDA_ARCH_BIN="1.0 1.3 2.0"`` . The functions that cannot be run on CC 1.0 GPUs throw an exception.
+2 -2
View File
@@ -7,7 +7,7 @@ Object Detection
gpu::HOGDescriptor gpu::HOGDescriptor
------------------ ------------------
.. ocv:class:: gpu::HOGDescriptor .. ocv:struct:: gpu::HOGDescriptor
The class implements Histogram of Oriented Gradients ([Dalal2005]_) object detector. :: The class implements Histogram of Oriented Gradients ([Dalal2005]_) object detector. ::
@@ -235,7 +235,7 @@ gpu::CascadeClassifier_GPU::CascadeClassifier_GPU
----------------------------------------------------- -----------------------------------------------------
Loads the classifier from a file. Loads the classifier from a file.
.. ocv:function:: gpu::CascadeClassifier_GPU(const string& filename) .. ocv:function:: gpu::CascadeClassifier_GPU::CascadeClassifier_GPU(const string& filename)
:param filename: Name of the file from which the classifier is loaded. Only the old ``haar`` classifier (trained by the ``haar`` training application) and NVIDIA's ``nvbin`` are supported. :param filename: Name of the file from which the classifier is loaded. Only the old ``haar`` classifier (trained by the ``haar`` training application) and NVIDIA's ``nvbin`` are supported.

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